Debian Codegraph @

clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

raw
1 //===- unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.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 //===----------------------------------------------------------------------===//
8
9 #include "TestingSupport.h"
10 #include "clang/AST/Decl.h"
11 #include "clang/AST/ExprCXX.h"
12 #include "clang/AST/Type.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/ASTMatchers/ASTMatchers.h"
15 #include "clang/Analysis/CFG.h"
16 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
17 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
18 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
19 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
20 #include "clang/Analysis/FlowSensitive/DebugSupport.h"
21 #include "clang/Analysis/FlowSensitive/NoopAnalysis.h"
22 #include "clang/Analysis/FlowSensitive/Value.h"
23 #include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
24 #include "clang/Tooling/Tooling.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Testing/ADT/StringMapEntry.h"
31 #include "llvm/Testing/Support/Error.h"
32 #include "gmock/gmock.h"
33 #include "gtest/gtest.h"
34 #include <cassert>
35 #include <memory>
36 #include <optional>
37 #include <ostream>
38 #include <string>
39 #include <utility>
40 #include <vector>
41
42 namespace {
43
44 using namespace clang;
45 using namespace dataflow;
46 using namespace test;
47 using namespace ast_matchers;
48 using llvm::IsStringMapEntry;
49 using ::testing::DescribeMatcher;
50 using ::testing::IsEmpty;
51 using ::testing::NotNull;
52 using ::testing::Test;
53 using ::testing::UnorderedElementsAre;
54
55 class DataflowAnalysisTest : public Test {
56 protected:
57 template <typename AnalysisT>
58 llvm::Expected<std::vector<
59 std::optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>>
60 runAnalysis(llvm::StringRef Code, AnalysisT (*MakeAnalysis)(ASTContext &)) {
61 AST = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++11"});
62
63 auto *Func = selectFirst<FunctionDecl>(
64 "func",
65 match(functionDecl(ast_matchers::hasName("target")).bind("func"),
66 AST->getASTContext()));
67 assert(Func != nullptr);
68
69 ACFG =
70 std::make_unique<AdornedCFG>(llvm::cantFail(AdornedCFG::build(*Func)));
71
72 AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
73 DACtx = std::make_unique<DataflowAnalysisContext>(
74 std::make_unique<WatchedLiteralsSolver>());
75 Environment Env(*DACtx, *Func);
76
77 return runDataflowAnalysis(*ACFG, Analysis, Env);
78 }
79
80 /// Returns the `CFGBlock` containing `S` (and asserts that it exists).
81 const CFGBlock *blockForStmt(const Stmt &S) {
82 const CFGBlock *Block = ACFG->getStmtToBlock().lookup(&S);
83 assert(Block != nullptr);
84 return Block;
85 }
86
87 template <typename StateT>
88 const StateT &
89 blockStateForStmt(const std::vector<std::optional<StateT>> &BlockStates,
90 const Stmt &S) {
91 const std::optional<StateT> &MaybeState =
92 BlockStates[blockForStmt(S)->getBlockID()];
93 assert(MaybeState.has_value());
94 return *MaybeState;
95 }
96
97 /// Returns the first node that matches `Matcher` (and asserts that the match
98 /// was successful, i.e. the returned node is not null).
99 template <typename NodeT, typename MatcherT>
100 const NodeT &matchNode(MatcherT Matcher) {
101 const auto *Node = selectFirst<NodeT>(
102 "node", match(Matcher.bind("node"), AST->getASTContext()));
103 assert(Node != nullptr);
104 return *Node;
105 }
106
107 std::unique_ptr<ASTUnit> AST;
108 std::unique_ptr<AdornedCFG> ACFG;
109 std::unique_ptr<DataflowAnalysisContext> DACtx;
110 };
111
112 TEST_F(DataflowAnalysisTest, NoopAnalysis) {
113 auto BlockStates = llvm::cantFail(
114 runAnalysis<NoopAnalysis>("void target() {}", [](ASTContext &C) {
115 return NoopAnalysis(C,
116 // Don't use builtin transfer function.
117 DataflowAnalysisOptions{std::nullopt});
118 }));
119 EXPECT_EQ(BlockStates.size(), 2u);
120 EXPECT_TRUE(BlockStates[0].has_value());
121 EXPECT_TRUE(BlockStates[1].has_value());
122 }
123
124 // Basic test that `diagnoseFunction` calls the Diagnoser function for the
125 // number of elements expected.
126 TEST_F(DataflowAnalysisTest, DiagnoseFunctionDiagnoserCalledOnEachElement) {
127 std::string Code = R"(void target() { int x = 0; ++x; })";
128 std::unique_ptr<ASTUnit> AST =
129 tooling::buildASTFromCodeWithArgs(Code, {"-std=c++11"});
130
131 auto *Func =
132 cast<FunctionDecl>(findValueDecl(AST->getASTContext(), "target"));
133 auto Diagnoser = [](const CFGElement &Elt, ASTContext &,
134 const TransferStateForDiagnostics<NoopLattice> &) {
135 llvm::SmallVector<std::string> Diagnostics(1);
136 llvm::raw_string_ostream OS(Diagnostics.front());
137 Elt.dumpToStream(OS);
138 return Diagnostics;
139 };
140 auto Result = diagnoseFunction<NoopAnalysis, std::string>(
141 *Func, AST->getASTContext(), Diagnoser);
142 // `diagnoseFunction` provides no guarantees about the order in which elements
143 // are visited, so we use `UnorderedElementsAre`.
144 EXPECT_THAT_EXPECTED(Result, llvm::HasValue(UnorderedElementsAre(
145 "0\n", "int x = 0;\n", "x\n", "++x\n",
146 " (Lifetime ends)\n")));
147 }
148
149 TEST_F(DataflowAnalysisTest, CanAnalyzeStmt) {
150 std::string Code = R"cc(
151 struct S { bool b; };
152 void foo() {
153 S AnS = S{true};
154 }
155 )cc";
156 AST = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++11"});
157 const auto &DeclStatement =
158 matchNode<DeclStmt>(declStmt(hasSingleDecl(varDecl(hasName("AnS")))));
159 const auto &Func = matchNode<FunctionDecl>(functionDecl(hasName("foo")));
160
161 ACFG = std::make_unique<AdornedCFG>(llvm::cantFail(AdornedCFG::build(
162 Func, const_cast<DeclStmt &>(DeclStatement), AST->getASTContext())));
163
164 NoopAnalysis Analysis = NoopAnalysis(AST->getASTContext());
165 DACtx = std::make_unique<DataflowAnalysisContext>(
166 std::make_unique<WatchedLiteralsSolver>());
167 Environment Env(*DACtx, const_cast<DeclStmt &>(DeclStatement));
168
169 llvm::Expected<std::vector<std::optional<DataflowAnalysisState<NoopLattice>>>>
170 Results = runDataflowAnalysis(*ACFG, Analysis, Env);
171
172 ASSERT_THAT_ERROR(Results.takeError(), llvm::Succeeded());
173 const Environment &ExitBlockEnv = Results->front()->Env;
174 BoolValue *BoolFieldValue = cast<BoolValue>(
175 getFieldValue(ExitBlockEnv.get<RecordStorageLocation>(
176 *cast<VarDecl>((*DeclStatement.decl_begin()))),
177 "b", AST->getASTContext(), ExitBlockEnv));
178 EXPECT_TRUE(Env.proves(BoolFieldValue->formula()));
179 }
180
181 // Tests for the statement-to-block map.
182 using StmtToBlockTest = DataflowAnalysisTest;
183
184 TEST_F(StmtToBlockTest, ConditionalOperator) {
185 std::string Code = R"(
186 void target(bool b) {
187 int i = b ? 1 : 0;
188 }
189 )";
190 ASSERT_THAT_ERROR(runAnalysis<NoopAnalysis>(
191 Code, [](ASTContext &C) { return NoopAnalysis(C); })
192 .takeError(),
193 llvm::Succeeded());
194
195 const auto &IDecl = matchNode<DeclStmt>(declStmt(has(varDecl(hasName("i")))));
196 const auto &ConditionalOp =
197 matchNode<ConditionalOperator>(conditionalOperator());
198
199 // The conditional operator should be associated with the same block as the
200 // `DeclStmt` for `i`. (Specifically, the conditional operator should not be
201 // associated with the block for which it is the terminator.)
202 EXPECT_EQ(blockForStmt(IDecl), blockForStmt(ConditionalOp));
203 }
204
205 TEST_F(StmtToBlockTest, LogicalAnd) {
206 std::string Code = R"(
207 void target(bool b1, bool b2) {
208 bool b = b1 && b2;
209 }
210 )";
211 ASSERT_THAT_ERROR(runAnalysis<NoopAnalysis>(
212 Code, [](ASTContext &C) { return NoopAnalysis(C); })
213 .takeError(),
214 llvm::Succeeded());
215
216 const auto &BDecl = matchNode<DeclStmt>(declStmt(has(varDecl(hasName("b")))));
217 const auto &AndOp =
218 matchNode<BinaryOperator>(binaryOperator(hasOperatorName("&&")));
219
220 // The `&&` operator should be associated with the same block as the
221 // `DeclStmt` for `b`. (Specifically, the `&&` operator should not be
222 // associated with the block for which it is the terminator.)
223 EXPECT_EQ(blockForStmt(BDecl), blockForStmt(AndOp));
224 }
225
226 TEST_F(StmtToBlockTest, IfStatementWithLogicalAnd) {
227 std::string Code = R"(
228 void target(bool b1, bool b2) {
229 if (b1 && b2)
230 ;
231 }
232 )";
233 ASSERT_THAT_ERROR(runAnalysis<NoopAnalysis>(
234 Code, [](ASTContext &C) { return NoopAnalysis(C); })
235 .takeError(),
236 llvm::Succeeded());
237
238 const auto &If = matchNode<IfStmt>(ifStmt());
239 const auto &B2 =
240 matchNode<DeclRefExpr>(declRefExpr(to(varDecl(hasName("b2")))));
241 const auto &AndOp =
242 matchNode<BinaryOperator>(binaryOperator(hasOperatorName("&&")));
243
244 // The if statement is the terminator for the block that contains both `b2`
245 // and the `&&` operator (which appears only as a terminator condition, not
246 // as a regular `CFGElement`).
247 const CFGBlock *IfBlock = blockForStmt(If);
248 const CFGBlock *B2Block = blockForStmt(B2);
249 const CFGBlock *AndOpBlock = blockForStmt(AndOp);
250 EXPECT_EQ(IfBlock, B2Block);
251 EXPECT_EQ(IfBlock, AndOpBlock);
252 }
253
254 // Tests that check we discard state for expressions correctly.
255 using DiscardExprStateTest = DataflowAnalysisTest;
256
257 TEST_F(DiscardExprStateTest, WhileStatement) {
258 std::string Code = R"(
259 void foo(int *p);
260 void target(int *p) {
261 while (p != nullptr)
262 foo(p);
263 }
264 )";
265 auto BlockStates = llvm::cantFail(runAnalysis<NoopAnalysis>(
266 Code, [](ASTContext &C) { return NoopAnalysis(C); }));
267
268 const auto &NotEqOp =
269 matchNode<BinaryOperator>(binaryOperator(hasOperatorName("!=")));
270 const auto &CallFoo =
271 matchNode<CallExpr>(callExpr(callee(functionDecl(hasName("foo")))));
272
273 // In the block that evaluates the expression `p != nullptr`, this expression
274 // is associated with a value.
275 const auto &NotEqOpState = blockStateForStmt(BlockStates, NotEqOp);
276 EXPECT_NE(NotEqOpState.Env.getValue(NotEqOp), nullptr);
277
278 // In the block that calls `foo(p)`, the value for `p != nullptr` is discarded
279 // because it is not consumed outside the block it is in.
280 const auto &CallFooState = blockStateForStmt(BlockStates, CallFoo);
281 EXPECT_EQ(CallFooState.Env.getValue(NotEqOp), nullptr);
282 }
283
284 TEST_F(DiscardExprStateTest, BooleanOperator) {
285 std::string Code = R"(
286 void f();
287 void target(bool b1, bool b2) {
288 if (b1 && b2)
289 f();
290 }
291 )";
292 auto BlockStates = llvm::cantFail(runAnalysis<NoopAnalysis>(
293 Code, [](ASTContext &C) { return NoopAnalysis(C); }));
294
295 const auto &AndOp =
296 matchNode<BinaryOperator>(binaryOperator(hasOperatorName("&&")));
297 const auto &CallF =
298 matchNode<CallExpr>(callExpr(callee(functionDecl(hasName("f")))));
299
300 // In the block that evaluates the LHS of the `&&` operator, the LHS is
301 // associated with a value, while the right-hand side is not (unsurprisingly,
302 // as it hasn't been evaluated yet).
303 const auto &LHSState = blockStateForStmt(BlockStates, *AndOp.getLHS());
304 auto *LHSValue = cast<BoolValue>(LHSState.Env.getValue(*AndOp.getLHS()));
305 EXPECT_NE(LHSValue, nullptr);
306 EXPECT_EQ(LHSState.Env.getValue(*AndOp.getRHS()), nullptr);
307
308 // In the block that evaluates the RHS, both the LHS and RHS are associated
309 // with values, as they are both subexpressions of the `&&` operator, which
310 // is evaluated in a later block.
311 const auto &RHSState = blockStateForStmt(BlockStates, *AndOp.getRHS());
312 EXPECT_EQ(RHSState.Env.getValue(*AndOp.getLHS()), LHSValue);
313 auto *RHSValue = RHSState.Env.get<BoolValue>(*AndOp.getRHS());
314 EXPECT_NE(RHSValue, nullptr);
315
316 // In the block that evaluates `b1 && b2`, the `&&` as well as its operands
317 // are associated with values.
318 const auto &AndOpState = blockStateForStmt(BlockStates, AndOp);
319 EXPECT_EQ(AndOpState.Env.getValue(*AndOp.getLHS()), LHSValue);
320 EXPECT_EQ(AndOpState.Env.getValue(*AndOp.getRHS()), RHSValue);
321 EXPECT_EQ(AndOpState.Env.getValue(AndOp),
322 &AndOpState.Env.makeAnd(*LHSValue, *RHSValue));
323
324 // In the block that calls `f()`, none of `b1`, `b2`, or `b1 && b2` should be
325 // associated with values.
326 const auto &CallFState = blockStateForStmt(BlockStates, CallF);
327 EXPECT_EQ(CallFState.Env.getValue(*AndOp.getLHS()), nullptr);
328 EXPECT_EQ(CallFState.Env.getValue(*AndOp.getRHS()), nullptr);
329 EXPECT_EQ(CallFState.Env.getValue(AndOp), nullptr);
330 }
331
332 TEST_F(DiscardExprStateTest, ConditionalOperator) {
333 std::string Code = R"(
334 void f(int*, int);
335 void g();
336 bool cond();
337
338 void target() {
339 int i = 0;
340 if (cond())
341 f(&i, cond() ? 1 : 0);
342 g();
343 }
344 )";
345 auto BlockStates = llvm::cantFail(runAnalysis<NoopAnalysis>(
346 Code, [](ASTContext &C) { return NoopAnalysis(C); }));
347
348 const auto &AddrOfI =
349 matchNode<UnaryOperator>(unaryOperator(hasOperatorName("&")));
350 const auto &CallF =
351 matchNode<CallExpr>(callExpr(callee(functionDecl(hasName("f")))));
352 const auto &CallG =
353 matchNode<CallExpr>(callExpr(callee(functionDecl(hasName("g")))));
354
355 // In the block that evaluates `&i`, it should obviously have a value.
356 const auto &AddrOfIState = blockStateForStmt(BlockStates, AddrOfI);
357 auto *AddrOfIVal = AddrOfIState.Env.get<PointerValue>(AddrOfI);
358 EXPECT_NE(AddrOfIVal, nullptr);
359
360 // Because of the conditional operator, the `f(...)` call is evaluated in a
361 // different block than `&i`, but `&i` still needs to have a value here
362 // because it's a subexpression of the call.
363 const auto &CallFState = blockStateForStmt(BlockStates, CallF);
364 EXPECT_NE(&CallFState, &AddrOfIState);
365 EXPECT_EQ(CallFState.Env.get<PointerValue>(AddrOfI), AddrOfIVal);
366
367 // In the block that calls `g()`, `&i` should no longer be associated with a
368 // value.
369 const auto &CallGState = blockStateForStmt(BlockStates, CallG);
370 EXPECT_EQ(CallGState.Env.get<PointerValue>(AddrOfI), nullptr);
371 }
372
373 struct NonConvergingLattice {
374 int State;
375
376 bool operator==(const NonConvergingLattice &Other) const {
377 return State == Other.State;
378 }
379
380 LatticeJoinEffect join(const NonConvergingLattice &Other) {
381 if (Other.State == 0)
382 return LatticeJoinEffect::Unchanged;
383 State += Other.State;
384 return LatticeJoinEffect::Changed;
385 }
386 };
387
388 class NonConvergingAnalysis
389 : public DataflowAnalysis<NonConvergingAnalysis, NonConvergingLattice> {
390 public:
391 explicit NonConvergingAnalysis(ASTContext &Context)
392 : DataflowAnalysis<NonConvergingAnalysis, NonConvergingLattice>(
393 Context,
394 // Don't apply builtin transfer function.
395 DataflowAnalysisOptions{std::nullopt}) {}
396
397 static NonConvergingLattice initialElement() { return {0}; }
398
399 void transfer(const CFGElement &, NonConvergingLattice &E, Environment &) {
400 ++E.State;
401 }
402 };
403
404 TEST_F(DataflowAnalysisTest, NonConvergingAnalysis) {
405 std::string Code = R"(
406 void target() {
407 while(true) {}
408 }
409 )";
410 auto Res = runAnalysis<NonConvergingAnalysis>(
411 Code, [](ASTContext &C) { return NonConvergingAnalysis(C); });
412 EXPECT_EQ(llvm::toString(Res.takeError()),
413 "maximum number of blocks processed");
414 }
415
416 // Regression test for joins of bool-typed lvalue expressions. The first loop
417 // results in two passes through the code that follows. Each pass results in a
418 // different `StorageLocation` for the pointee of `v`. Then, the second loop
419 // causes a join at the loop head where the two environments map expresssion
420 // `*v` to different `StorageLocation`s.
421 //
422 // An earlier version crashed for this condition (for boolean-typed lvalues), so
423 // this test only verifies that the analysis runs successfully, without
424 // examining any details of the results.
425 TEST_F(DataflowAnalysisTest, JoinBoolLValues) {
426 std::string Code = R"(
427 void target() {
428 for (int x = 1; x; x = 0)
429 (void)x;
430 bool *v;
431 if (*v)
432 for (int x = 1; x; x = 0)
433 (void)x;
434 }
435 )";
436 ASSERT_THAT_ERROR(
437 runAnalysis<NoopAnalysis>(Code,
438 [](ASTContext &C) {
439 auto EnableBuiltIns = DataflowAnalysisOptions{
440 DataflowAnalysisContext::Options{}};
441 return NoopAnalysis(C, EnableBuiltIns);
442 })
443 .takeError(),
444 llvm::Succeeded());
445 }
446
447 struct FunctionCallLattice {
448 using FunctionSet = llvm::SmallSet<std::string, 8>;
449 FunctionSet CalledFunctions;
450
451 bool operator==(const FunctionCallLattice &Other) const {
452 return CalledFunctions == Other.CalledFunctions;
453 }
454
455 LatticeJoinEffect join(const FunctionCallLattice &Other) {
456 if (Other.CalledFunctions.empty())
457 return LatticeJoinEffect::Unchanged;
458 const size_t size_before = CalledFunctions.size();
459 CalledFunctions.insert(Other.CalledFunctions.begin(),
460 Other.CalledFunctions.end());
461 return CalledFunctions.size() == size_before ? LatticeJoinEffect::Unchanged
462 : LatticeJoinEffect::Changed;
463 }
464 };
465
466 std::ostream &operator<<(std::ostream &OS, const FunctionCallLattice &L) {
467 std::string S;
468 llvm::raw_string_ostream ROS(S);
469 llvm::interleaveComma(L.CalledFunctions, ROS);
470 return OS << "{" << S << "}";
471 }
472
473 class FunctionCallAnalysis
474 : public DataflowAnalysis<FunctionCallAnalysis, FunctionCallLattice> {
475 public:
476 explicit FunctionCallAnalysis(ASTContext &Context)
477 : DataflowAnalysis<FunctionCallAnalysis, FunctionCallLattice>(Context) {}
478
479 static FunctionCallLattice initialElement() { return {}; }
480
481 void transfer(const CFGElement &Elt, FunctionCallLattice &E, Environment &) {
482 auto CS = Elt.getAs<CFGStmt>();
483 if (!CS)
484 return;
485 const auto *S = CS->getStmt();
486 if (auto *C = dyn_cast<CallExpr>(S)) {
487 if (auto *F = dyn_cast<FunctionDecl>(C->getCalleeDecl())) {
488 E.CalledFunctions.insert(F->getNameInfo().getAsString());
489 }
490 }
491 }
492 };
493
494 class NoreturnDestructorTest : public Test {
495 protected:
496 template <typename Matcher>
497 void runDataflow(llvm::StringRef Code, Matcher Expectations) {
498 tooling::FileContentMappings FilesContents;
499 FilesContents.push_back(std::make_pair<std::string, std::string>(
500 "noreturn_destructor_test_defs.h", R"(
501 int foo();
502
503 class Fatal {
504 public:
505 ~Fatal() __attribute__((noreturn));
506 int bar();
507 int baz();
508 };
509
510 class NonFatal {
511 public:
512 ~NonFatal();
513 int bar();
514 };
515 )"));
516
517 ASSERT_THAT_ERROR(
518 test::checkDataflow<FunctionCallAnalysis>(
519 AnalysisInputs<FunctionCallAnalysis>(
520 Code, ast_matchers::hasName("target"),
521 [](ASTContext &C, Environment &) {
522 return FunctionCallAnalysis(C);
523 })
524 .withASTBuildArgs({"-fsyntax-only", "-std=c++17"})
525 .withASTBuildVirtualMappedFiles(std::move(FilesContents)),
526 /*VerifyResults=*/
527 [&Expectations](
528 const llvm::StringMap<
529 DataflowAnalysisState<FunctionCallLattice>> &Results,
530 const AnalysisOutputs &) {
531 EXPECT_THAT(Results, Expectations);
532 }),
533 llvm::Succeeded());
534 }
535 };
536
537 MATCHER_P(HoldsFunctionCallLattice, m,
538 ((negation ? "doesn't hold" : "holds") +
539 llvm::StringRef(" a lattice element that ") +
540 DescribeMatcher<FunctionCallLattice>(m))
541 .str()) {
542 return ExplainMatchResult(m, arg.Lattice, result_listener);
543 }
544
545 MATCHER_P(HasCalledFunctions, m,
546 ((negation ? "doesn't hold" : "holds") +
547 llvm::StringRef(" a set of called functions that ") +
548 DescribeMatcher<FunctionCallLattice::FunctionSet>(m))
549 .str()) {
550 return ExplainMatchResult(m, arg.CalledFunctions, result_listener);
551 }
552
553 TEST_F(NoreturnDestructorTest, ConditionalOperatorBothBranchesReturn) {
554 std::string Code = R"(
555 #include "noreturn_destructor_test_defs.h"
556
557 void target(bool b) {
558 int value = b ? foo() : NonFatal().bar();
559 (void)0;
560 // [[p]]
561 }
562 )";
563 runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
564 "p", HoldsFunctionCallLattice(HasCalledFunctions(
565 UnorderedElementsAre("foo", "bar"))))));
566 }
567
568 TEST_F(NoreturnDestructorTest, ConditionalOperatorLeftBranchReturns) {
569 std::string Code = R"(
570 #include "noreturn_destructor_test_defs.h"
571
572 void target(bool b) {
573 int value = b ? foo() : Fatal().bar();
574 (void)0;
575 // [[p]]
576 }
577 )";
578 runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
579 "p", HoldsFunctionCallLattice(HasCalledFunctions(
580 UnorderedElementsAre("foo"))))));
581 }
582
583 TEST_F(NoreturnDestructorTest,
584 ConditionalOperatorConstantCondition_LeftBranchReturns) {
585 std::string Code = R"(
586 #include "noreturn_destructor_test_defs.h"
587
588 void target() {
589 int value = true ? foo() : Fatal().bar();
590 (void)0;
591 // [[p]]
592 }
593 )";
594 runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
595 "p", HoldsFunctionCallLattice(HasCalledFunctions(
596 UnorderedElementsAre("foo"))))));
597 }
598
599 TEST_F(NoreturnDestructorTest, ConditionalOperatorRightBranchReturns) {
600 std::string Code = R"(
601 #include "noreturn_destructor_test_defs.h"
602
603 void target(bool b) {
604 int value = b ? Fatal().bar() : foo();
605 (void)0;
606 // [[p]]
607 }
608 )";
609 runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
610 "p", HoldsFunctionCallLattice(HasCalledFunctions(
611 UnorderedElementsAre("foo"))))));
612 }
613
614 TEST_F(NoreturnDestructorTest,
615 ConditionalOperatorConstantCondition_RightBranchReturns) {
616 std::string Code = R"(
617 #include "noreturn_destructor_test_defs.h"
618
619 void target() {
620 int value = false ? Fatal().bar() : foo();
621 (void)0;
622 // [[p]]
623 }
624 )";
625 runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
626 "p", HoldsFunctionCallLattice(HasCalledFunctions(
627 UnorderedElementsAre("foo"))))));
628 }
629
630 TEST_F(NoreturnDestructorTest, ConditionalOperatorNestedBranchesDoNotReturn) {
631 std::string Code = R"(
632 #include "noreturn_destructor_test_defs.h"
633
634 void target(bool b1, bool b2) {
635 int value = b1 ? foo() : (b2 ? Fatal().bar() : Fatal().baz());
636 (void)0;
637 // [[p]]
638 }
639 )";
640 runDataflow(Code, IsEmpty());
641 // FIXME: Called functions at point `p` should contain "foo".
642 }
643
644 TEST_F(NoreturnDestructorTest, ConditionalOperatorNestedBranchReturns) {
645 std::string Code = R"(
646 #include "noreturn_destructor_test_defs.h"
647
648 void target(bool b1, bool b2) {
649 int value = b1 ? Fatal().bar() : (b2 ? Fatal().baz() : foo());
650 (void)0;
651 // [[p]]
652 }
653 )";
654 runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
655 "p", HoldsFunctionCallLattice(HasCalledFunctions(
656 UnorderedElementsAre("baz", "foo"))))));
657 // FIXME: Called functions at point `p` should contain only "foo".
658 }
659
660 // Models an analysis that uses flow conditions.
661 class SpecialBoolAnalysis final
662 : public DataflowAnalysis<SpecialBoolAnalysis, NoopLattice> {
663 public:
664 explicit SpecialBoolAnalysis(ASTContext &Context, Environment &Env)
665 : DataflowAnalysis<SpecialBoolAnalysis, NoopLattice>(Context) {
666 Env.getDataflowAnalysisContext().setSyntheticFieldCallback(
667 [](QualType Ty) -> llvm::StringMap<QualType> {
668 RecordDecl *RD = Ty->getAsRecordDecl();
669 if (RD == nullptr || RD->getIdentifier() == nullptr ||
670 RD->getName() != "SpecialBool")
671 return {};
672 return {{"is_set", RD->getASTContext().BoolTy}};
673 });
674 }
675
676 static NoopLattice initialElement() { return {}; }
677
678 void transfer(const CFGElement &Elt, NoopLattice &, Environment &Env) {
679 auto CS = Elt.getAs<CFGStmt>();
680 if (!CS)
681 return;
682 const auto *S = CS->getStmt();
683 auto SpecialBoolRecordDecl = recordDecl(hasName("SpecialBool"));
684 auto HasSpecialBoolType = hasType(SpecialBoolRecordDecl);
685
686 if (const auto *E = selectFirst<CXXConstructExpr>(
687 "call", match(cxxConstructExpr(HasSpecialBoolType).bind("call"), *S,
688 getASTContext()))) {
689 Env.setValue(Env.getResultObjectLocation(*E).getSyntheticField("is_set"),
690 Env.getBoolLiteralValue(false));
691 } else if (const auto *E = selectFirst<CXXMemberCallExpr>(
692 "call", match(cxxMemberCallExpr(callee(cxxMethodDecl(ofClass(
693 SpecialBoolRecordDecl))))
694 .bind("call"),
695 *S, getASTContext()))) {
696 if (RecordStorageLocation *ObjectLoc = getImplicitObjectLocation(*E, Env))
697 Env.setValue(ObjectLoc->getSyntheticField("is_set"),
698 Env.getBoolLiteralValue(true));
699 }
700 }
701 };
702
703 class JoinFlowConditionsTest : public Test {
704 protected:
705 template <typename Matcher>
706 void runDataflow(llvm::StringRef Code, Matcher Match) {
707 ASSERT_THAT_ERROR(
708 test::checkDataflow<SpecialBoolAnalysis>(
709 AnalysisInputs<SpecialBoolAnalysis>(
710 Code, ast_matchers::hasName("target"),
711 [](ASTContext &Context, Environment &Env) {
712 return SpecialBoolAnalysis(Context, Env);
713 })
714 .withASTBuildArgs({"-fsyntax-only", "-std=c++17"}),
715 /*VerifyResults=*/[&Match](const llvm::StringMap<
716 DataflowAnalysisState<NoopLattice>>
717 &Results,
718 const AnalysisOutputs
719 &AO) { Match(Results, AO.ASTCtx); }),
720 llvm::Succeeded());
721 }
722 };
723
724 TEST_F(JoinFlowConditionsTest, JoinDistinctButProvablyEquivalentValues) {
725 std::string Code = R"(
726 struct SpecialBool {
727 SpecialBool() = default;
728 void set();
729 };
730
731 void target(bool Cond) {
732 SpecialBool Foo;
733 /*[[p1]]*/
734 if (Cond) {
735 Foo.set();
736 /*[[p2]]*/
737 } else {
738 Foo.set();
739 /*[[p3]]*/
740 }
741 (void)0;
742 /*[[p4]]*/
743 }
744 )";
745 runDataflow(
746 Code,
747 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
748 ASTContext &ASTCtx) {
749 ASSERT_THAT(Results.keys(),
750 UnorderedElementsAre("p1", "p2", "p3", "p4"));
751 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
752 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
753 const Environment &Env3 = getEnvironmentAtAnnotation(Results, "p3");
754 const Environment &Env4 = getEnvironmentAtAnnotation(Results, "p4");
755
756 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
757 ASSERT_THAT(FooDecl, NotNull());
758
759 auto GetFoo = [FooDecl](const Environment &Env) -> const Formula & {
760 auto *Loc =
761 cast<RecordStorageLocation>(Env.getStorageLocation(*FooDecl));
762 return cast<BoolValue>(Env.getValue(Loc->getSyntheticField("is_set")))
763 ->formula();
764 };
765
766 EXPECT_FALSE(Env1.proves(GetFoo(Env1)));
767 EXPECT_TRUE(Env2.proves(GetFoo(Env2)));
768 EXPECT_TRUE(Env3.proves(GetFoo(Env3)));
769 EXPECT_TRUE(Env4.proves(GetFoo(Env4)));
770 });
771 }
772
773 class NullPointerAnalysis final
774 : public DataflowAnalysis<NullPointerAnalysis, NoopLattice> {
775 public:
776 explicit NullPointerAnalysis(ASTContext &Context)
777 : DataflowAnalysis<NullPointerAnalysis, NoopLattice>(Context) {}
778
779 static NoopLattice initialElement() { return {}; }
780
781 void transfer(const CFGElement &Elt, NoopLattice &, Environment &Env) {
782 auto CS = Elt.getAs<CFGStmt>();
783 if (!CS)
784 return;
785 const Stmt *S = CS->getStmt();
786 const Expr *E = dyn_cast<Expr>(S);
787 if (!E)
788 return;
789
790 if (!E->getType()->isPointerType())
791 return;
792
793 // Make sure we have a `PointerValue` for `E`.
794 auto *PtrVal = cast_or_null<PointerValue>(Env.getValue(*E));
795 if (PtrVal == nullptr) {
796 PtrVal = cast<PointerValue>(Env.createValue(E->getType()));
797 Env.setValue(*E, *PtrVal);
798 }
799
800 if (auto *Cast = dyn_cast<ImplicitCastExpr>(E);
801 Cast && Cast->getCastKind() == CK_NullToPointer)
802 PtrVal->setProperty("is_null", Env.getBoolLiteralValue(true));
803 else if (auto *Op = dyn_cast<UnaryOperator>(E);
804 Op && Op->getOpcode() == UO_AddrOf)
805 PtrVal->setProperty("is_null", Env.getBoolLiteralValue(false));
806 }
807
808 ComparisonResult compare(QualType Type, const Value &Val1,
809 const Environment &Env1, const Value &Val2,
810 const Environment &Env2) override {
811 // Nothing to say about a value that is not a pointer.
812 if (!Type->isPointerType())
813 return ComparisonResult::Unknown;
814
815 auto *Prop1 = Val1.getProperty("is_null");
816 auto *Prop2 = Val2.getProperty("is_null");
817 assert(Prop1 != nullptr && Prop2 != nullptr);
818 return areEquivalentValues(*Prop1, *Prop2) ? ComparisonResult::Same
819 : ComparisonResult::Different;
820 }
821
822 void join(QualType Type, const Value &Val1, const Environment &Env1,
823 const Value &Val2, const Environment &Env2, Value &JoinedVal,
824 Environment &JoinedEnv) override {
825 // Nothing to say about a value that is not a pointer...
826 if (!Type->isPointerType())
827 return;
828
829 // ... or, a pointer without the `is_null` property.
830 auto *IsNull1 = cast_or_null<BoolValue>(Val1.getProperty("is_null"));
831 auto *IsNull2 = cast_or_null<BoolValue>(Val2.getProperty("is_null"));
832 if (IsNull1 == nullptr || IsNull2 == nullptr)
833 return;
834
835 if (IsNull1 == IsNull2)
836 JoinedVal.setProperty("is_null", *IsNull1);
837 else
838 JoinedVal.setProperty("is_null", JoinedEnv.makeTopBoolValue());
839 }
840
841 std::optional<WidenResult> widen(QualType Type, Value &Prev,
842 const Environment &PrevEnv, Value &Current,
843 Environment &CurrentEnv) override {
844 switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) {
845 case ComparisonResult::Same:
846 return WidenResult{&Current, LatticeJoinEffect::Unchanged};
847 case ComparisonResult::Different: {
848 auto &CurPtr = cast<PointerValue>(Current);
849 auto &WidenedPtr =
850 CurrentEnv.create<PointerValue>(CurPtr.getPointeeLoc());
851 WidenedPtr.setProperty("is_null", CurrentEnv.makeTopBoolValue());
852 return WidenResult{&WidenedPtr, LatticeJoinEffect::Changed};
853 }
854 case ComparisonResult::Unknown:
855 return std::nullopt;
856 }
857 llvm_unreachable("all cases in switch covered");
858 }
859 };
860
861 class WideningTest : public Test {
862 protected:
863 template <typename Matcher>
864 void runDataflow(llvm::StringRef Code, Matcher Match) {
865 ASSERT_THAT_ERROR(
866 checkDataflow<NullPointerAnalysis>(
867 AnalysisInputs<NullPointerAnalysis>(
868 Code, ast_matchers::hasName("target"),
869 [](ASTContext &Context, Environment &Env) {
870 return NullPointerAnalysis(Context);
871 })
872 .withASTBuildArgs({"-fsyntax-only", "-std=c++17"}),
873 /*VerifyResults=*/[&Match](const llvm::StringMap<
874 DataflowAnalysisState<NoopLattice>>
875 &Results,
876 const AnalysisOutputs
877 &AO) { Match(Results, AO.ASTCtx); }),
878 llvm::Succeeded());
879 }
880 };
881
882 TEST_F(WideningTest, JoinDistinctValuesWithDistinctProperties) {
883 std::string Code = R"(
884 void target(bool Cond) {
885 int *Foo = nullptr;
886 int i = 0;
887 /*[[p1]]*/
888 if (Cond) {
889 Foo = &i;
890 /*[[p2]]*/
891 }
892 (void)0;
893 /*[[p3]]*/
894 }
895 )";
896 runDataflow(
897 Code,
898 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
899 ASTContext &ASTCtx) {
900 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
901 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
902 const Environment &Env3 = getEnvironmentAtAnnotation(Results, "p3");
903
904 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
905 ASSERT_THAT(FooDecl, NotNull());
906
907 auto GetFooValue = [FooDecl](const Environment &Env) {
908 return Env.getValue(*FooDecl);
909 };
910
911 EXPECT_EQ(GetFooValue(Env1)->getProperty("is_null"),
912 &Env1.getBoolLiteralValue(true));
913 EXPECT_EQ(GetFooValue(Env2)->getProperty("is_null"),
914 &Env2.getBoolLiteralValue(false));
915 EXPECT_TRUE(
916 isa<TopBoolValue>(GetFooValue(Env3)->getProperty("is_null")));
917 });
918 }
919
920 TEST_F(WideningTest, JoinDistinctValuesWithSameProperties) {
921 std::string Code = R"(
922 void target(bool Cond) {
923 int *Foo = nullptr;
924 int i1 = 0;
925 int i2 = 0;
926 /*[[p1]]*/
927 if (Cond) {
928 Foo = &i1;
929 /*[[p2]]*/
930 } else {
931 Foo = &i2;
932 /*[[p3]]*/
933 }
934 (void)0;
935 /*[[p4]]*/
936 }
937 )";
938 runDataflow(
939 Code,
940 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
941 ASTContext &ASTCtx) {
942 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
943 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
944 const Environment &Env3 = getEnvironmentAtAnnotation(Results, "p3");
945 const Environment &Env4 = getEnvironmentAtAnnotation(Results, "p4");
946
947 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
948 ASSERT_THAT(FooDecl, NotNull());
949
950 auto GetFooValue = [FooDecl](const Environment &Env) {
951 return Env.getValue(*FooDecl);
952 };
953
954 EXPECT_EQ(GetFooValue(Env1)->getProperty("is_null"),
955 &Env1.getBoolLiteralValue(true));
956 EXPECT_EQ(GetFooValue(Env2)->getProperty("is_null"),
957 &Env2.getBoolLiteralValue(false));
958 EXPECT_EQ(GetFooValue(Env3)->getProperty("is_null"),
959 &Env3.getBoolLiteralValue(false));
960 EXPECT_EQ(GetFooValue(Env4)->getProperty("is_null"),
961 &Env4.getBoolLiteralValue(false));
962 });
963 }
964
965 TEST_F(WideningTest, DistinctPointersToTheSameLocationAreEquivalent) {
966 std::string Code = R"(
967 void target(int Foo, bool Cond) {
968 int *Bar = &Foo;
969 while (Cond) {
970 Bar = &Foo;
971 }
972 (void)0;
973 // [[p]]
974 }
975 )";
976 runDataflow(
977 Code,
978 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
979 ASTContext &ASTCtx) {
980 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
981 const auto &FooLoc =
982 getLocForDecl<ScalarStorageLocation>(ASTCtx, Env, "Foo");
983 const auto &BarVal = getValueForDecl<PointerValue>(ASTCtx, Env, "Bar");
984 EXPECT_EQ(&BarVal.getPointeeLoc(), &FooLoc);
985 });
986 }
987
988 TEST_F(WideningTest, DistinctValuesWithSamePropertiesAreEquivalent) {
989 std::string Code = R"(
990 void target(bool Cond) {
991 int *Foo;
992 int i1 = 0;
993 int i2 = 0;
994 Foo = &i1;
995 while (Cond) {
996 Foo = &i2;
997 }
998 (void)0;
999 /*[[p]]*/
1000 }
1001 )";
1002 runDataflow(
1003 Code,
1004 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1005 ASTContext &ASTCtx) {
1006 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1007 const auto &FooVal = getValueForDecl<Value>(ASTCtx, Env, "Foo");
1008 EXPECT_EQ(FooVal.getProperty("is_null"),
1009 &Env.getBoolLiteralValue(false));
1010 });
1011 }
1012
1013 TEST_F(WideningTest, DistinctValuesWithDifferentPropertiesWidenedToTop) {
1014 std::string Code = R"(
1015 void target(bool Cond) {
1016 int *Foo;
1017 int i = 0;
1018 Foo = nullptr;
1019 while (Cond) {
1020 Foo = &i;
1021 }
1022 (void)0;
1023 /*[[p]]*/
1024 }
1025 )";
1026 runDataflow(
1027 Code,
1028 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1029 ASTContext &ASTCtx) {
1030 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1031 const auto &FooVal = getValueForDecl<Value>(ASTCtx, Env, "Foo");
1032 ASSERT_THAT(FooVal.getProperty("is_null"), NotNull());
1033 EXPECT_TRUE(areEquivalentValues(*FooVal.getProperty("is_null"),
1034 Env.makeTopBoolValue()));
1035 });
1036 }
1037
1038 class FlowConditionTest : public Test {
1039 protected:
1040 template <typename Matcher>
1041 void runDataflow(llvm::StringRef Code, Matcher Match) {
1042 ASSERT_THAT_ERROR(
1043 checkDataflow<NoopAnalysis>(
1044 AnalysisInputs<NoopAnalysis>(
1045 Code, ast_matchers::hasName("target"),
1046 [](ASTContext &Context, Environment &Env) {
1047 return NoopAnalysis(Context);
1048 })
1049 .withASTBuildArgs({"-fsyntax-only", "-std=c++17"}),
1050 /*VerifyResults=*/[&Match](const llvm::StringMap<
1051 DataflowAnalysisState<NoopLattice>>
1052 &Results,
1053 const AnalysisOutputs
1054 &AO) { Match(Results, AO.ASTCtx); }),
1055 llvm::Succeeded());
1056 }
1057 };
1058
1059 TEST_F(FlowConditionTest, IfStmtSingleVar) {
1060 std::string Code = R"(
1061 void target(bool Foo) {
1062 if (Foo) {
1063 (void)0;
1064 /*[[p1]]*/
1065 } else {
1066 (void)1;
1067 /*[[p2]]*/
1068 }
1069 }
1070 )";
1071 runDataflow(
1072 Code,
1073 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1074 ASTContext &ASTCtx) {
1075 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1076 ASSERT_THAT(FooDecl, NotNull());
1077
1078 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1079
1080 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1081 auto &FooVal1 = cast<BoolValue>(Env1.getValue(*FooDecl))->formula();
1082 EXPECT_TRUE(Env1.proves(FooVal1));
1083
1084 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1085 auto &FooVal2 = cast<BoolValue>(Env2.getValue(*FooDecl))->formula();
1086 EXPECT_FALSE(Env2.proves(FooVal2));
1087 });
1088 }
1089
1090 TEST_F(FlowConditionTest, IfStmtSingleNegatedVar) {
1091 std::string Code = R"(
1092 void target(bool Foo) {
1093 if (!Foo) {
1094 (void)0;
1095 /*[[p1]]*/
1096 } else {
1097 (void)1;
1098 /*[[p2]]*/
1099 }
1100 }
1101 )";
1102 runDataflow(
1103 Code,
1104 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1105 ASTContext &ASTCtx) {
1106 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1107 ASSERT_THAT(FooDecl, NotNull());
1108
1109 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1110
1111 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1112 auto &FooVal1 = cast<BoolValue>(Env1.getValue(*FooDecl))->formula();
1113 EXPECT_FALSE(Env1.proves(FooVal1));
1114
1115 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1116 auto &FooVal2 = cast<BoolValue>(Env2.getValue(*FooDecl))->formula();
1117 EXPECT_TRUE(Env2.proves(FooVal2));
1118 });
1119 }
1120
1121 TEST_F(FlowConditionTest, WhileStmt) {
1122 std::string Code = R"(
1123 void target(bool Foo) {
1124 while (Foo) {
1125 (void)0;
1126 /*[[p]]*/
1127 }
1128 }
1129 )";
1130 runDataflow(
1131 Code,
1132 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1133 ASTContext &ASTCtx) {
1134 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1135 ASSERT_THAT(FooDecl, NotNull());
1136
1137 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
1138 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1139
1140 auto &FooVal = cast<BoolValue>(Env.getValue(*FooDecl))->formula();
1141 EXPECT_TRUE(Env.proves(FooVal));
1142 });
1143 }
1144
1145 TEST_F(FlowConditionTest, WhileStmtWithAssignmentInCondition) {
1146 std::string Code = R"(
1147 void target(bool Foo) {
1148 // This test checks whether the analysis preserves the connection between
1149 // the value of `Foo` and the assignment expression, despite widening.
1150 // The equality operator generates a fresh boolean variable on each
1151 // interpretation, which forces use of widening.
1152 while ((Foo = (3 == 4))) {
1153 (void)0;
1154 /*[[p]]*/
1155 }
1156 }
1157 )";
1158 runDataflow(
1159 Code,
1160 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1161 ASTContext &ASTCtx) {
1162 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1163 auto &FooVal = getValueForDecl<BoolValue>(ASTCtx, Env, "Foo").formula();
1164 EXPECT_TRUE(Env.proves(FooVal));
1165 });
1166 }
1167
1168 TEST_F(FlowConditionTest, Conjunction) {
1169 std::string Code = R"(
1170 void target(bool Foo, bool Bar) {
1171 if (Foo && Bar) {
1172 (void)0;
1173 /*[[p1]]*/
1174 } else {
1175 (void)1;
1176 /*[[p2]]*/
1177 }
1178 }
1179 )";
1180 runDataflow(Code, [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>>
1181 &Results,
1182 ASTContext &ASTCtx) {
1183 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1184 ASSERT_THAT(FooDecl, NotNull());
1185
1186 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
1187 ASSERT_THAT(BarDecl, NotNull());
1188
1189 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1190
1191 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1192 auto &FooVal1 = cast<BoolValue>(Env1.getValue(*FooDecl))->formula();
1193 auto &BarVal1 = cast<BoolValue>(Env1.getValue(*BarDecl))->formula();
1194 EXPECT_TRUE(Env1.proves(FooVal1));
1195 EXPECT_TRUE(Env1.proves(BarVal1));
1196
1197 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1198 auto &FooVal2 = cast<BoolValue>(Env2.getValue(*FooDecl))->formula();
1199 auto &BarVal2 = cast<BoolValue>(Env2.getValue(*BarDecl))->formula();
1200 EXPECT_FALSE(Env2.proves(FooVal2));
1201 EXPECT_FALSE(Env2.proves(BarVal2));
1202 });
1203 }
1204
1205 TEST_F(FlowConditionTest, Disjunction) {
1206 std::string Code = R"(
1207 void target(bool Foo, bool Bar) {
1208 if (Foo || Bar) {
1209 (void)0;
1210 /*[[p1]]*/
1211 } else {
1212 (void)1;
1213 /*[[p2]]*/
1214 }
1215 }
1216 )";
1217 runDataflow(Code, [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>>
1218 &Results,
1219 ASTContext &ASTCtx) {
1220 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1221 ASSERT_THAT(FooDecl, NotNull());
1222
1223 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
1224 ASSERT_THAT(BarDecl, NotNull());
1225
1226 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1227
1228 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1229 auto &FooVal1 = cast<BoolValue>(Env1.getValue(*FooDecl))->formula();
1230 auto &BarVal1 = cast<BoolValue>(Env1.getValue(*BarDecl))->formula();
1231 EXPECT_FALSE(Env1.proves(FooVal1));
1232 EXPECT_FALSE(Env1.proves(BarVal1));
1233
1234 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1235 auto &FooVal2 = cast<BoolValue>(Env2.getValue(*FooDecl))->formula();
1236 auto &BarVal2 = cast<BoolValue>(Env2.getValue(*BarDecl))->formula();
1237 EXPECT_FALSE(Env2.proves(FooVal2));
1238 EXPECT_FALSE(Env2.proves(BarVal2));
1239 });
1240 }
1241
1242 TEST_F(FlowConditionTest, NegatedConjunction) {
1243 std::string Code = R"(
1244 void target(bool Foo, bool Bar) {
1245 if (!(Foo && Bar)) {
1246 (void)0;
1247 /*[[p1]]*/
1248 } else {
1249 (void)1;
1250 /*[[p2]]*/
1251 }
1252 }
1253 )";
1254 runDataflow(Code, [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>>
1255 &Results,
1256 ASTContext &ASTCtx) {
1257 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1258 ASSERT_THAT(FooDecl, NotNull());
1259
1260 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
1261 ASSERT_THAT(BarDecl, NotNull());
1262
1263 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1264
1265 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1266 auto &FooVal1 = cast<BoolValue>(Env1.getValue(*FooDecl))->formula();
1267 auto &BarVal1 = cast<BoolValue>(Env1.getValue(*BarDecl))->formula();
1268 EXPECT_FALSE(Env1.proves(FooVal1));
1269 EXPECT_FALSE(Env1.proves(BarVal1));
1270
1271 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1272 auto &FooVal2 = cast<BoolValue>(Env2.getValue(*FooDecl))->formula();
1273 auto &BarVal2 = cast<BoolValue>(Env2.getValue(*BarDecl))->formula();
1274 EXPECT_TRUE(Env2.proves(FooVal2));
1275 EXPECT_TRUE(Env2.proves(BarVal2));
1276 });
1277 }
1278
1279 TEST_F(FlowConditionTest, DeMorgan) {
1280 std::string Code = R"(
1281 void target(bool Foo, bool Bar) {
1282 if (!(!Foo || !Bar)) {
1283 (void)0;
1284 /*[[p1]]*/
1285 } else {
1286 (void)1;
1287 /*[[p2]]*/
1288 }
1289 }
1290 )";
1291 runDataflow(Code, [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>>
1292 &Results,
1293 ASTContext &ASTCtx) {
1294 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1295 ASSERT_THAT(FooDecl, NotNull());
1296
1297 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
1298 ASSERT_THAT(BarDecl, NotNull());
1299
1300 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1301
1302 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1303 auto &FooVal1 = cast<BoolValue>(Env1.getValue(*FooDecl))->formula();
1304 auto &BarVal1 = cast<BoolValue>(Env1.getValue(*BarDecl))->formula();
1305 EXPECT_TRUE(Env1.proves(FooVal1));
1306 EXPECT_TRUE(Env1.proves(BarVal1));
1307
1308 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1309 auto &FooVal2 = cast<BoolValue>(Env2.getValue(*FooDecl))->formula();
1310 auto &BarVal2 = cast<BoolValue>(Env2.getValue(*BarDecl))->formula();
1311 EXPECT_FALSE(Env2.proves(FooVal2));
1312 EXPECT_FALSE(Env2.proves(BarVal2));
1313 });
1314 }
1315
1316 TEST_F(FlowConditionTest, Join) {
1317 std::string Code = R"(
1318 void target(bool Foo, bool Bar) {
1319 if (Bar) {
1320 if (!Foo)
1321 return;
1322 } else {
1323 if (!Foo)
1324 return;
1325 }
1326 (void)0;
1327 /*[[p]]*/
1328 }
1329 )";
1330 runDataflow(
1331 Code,
1332 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1333 ASTContext &ASTCtx) {
1334 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
1335
1336 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1337 ASSERT_THAT(FooDecl, NotNull());
1338
1339 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1340 auto &FooVal = cast<BoolValue>(Env.getValue(*FooDecl))->formula();
1341 EXPECT_TRUE(Env.proves(FooVal));
1342 });
1343 }
1344
1345 // Verifies that flow conditions are properly constructed even when the
1346 // condition is not meaningfully interpreted.
1347 //
1348 // Note: currently, arbitrary function calls are uninterpreted, so the test
1349 // exercises this case. If and when we change that, this test will not add to
1350 // coverage (although it may still test a valuable case).
1351 TEST_F(FlowConditionTest, OpaqueFlowConditionJoinsToOpaqueBool) {
1352 std::string Code = R"(
1353 bool foo();
1354
1355 void target() {
1356 bool Bar = true;
1357 if (foo())
1358 Bar = false;
1359 (void)0;
1360 /*[[p]]*/
1361 }
1362 )";
1363 runDataflow(
1364 Code,
1365 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1366 ASTContext &ASTCtx) {
1367 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
1368 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1369
1370 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
1371 ASSERT_THAT(BarDecl, NotNull());
1372
1373 auto &BarVal = cast<BoolValue>(Env.getValue(*BarDecl))->formula();
1374
1375 EXPECT_FALSE(Env.proves(BarVal));
1376 });
1377 }
1378
1379 // Verifies that flow conditions are properly constructed even when the
1380 // condition is not meaningfully interpreted.
1381 //
1382 // Note: currently, fields with recursive type calls are uninterpreted (beneath
1383 // the first instance), so the test exercises this case. If and when we change
1384 // that, this test will not add to coverage (although it may still test a
1385 // valuable case).
1386 TEST_F(FlowConditionTest, OpaqueFieldFlowConditionJoinsToOpaqueBool) {
1387 std::string Code = R"(
1388 struct Rec {
1389 Rec* Next;
1390 };
1391
1392 struct Foo {
1393 Rec* X;
1394 };
1395
1396 void target(Foo F) {
1397 bool Bar = true;
1398 if (F.X->Next)
1399 Bar = false;
1400 (void)0;
1401 /*[[p]]*/
1402 }
1403 )";
1404 runDataflow(
1405 Code,
1406 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1407 ASTContext &ASTCtx) {
1408 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
1409 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1410
1411 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
1412 ASSERT_THAT(BarDecl, NotNull());
1413
1414 auto &BarVal = cast<BoolValue>(Env.getValue(*BarDecl))->formula();
1415
1416 EXPECT_FALSE(Env.proves(BarVal));
1417 });
1418 }
1419
1420 // Verifies that flow conditions are properly constructed even when the
1421 // condition is not meaningfully interpreted. Adds to above by nesting the
1422 // interestnig case inside a normal branch. This protects against degenerate
1423 // solutions which only test for empty flow conditions, for example.
1424 TEST_F(FlowConditionTest, OpaqueFlowConditionInsideBranchJoinsToOpaqueBool) {
1425 std::string Code = R"(
1426 bool foo();
1427
1428 void target(bool Cond) {
1429 bool Bar = true;
1430 if (Cond) {
1431 if (foo())
1432 Bar = false;
1433 (void)0;
1434 /*[[p]]*/
1435 }
1436 }
1437 )";
1438 runDataflow(
1439 Code,
1440 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1441 ASTContext &ASTCtx) {
1442 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
1443 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1444
1445 const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
1446 ASSERT_THAT(BarDecl, NotNull());
1447
1448 auto &BarVal = cast<BoolValue>(Env.getValue(*BarDecl))->formula();
1449
1450 EXPECT_FALSE(Env.proves(BarVal));
1451 });
1452 }
1453
1454 TEST_F(FlowConditionTest, PointerToBoolImplicitCast) {
1455 std::string Code = R"(
1456 void target(int *Ptr) {
1457 bool Foo = false;
1458 if (Ptr) {
1459 Foo = true;
1460 /*[[p1]]*/
1461 }
1462
1463 (void)0;
1464 /*[[p2]]*/
1465 }
1466 )";
1467 runDataflow(
1468 Code,
1469 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1470 ASTContext &ASTCtx) {
1471 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1472
1473 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
1474 ASSERT_THAT(FooDecl, NotNull());
1475
1476 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1477 auto &FooVal1 = cast<BoolValue>(Env1.getValue(*FooDecl))->formula();
1478 EXPECT_TRUE(Env1.proves(FooVal1));
1479
1480 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1481 auto &FooVal2 = cast<BoolValue>(Env2.getValue(*FooDecl))->formula();
1482 EXPECT_FALSE(Env2.proves(FooVal2));
1483 });
1484 }
1485
1486 class TopAnalysis final : public DataflowAnalysis<TopAnalysis, NoopLattice> {
1487 public:
1488 explicit TopAnalysis(ASTContext &Context)
1489 : DataflowAnalysis<TopAnalysis, NoopLattice>(Context) {}
1490
1491 static NoopLattice initialElement() { return {}; }
1492
1493 void transfer(const CFGElement &Elt, NoopLattice &, Environment &Env) {
1494 auto CS = Elt.getAs<CFGStmt>();
1495 if (!CS)
1496 return;
1497 const Stmt *S = CS->getStmt();
1498 SmallVector<BoundNodes, 1> Matches =
1499 match(callExpr(callee(functionDecl(hasName("makeTop")))).bind("top"),
1500 *S, getASTContext());
1501 if (const auto *E = selectFirst<CallExpr>("top", Matches)) {
1502 Env.setValue(*E, Env.makeTopBoolValue());
1503 }
1504 }
1505
1506 ComparisonResult compare(QualType Type, const Value &Val1,
1507 const Environment &Env1, const Value &Val2,
1508 const Environment &Env2) override {
1509 // Changes to a sound approximation, which allows us to test whether we can
1510 // (soundly) converge for some loops.
1511 return ComparisonResult::Unknown;
1512 }
1513 };
1514
1515 class TopTest : public Test {
1516 protected:
1517 template <typename Matcher>
1518 void runDataflow(llvm::StringRef Code, Matcher VerifyResults) {
1519 ASSERT_THAT_ERROR(
1520 checkDataflow<TopAnalysis>(
1521 AnalysisInputs<TopAnalysis>(
1522 Code, ast_matchers::hasName("target"),
1523 [](ASTContext &Context, Environment &Env) {
1524 return TopAnalysis(Context);
1525 })
1526 .withASTBuildArgs({"-fsyntax-only", "-std=c++17"}),
1527 VerifyResults),
1528 llvm::Succeeded());
1529 }
1530 };
1531
1532 // Tests that when Top is unused it remains Top.
1533 TEST_F(TopTest, UnusedTopInitializer) {
1534 std::string Code = R"(
1535 bool makeTop();
1536
1537 void target() {
1538 bool Foo = makeTop();
1539 /*[[p1]]*/
1540 (void)0;
1541 /*[[p2]]*/
1542 }
1543 )";
1544 runDataflow(
1545 Code,
1546 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1547 const AnalysisOutputs &AO) {
1548 ASSERT_THAT(Results.keys(),
1549 UnorderedElementsAre("p1", "p2"));
1550 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1551 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1552
1553 const ValueDecl *FooDecl = findValueDecl(AO.ASTCtx, "Foo");
1554 ASSERT_THAT(FooDecl, NotNull());
1555
1556 auto GetFooValue = [FooDecl](const Environment &Env) {
1557 return Env.getValue(*FooDecl);
1558 };
1559
1560 Value *FooVal1 = GetFooValue(Env1);
1561 ASSERT_THAT(FooVal1, NotNull());
1562 EXPECT_TRUE(isa<TopBoolValue>(FooVal1))
1563 << debugString(FooVal1->getKind());
1564
1565 Value *FooVal2 = GetFooValue(Env2);
1566 ASSERT_THAT(FooVal2, NotNull());
1567 EXPECT_TRUE(isa<TopBoolValue>(FooVal2))
1568 << debugString(FooVal2->getKind());
1569
1570 EXPECT_EQ(FooVal1, FooVal2);
1571 });
1572 }
1573
1574 // Tests that when Top is unused it remains Top. Like above, but uses the
1575 // assignment form rather than initialization, which uses Top as an lvalue that
1576 // is *not* in an rvalue position.
1577 TEST_F(TopTest, UnusedTopAssignment) {
1578 std::string Code = R"(
1579 bool makeTop();
1580
1581 void target() {
1582 bool Foo;
1583 Foo = makeTop();
1584 /*[[p1]]*/
1585 (void)0;
1586 /*[[p2]]*/
1587 }
1588 )";
1589 runDataflow(
1590 Code,
1591 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1592 const AnalysisOutputs &AO) {
1593 ASSERT_THAT(Results.keys(),
1594 UnorderedElementsAre("p1", "p2"));
1595 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1596 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1597
1598 const ValueDecl *FooDecl = findValueDecl(AO.ASTCtx, "Foo");
1599 ASSERT_THAT(FooDecl, NotNull());
1600
1601 auto GetFooValue = [FooDecl](const Environment &Env) {
1602 return Env.getValue(*FooDecl);
1603 };
1604
1605 Value *FooVal1 = GetFooValue(Env1);
1606 ASSERT_THAT(FooVal1, NotNull());
1607 EXPECT_TRUE(isa<TopBoolValue>(FooVal1))
1608 << debugString(FooVal1->getKind());
1609
1610 Value *FooVal2 = GetFooValue(Env2);
1611 ASSERT_THAT(FooVal2, NotNull());
1612 EXPECT_TRUE(isa<TopBoolValue>(FooVal2))
1613 << debugString(FooVal2->getKind());
1614
1615 EXPECT_EQ(FooVal1, FooVal2);
1616 });
1617 }
1618
1619 TEST_F(TopTest, UnusedTopJoinsToTop) {
1620 std::string Code = R"(
1621 bool makeTop();
1622
1623 void target(bool Cond, bool F) {
1624 bool Foo = makeTop();
1625 // Force a new CFG block.
1626 if (F) return;
1627 (void)0;
1628 /*[[p1]]*/
1629
1630 bool Zab1;
1631 bool Zab2;
1632 if (Cond) {
1633 Zab1 = true;
1634 } else {
1635 Zab2 = true;
1636 }
1637 (void)0;
1638 /*[[p2]]*/
1639 }
1640 )";
1641 runDataflow(
1642 Code,
1643 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1644 const AnalysisOutputs &AO) {
1645 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1646 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1647 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1648
1649 const ValueDecl *FooDecl = findValueDecl(AO.ASTCtx, "Foo");
1650 ASSERT_THAT(FooDecl, NotNull());
1651
1652 auto GetFooValue = [FooDecl](const Environment &Env) {
1653 return Env.getValue(*FooDecl);
1654 };
1655
1656 Value *FooVal1 = GetFooValue(Env1);
1657 ASSERT_THAT(FooVal1, NotNull());
1658 EXPECT_TRUE(isa<TopBoolValue>(FooVal1))
1659 << debugString(FooVal1->getKind());
1660
1661 Value *FooVal2 = GetFooValue(Env2);
1662 ASSERT_THAT(FooVal2, NotNull());
1663 EXPECT_TRUE(isa<TopBoolValue>(FooVal2))
1664 << debugString(FooVal2->getKind());
1665 });
1666 }
1667
1668 TEST_F(TopTest, TopUsedBeforeBranchJoinsToSameAtomicBool) {
1669 std::string Code = R"(
1670 bool makeTop();
1671
1672 void target(bool Cond, bool F) {
1673 bool Foo = makeTop();
1674 /*[[p0]]*/
1675
1676 // Use `Top`.
1677 bool Bar = Foo;
1678 // Force a new CFG block.
1679 if (F) return;
1680 (void)0;
1681 /*[[p1]]*/
1682
1683 bool Zab1;
1684 bool Zab2;
1685 if (Cond) {
1686 Zab1 = true;
1687 } else {
1688 Zab2 = true;
1689 }
1690 (void)0;
1691 /*[[p2]]*/
1692 }
1693 )";
1694 runDataflow(
1695 Code,
1696 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1697 const AnalysisOutputs &AO) {
1698 ASSERT_THAT(Results.keys(),
1699 UnorderedElementsAre("p0", "p1", "p2"));
1700 const Environment &Env0 = getEnvironmentAtAnnotation(Results, "p0");
1701 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1702 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1703
1704 const ValueDecl *FooDecl = findValueDecl(AO.ASTCtx, "Foo");
1705 ASSERT_THAT(FooDecl, NotNull());
1706
1707 auto GetFooValue = [FooDecl](const Environment &Env) {
1708 return Env.getValue(*FooDecl);
1709 };
1710
1711 Value *FooVal0 = GetFooValue(Env0);
1712 ASSERT_THAT(FooVal0, NotNull());
1713 EXPECT_TRUE(isa<TopBoolValue>(FooVal0))
1714 << debugString(FooVal0->getKind());
1715
1716 Value *FooVal1 = GetFooValue(Env1);
1717 ASSERT_THAT(FooVal1, NotNull());
1718 EXPECT_TRUE(isa<AtomicBoolValue>(FooVal1))
1719 << debugString(FooVal1->getKind());
1720
1721 Value *FooVal2 = GetFooValue(Env2);
1722 ASSERT_THAT(FooVal2, NotNull());
1723 EXPECT_TRUE(isa<AtomicBoolValue>(FooVal2))
1724 << debugString(FooVal2->getKind());
1725
1726 EXPECT_EQ(FooVal2, FooVal1);
1727 });
1728 }
1729
1730 TEST_F(TopTest, TopUsedInBothBranchesJoinsToAtomic) {
1731 std::string Code = R"(
1732 bool makeTop();
1733
1734 void target(bool Cond, bool F) {
1735 bool Foo = makeTop();
1736 // Force a new CFG block.
1737 if (F) return;
1738 (void)0;
1739 /*[[p1]]*/
1740
1741 bool Zab1;
1742 bool Zab2;
1743 if (Cond) {
1744 Zab1 = Foo;
1745 } else {
1746 Zab2 = Foo;
1747 }
1748 (void)0;
1749 /*[[p2]]*/
1750 }
1751 )";
1752 runDataflow(
1753 Code,
1754 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1755 const AnalysisOutputs &AO) {
1756 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1757 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1758 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1759
1760 const ValueDecl *FooDecl = findValueDecl(AO.ASTCtx, "Foo");
1761 ASSERT_THAT(FooDecl, NotNull());
1762
1763 auto GetFooValue = [FooDecl](const Environment &Env) {
1764 return Env.getValue(*FooDecl);
1765 };
1766
1767 Value *FooVal1 = GetFooValue(Env1);
1768 ASSERT_THAT(FooVal1, NotNull());
1769 EXPECT_TRUE(isa<TopBoolValue>(FooVal1))
1770 << debugString(FooVal1->getKind());
1771
1772 Value *FooVal2 = GetFooValue(Env2);
1773 ASSERT_THAT(FooVal2, NotNull());
1774 EXPECT_TRUE(isa<AtomicBoolValue>(FooVal2))
1775 << debugString(FooVal2->getKind());
1776 });
1777 }
1778
1779 TEST_F(TopTest, TopUsedInBothBranchesWithoutPrecisionLoss) {
1780 std::string Code = R"(
1781 bool makeTop();
1782
1783 void target(bool Cond, bool F) {
1784 bool Foo = makeTop();
1785 // Force a new CFG block.
1786 if (F) return;
1787 (void)0;
1788
1789 bool Bar;
1790 if (Cond) {
1791 Bar = Foo;
1792 } else {
1793 Bar = Foo;
1794 }
1795 (void)0;
1796 /*[[p]]*/
1797 }
1798 )";
1799 runDataflow(
1800 Code,
1801 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1802 const AnalysisOutputs &AO) {
1803 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
1804 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
1805
1806 const ValueDecl *FooDecl = findValueDecl(AO.ASTCtx, "Foo");
1807 ASSERT_THAT(FooDecl, NotNull());
1808
1809 const ValueDecl *BarDecl = findValueDecl(AO.ASTCtx, "Bar");
1810 ASSERT_THAT(BarDecl, NotNull());
1811
1812 auto *FooVal = dyn_cast_or_null<BoolValue>(Env.getValue(*FooDecl));
1813 ASSERT_THAT(FooVal, NotNull());
1814
1815 auto *BarVal = dyn_cast_or_null<BoolValue>(Env.getValue(*BarDecl));
1816 ASSERT_THAT(BarVal, NotNull());
1817
1818 EXPECT_TRUE(Env.proves(
1819 Env.arena().makeEquals(FooVal->formula(), BarVal->formula())));
1820 });
1821 }
1822
1823 TEST_F(TopTest, TopUnusedBeforeLoopHeadJoinsToTop) {
1824 std::string Code = R"(
1825 bool makeTop();
1826
1827 void target(bool Cond, bool F) {
1828 bool Foo = makeTop();
1829 // Force a new CFG block.
1830 if (F) return;
1831 (void)0;
1832 /*[[p1]]*/
1833
1834 while (Cond) {
1835 // Use `Foo`.
1836 bool Zab = Foo;
1837 Zab = false;
1838 Foo = makeTop();
1839 }
1840 (void)0;
1841 /*[[p2]]*/
1842 }
1843 )";
1844 runDataflow(
1845 Code,
1846 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
1847 const AnalysisOutputs &AO) {
1848 ASSERT_THAT(Results.keys(), UnorderedElementsAre("p1", "p2"));
1849 const Environment &Env1 = getEnvironmentAtAnnotation(Results, "p1");
1850 const Environment &Env2 = getEnvironmentAtAnnotation(Results, "p2");
1851
1852 const ValueDecl *FooDecl = findValueDecl(AO.ASTCtx, "Foo");
1853 ASSERT_THAT(FooDecl, NotNull());
1854
1855 auto GetFooValue = [FooDecl](const Environment &Env) {
1856 return Env.getValue(*FooDecl);
1857 };
1858
1859 Value *FooVal1 = GetFooValue(Env1);
1860 ASSERT_THAT(FooVal1, NotNull());
1861 EXPECT_TRUE(isa<TopBoolValue>(FooVal1))
1862 << debugString(FooVal1->getKind());
1863
1864 Value *FooVal2 = GetFooValue(Env2);
1865 ASSERT_THAT(FooVal2, NotNull());
1866 EXPECT_TRUE(isa<TopBoolValue>(FooVal2))
1867 << debugString(FooVal2->getKind());
1868
1869 });
1870 }
1871
1872 TEST_F(TopTest, ForRangeStmtConverges) {
1873 std::string Code = R"(
1874 void target(bool Foo) {
1875 int Ints[10];
1876 bool B = false;
1877 for (int I : Ints)
1878 B = true;
1879 }
1880 )";
1881 runDataflow(Code,
1882 [](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &,
1883 const AnalysisOutputs &) {
1884 // No additional expectations. We're only checking that the
1885 // analysis converged.
1886 });
1887 }
1888 } // namespace