File: MultiVarConstantPropagationTest.cpp

package info (click to toggle)
llvm-toolchain-14 1%3A14.0.6-16
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,496,368 kB
  • sloc: cpp: 5,593,980; ansic: 986,873; asm: 585,869; python: 184,223; objc: 72,530; lisp: 31,119; f90: 27,793; javascript: 9,780; pascal: 9,762; sh: 9,482; perl: 7,468; ml: 5,432; awk: 3,523; makefile: 2,547; xml: 953; cs: 573; fortran: 567
file content (481 lines) | stat: -rw-r--r-- 16,723 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//===- unittests/Analysis/FlowSensitive/SingelVarConstantPropagation.cpp --===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
//  This file defines a simplistic version of Constant Propagation as an example
//  of a forward, monotonic dataflow analysis. The analysis tracks all
//  variables in the scope, but lacks escape analysis.
//
//===----------------------------------------------------------------------===//

#include "TestingSupport.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Stmt.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
#include "clang/Analysis/FlowSensitive/MapLattice.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Testing/Support/Annotations.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <cstdint>
#include <memory>
#include <ostream>
#include <string>
#include <utility>

namespace clang {
namespace dataflow {
namespace {
using namespace ast_matchers;

// Models the value of an expression at a program point, for all paths through
// the program.
struct ValueLattice {
  // FIXME: change the internal representation to use a `std::variant`, once
  // clang admits C++17 constructs.
  enum class ValueState : bool {
    Undefined,
    Defined,
  };
  // `State` determines the meaning of the lattice when `Value` is `None`:
  //  * `Undefined` -> bottom,
  //  * `Defined` -> top.
  ValueState State;

  // When `None`, the lattice is either at top or bottom, based on `State`.
  llvm::Optional<int64_t> Value;

  constexpr ValueLattice() : State(ValueState::Undefined), Value(llvm::None) {}
  constexpr ValueLattice(int64_t V) : State(ValueState::Defined), Value(V) {}
  constexpr ValueLattice(ValueState S) : State(S), Value(llvm::None) {}

  static constexpr ValueLattice bottom() {
    return ValueLattice(ValueState::Undefined);
  }
  static constexpr ValueLattice top() {
    return ValueLattice(ValueState::Defined);
  }

  friend bool operator==(const ValueLattice &Lhs, const ValueLattice &Rhs) {
    return Lhs.State == Rhs.State && Lhs.Value == Rhs.Value;
  }
  friend bool operator!=(const ValueLattice &Lhs, const ValueLattice &Rhs) {
    return !(Lhs == Rhs);
  }

  LatticeJoinEffect join(const ValueLattice &Other) {
    if (*this == Other || Other == bottom() || *this == top())
      return LatticeJoinEffect::Unchanged;

    if (*this == bottom()) {
      *this = Other;
      return LatticeJoinEffect::Changed;
    }

    *this = top();
    return LatticeJoinEffect::Changed;
  }
};

std::ostream &operator<<(std::ostream &OS, const ValueLattice &L) {
  if (L.Value.hasValue())
    return OS << *L.Value;
  switch (L.State) {
  case ValueLattice::ValueState::Undefined:
    return OS << "None";
  case ValueLattice::ValueState::Defined:
    return OS << "Any";
  }
  llvm_unreachable("unknown ValueState!");
}

using ConstantPropagationLattice = VarMapLattice<ValueLattice>;

constexpr char kDecl[] = "decl";
constexpr char kVar[] = "var";
constexpr char kInit[] = "init";
constexpr char kJustAssignment[] = "just-assignment";
constexpr char kAssignment[] = "assignment";
constexpr char kRHS[] = "rhs";

auto refToVar() { return declRefExpr(to(varDecl().bind(kVar))); }

// N.B. This analysis is deliberately simplistic, leaving out many important
// details needed for a real analysis. Most notably, the transfer function does
// not account for the variable's address possibly escaping, which would
// invalidate the analysis. It also could be optimized to drop out-of-scope
// variables from the map.
class ConstantPropagationAnalysis
    : public DataflowAnalysis<ConstantPropagationAnalysis,
                              ConstantPropagationLattice> {
public:
  explicit ConstantPropagationAnalysis(ASTContext &Context)
      : DataflowAnalysis<ConstantPropagationAnalysis,
                         ConstantPropagationLattice>(Context) {}

  static ConstantPropagationLattice initialElement() {
    return ConstantPropagationLattice::bottom();
  }

  void transfer(const Stmt *S, ConstantPropagationLattice &Vars,
                Environment &Env) {
    auto matcher =
        stmt(anyOf(declStmt(hasSingleDecl(
                       varDecl(decl().bind(kVar), hasType(isInteger()),
                               optionally(hasInitializer(expr().bind(kInit))))
                           .bind(kDecl))),
                   binaryOperator(hasOperatorName("="), hasLHS(refToVar()),
                                  hasRHS(expr().bind(kRHS)))
                       .bind(kJustAssignment),
                   binaryOperator(isAssignmentOperator(), hasLHS(refToVar()))
                       .bind(kAssignment)));

    ASTContext &Context = getASTContext();
    auto Results = match(matcher, *S, Context);
    if (Results.empty())
      return;
    const BoundNodes &Nodes = Results[0];

    const auto *Var = Nodes.getNodeAs<clang::VarDecl>(kVar);
    assert(Var != nullptr);

    if (Nodes.getNodeAs<clang::VarDecl>(kDecl) != nullptr) {
      if (const auto *E = Nodes.getNodeAs<clang::Expr>(kInit)) {
        Expr::EvalResult R;
        Vars[Var] = (E->EvaluateAsInt(R, Context) && R.Val.isInt())
                        ? ValueLattice(R.Val.getInt().getExtValue())
                        : ValueLattice::top();
      } else {
        // An unitialized variable holds *some* value, but we don't know what it
        // is (it is implementation defined), so we set it to top.
        Vars[Var] = ValueLattice::top();
      }
    } else if (Nodes.getNodeAs<clang::Expr>(kJustAssignment)) {
      const auto *E = Nodes.getNodeAs<clang::Expr>(kRHS);
      assert(E != nullptr);

      Expr::EvalResult R;
      Vars[Var] = (E->EvaluateAsInt(R, Context) && R.Val.isInt())
                      ? ValueLattice(R.Val.getInt().getExtValue())
                      : ValueLattice::top();
    } else if (Nodes.getNodeAs<clang::Expr>(kAssignment)) {
      // Any assignment involving the expression itself resets the variable to
      // "unknown". A more advanced analysis could try to evaluate the compound
      // assignment. For example, `x += 0` need not invalidate `x`.
      Vars[Var] = ValueLattice::top();
    }
  }
};

using ::testing::IsEmpty;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;

MATCHER_P(Var, name,
          (llvm::Twine(negation ? "isn't" : "is") + " a variable named `" +
           name + "`")
              .str()) {
  return arg->getName() == name;
}

MATCHER_P(HasConstantVal, v, "") {
  return arg.Value.hasValue() && *arg.Value == v;
}

MATCHER(Varies, "") { return arg == arg.top(); }

MATCHER_P(HoldsCPLattice, m,
          ((negation ? "doesn't hold" : "holds") +
           llvm::StringRef(" a lattice element that ") +
           ::testing::DescribeMatcher<ConstantPropagationLattice>(m, negation))
              .str()) {
  return ExplainMatchResult(m, arg.Lattice, result_listener);
}

class MultiVarConstantPropagationTest : public ::testing::Test {
protected:
  template <typename Matcher>
  void RunDataflow(llvm::StringRef Code, Matcher Expectations) {
    ASSERT_THAT_ERROR(
        test::checkDataflow<ConstantPropagationAnalysis>(
            Code, "fun",
            [](ASTContext &C, Environment &) {
              return ConstantPropagationAnalysis(C);
            },
            [&Expectations](
                llvm::ArrayRef<std::pair<
                    std::string, DataflowAnalysisState<
                                     ConstantPropagationAnalysis::Lattice>>>
                    Results,
                ASTContext &) { EXPECT_THAT(Results, Expectations); },
            {"-fsyntax-only", "-std=c++17"}),
        llvm::Succeeded());
  }
};

TEST_F(MultiVarConstantPropagationTest, JustInit) {
  std::string Code = R"(
    void fun() {
      int target = 1;
      // [[p]]
    }
  )";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p", HoldsCPLattice(UnorderedElementsAre(Pair(
                                      Var("target"), HasConstantVal(1)))))));
}

TEST_F(MultiVarConstantPropagationTest, Assignment) {
  std::string Code = R"(
    void fun() {
      int target = 1;
      // [[p1]]
      target = 2;
      // [[p2]]
    }
  )";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1))))),
                        Pair("p2", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(2)))))));
}

TEST_F(MultiVarConstantPropagationTest, AssignmentCall) {
  std::string Code = R"(
    int g();
    void fun() {
      int target;
      target = g();
      // [[p]]
    }
  )";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p", HoldsCPLattice(UnorderedElementsAre(
                                      Pair(Var("target"), Varies()))))));
}

TEST_F(MultiVarConstantPropagationTest, AssignmentBinOp) {
  std::string Code = R"(
    void fun() {
      int target;
      target = 2 + 3;
      // [[p]]
    }
  )";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p", HoldsCPLattice(UnorderedElementsAre(Pair(
                                      Var("target"), HasConstantVal(5)))))));
}

TEST_F(MultiVarConstantPropagationTest, PlusAssignment) {
  std::string Code = R"(
    void fun() {
      int target = 1;
      // [[p1]]
      target += 2;
      // [[p2]]
    }
  )";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1))))),
                        Pair("p2", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies()))))));
}

TEST_F(MultiVarConstantPropagationTest, SameAssignmentInBranches) {
  std::string Code = R"cc(
    void fun(bool b) {
      int target;
      // [[p1]]
      if (b) {
        target = 2;
        // [[pT]]
      } else {
        target = 2;
        // [[pF]]
      }
      (void)0;
      // [[p2]]
    }
  )cc";
  RunDataflow(Code,
              UnorderedElementsAre(
                  Pair("p1", HoldsCPLattice(UnorderedElementsAre(
                                 Pair(Var("target"), Varies())))),
                  Pair("pT", HoldsCPLattice(UnorderedElementsAre(
                                 Pair(Var("target"), HasConstantVal(2))))),
                  Pair("pF", HoldsCPLattice(UnorderedElementsAre(
                                 Pair(Var("target"), HasConstantVal(2))))),
                  Pair("p2", HoldsCPLattice(UnorderedElementsAre(
                                 Pair(Var("target"), HasConstantVal(2)))))));
}

// Verifies that the analysis tracks multiple variables simultaneously.
TEST_F(MultiVarConstantPropagationTest, TwoVariables) {
  std::string Code = R"(
    void fun() {
      int target = 1;
      // [[p1]]
      int other = 2;
      // [[p2]]
      target = 3;
      // [[p3]]
    }
  )";
  RunDataflow(Code,
              UnorderedElementsAre(
                  Pair("p1", HoldsCPLattice(UnorderedElementsAre(
                                 Pair(Var("target"), HasConstantVal(1))))),
                  Pair("p2", HoldsCPLattice(UnorderedElementsAre(
                                 Pair(Var("target"), HasConstantVal(1)),
                                 Pair(Var("other"), HasConstantVal(2))))),
                  Pair("p3", HoldsCPLattice(UnorderedElementsAre(
                                 Pair(Var("target"), HasConstantVal(3)),
                                 Pair(Var("other"), HasConstantVal(2)))))));
}

TEST_F(MultiVarConstantPropagationTest, TwoVariablesInBranches) {
  std::string Code = R"cc(
    void fun(bool b) {
      int target;
      int other;
      // [[p1]]
      if (b) {
        target = 2;
        // [[pT]]
      } else {
        other = 3;
        // [[pF]]
      }
      (void)0;
      // [[p2]]
    }
  )cc";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p1", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies()),
                                       Pair(Var("other"), Varies())))),
                        Pair("pT", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), HasConstantVal(2)),
                                       Pair(Var("other"), Varies())))),
                        Pair("pF", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("other"), HasConstantVal(3)),
                                       Pair(Var("target"), Varies())))),
                        Pair("p2", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies()),
                                       Pair(Var("other"), Varies()))))));
}

TEST_F(MultiVarConstantPropagationTest, SameAssignmentInBranch) {
  std::string Code = R"cc(
    void fun(bool b) {
      int target = 1;
      // [[p1]]
      if (b) {
        target = 1;
      }
      (void)0;
      // [[p2]]
    }
  )cc";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1))))),
                        Pair("p2", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1)))))));
}

TEST_F(MultiVarConstantPropagationTest, NewVarInBranch) {
  std::string Code = R"cc(
    void fun(bool b) {
      if (b) {
        int target;
        // [[p1]]
        target = 1;
        // [[p2]]
      } else {
        int target;
        // [[p3]]
        target = 1;
        // [[p4]]
      }
    }
  )cc";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p1", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies())))),
                        Pair("p2", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1))))),
                        Pair("p3", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies())))),
                        Pair("p4", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1)))))));
}

TEST_F(MultiVarConstantPropagationTest, DifferentAssignmentInBranches) {
  std::string Code = R"cc(
    void fun(bool b) {
      int target;
      // [[p1]]
      if (b) {
        target = 1;
        // [[pT]]
      } else {
        target = 2;
        // [[pF]]
      }
      (void)0;
      // [[p2]]
    }
  )cc";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p1", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies())))),
                        Pair("pT", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1))))),
                        Pair("pF", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(2))))),
                        Pair("p2", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies()))))));
}

TEST_F(MultiVarConstantPropagationTest, DifferentAssignmentInBranch) {
  std::string Code = R"cc(
    void fun(bool b) {
      int target = 1;
      // [[p1]]
      if (b) {
        target = 3;
      }
      (void)0;
      // [[p2]]
    }
  )cc";
  RunDataflow(Code, UnorderedElementsAre(
                        Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair(
                                       Var("target"), HasConstantVal(1))))),
                        Pair("p2", HoldsCPLattice(UnorderedElementsAre(
                                       Pair(Var("target"), Varies()))))));
}

} // namespace
} // namespace dataflow
} // namespace clang