1 //===- WatchedLiteralsSolver.cpp --------------------------------*- C++ -*-===//
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 //  This file defines a SAT solver implementation that can be used by dataflow
10 //  analyses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include <cassert>
15 #include <cstdint>
16 #include <iterator>
17 #include <queue>
18 #include <vector>
19 
20 #include "clang/Analysis/FlowSensitive/Solver.h"
21 #include "clang/Analysis/FlowSensitive/Value.h"
22 #include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/STLExtras.h"
26 
27 namespace clang {
28 namespace dataflow {
29 
30 // `WatchedLiteralsSolver` is an implementation of Algorithm D from Knuth's
31 // The Art of Computer Programming Volume 4: Satisfiability, Fascicle 6. It is
32 // based on the backtracking DPLL algorithm [1], keeps references to a single
33 // "watched" literal per clause, and uses a set of "active" variables to perform
34 // unit propagation.
35 //
36 // The solver expects that its input is a boolean formula in conjunctive normal
37 // form that consists of clauses of at least one literal. A literal is either a
38 // boolean variable or its negation. Below we define types, data structures, and
39 // utilities that are used to represent boolean formulas in conjunctive normal
40 // form.
41 //
42 // [1] https://en.wikipedia.org/wiki/DPLL_algorithm
43 
44 /// Boolean variables are represented as positive integers.
45 using Variable = uint32_t;
46 
47 /// A null boolean variable is used as a placeholder in various data structures
48 /// and algorithms.
49 static constexpr Variable NullVar = 0;
50 
51 /// Literals are represented as positive integers. Specifically, for a boolean
52 /// variable `V` that is represented as the positive integer `I`, the positive
53 /// literal `V` is represented as the integer `2*I` and the negative literal
54 /// `!V` is represented as the integer `2*I+1`.
55 using Literal = uint32_t;
56 
57 /// A null literal is used as a placeholder in various data structures and
58 /// algorithms.
59 static constexpr Literal NullLit = 0;
60 
61 /// Returns the positive literal `V`.
62 static constexpr Literal posLit(Variable V) { return 2 * V; }
63 
64 /// Returns the negative literal `!V`.
65 static constexpr Literal negLit(Variable V) { return 2 * V + 1; }
66 
67 /// Returns the negated literal `!L`.
68 static constexpr Literal notLit(Literal L) { return L ^ 1; }
69 
70 /// Returns the variable of `L`.
71 static constexpr Variable var(Literal L) { return L >> 1; }
72 
73 /// Clause identifiers are represented as positive integers.
74 using ClauseID = uint32_t;
75 
76 /// A null clause identifier is used as a placeholder in various data structures
77 /// and algorithms.
78 static constexpr ClauseID NullClause = 0;
79 
80 /// A boolean formula in conjunctive normal form.
81 struct BooleanFormula {
82   /// `LargestVar` is equal to the largest positive integer that represents a
83   /// variable in the formula.
84   const Variable LargestVar;
85 
86   /// Literals of all clauses in the formula.
87   ///
88   /// The element at index 0 stands for the literal in the null clause. It is
89   /// set to 0 and isn't used. Literals of clauses in the formula start from the
90   /// element at index 1.
91   ///
92   /// For example, for the formula `(L1 v L2) ^ (L2 v L3 v L4)` the elements of
93   /// `Clauses` will be `[0, L1, L2, L2, L3, L4]`.
94   std::vector<Literal> Clauses;
95 
96   /// Start indices of clauses of the formula in `Clauses`.
97   ///
98   /// The element at index 0 stands for the start index of the null clause. It
99   /// is set to 0 and isn't used. Start indices of clauses in the formula start
100   /// from the element at index 1.
101   ///
102   /// For example, for the formula `(L1 v L2) ^ (L2 v L3 v L4)` the elements of
103   /// `ClauseStarts` will be `[0, 1, 3]`. Note that the literals of the first
104   /// clause always start at index 1. The start index for the literals of the
105   /// second clause depends on the size of the first clause and so on.
106   std::vector<size_t> ClauseStarts;
107 
108   /// Maps literals (indices of the vector) to clause identifiers (elements of
109   /// the vector) that watch the respective literals.
110   ///
111   /// For a given clause, its watched literal is always its first literal in
112   /// `Clauses`. This invariant is maintained when watched literals change.
113   std::vector<ClauseID> WatchedHead;
114 
115   /// Maps clause identifiers (elements of the vector) to identifiers of other
116   /// clauses that watch the same literals, forming a set of linked lists.
117   ///
118   /// The element at index 0 stands for the identifier of the clause that
119   /// follows the null clause. It is set to 0 and isn't used. Identifiers of
120   /// clauses in the formula start from the element at index 1.
121   std::vector<ClauseID> NextWatched;
122 
123   /// Stores the variable identifier and value location for atomic booleans in
124   /// the formula.
125   llvm::DenseMap<Variable, AtomicBoolValue *> Atomics;
126 
127   explicit BooleanFormula(Variable LargestVar,
128                           llvm::DenseMap<Variable, AtomicBoolValue *> Atomics)
129       : LargestVar(LargestVar), Atomics(std::move(Atomics)) {
130     Clauses.push_back(0);
131     ClauseStarts.push_back(0);
132     NextWatched.push_back(0);
133     const size_t NumLiterals = 2 * LargestVar + 1;
134     WatchedHead.resize(NumLiterals + 1, 0);
135   }
136 
137   /// Adds the `L1 v L2 v L3` clause to the formula. If `L2` or `L3` are
138   /// `NullLit` they are respectively omitted from the clause.
139   ///
140   /// Requirements:
141   ///
142   ///  `L1` must not be `NullLit`.
143   ///
144   ///  All literals in the input that are not `NullLit` must be distinct.
145   void addClause(Literal L1, Literal L2 = NullLit, Literal L3 = NullLit) {
146     // The literals are guaranteed to be distinct from properties of BoolValue
147     // and the construction in `buildBooleanFormula`.
148     assert(L1 != NullLit && L1 != L2 && L1 != L3 &&
149            (L2 != L3 || L2 == NullLit));
150 
151     const ClauseID C = ClauseStarts.size();
152     const size_t S = Clauses.size();
153     ClauseStarts.push_back(S);
154 
155     Clauses.push_back(L1);
156     if (L2 != NullLit)
157       Clauses.push_back(L2);
158     if (L3 != NullLit)
159       Clauses.push_back(L3);
160 
161     // Designate the first literal as the "watched" literal of the clause.
162     NextWatched.push_back(WatchedHead[L1]);
163     WatchedHead[L1] = C;
164   }
165 
166   /// Returns the number of literals in clause `C`.
167   size_t clauseSize(ClauseID C) const {
168     return C == ClauseStarts.size() - 1 ? Clauses.size() - ClauseStarts[C]
169                                         : ClauseStarts[C + 1] - ClauseStarts[C];
170   }
171 
172   /// Returns the literals of clause `C`.
173   llvm::ArrayRef<Literal> clauseLiterals(ClauseID C) const {
174     return llvm::ArrayRef<Literal>(&Clauses[ClauseStarts[C]], clauseSize(C));
175   }
176 };
177 
178 /// Converts the conjunction of `Vals` into a formula in conjunctive normal
179 /// form where each clause has at least one and at most three literals.
180 BooleanFormula buildBooleanFormula(const llvm::DenseSet<BoolValue *> &Vals) {
181   // The general strategy of the algorithm implemented below is to map each
182   // of the sub-values in `Vals` to a unique variable and use these variables in
183   // the resulting CNF expression to avoid exponential blow up. The number of
184   // literals in the resulting formula is guaranteed to be linear in the number
185   // of sub-values in `Vals`.
186 
187   // Map each sub-value in `Vals` to a unique variable.
188   llvm::DenseMap<BoolValue *, Variable> SubValsToVar;
189   // Store variable identifiers and value location of atomic booleans.
190   llvm::DenseMap<Variable, AtomicBoolValue *> Atomics;
191   Variable NextVar = 1;
192   {
193     std::queue<BoolValue *> UnprocessedSubVals;
194     for (BoolValue *Val : Vals)
195       UnprocessedSubVals.push(Val);
196     while (!UnprocessedSubVals.empty()) {
197       Variable Var = NextVar;
198       BoolValue *Val = UnprocessedSubVals.front();
199       UnprocessedSubVals.pop();
200 
201       if (!SubValsToVar.try_emplace(Val, Var).second)
202         continue;
203       ++NextVar;
204 
205       // Visit the sub-values of `Val`.
206       switch (Val->getKind()) {
207       case Value::Kind::Conjunction: {
208         auto *C = cast<ConjunctionValue>(Val);
209         UnprocessedSubVals.push(&C->getLeftSubValue());
210         UnprocessedSubVals.push(&C->getRightSubValue());
211         break;
212       }
213       case Value::Kind::Disjunction: {
214         auto *D = cast<DisjunctionValue>(Val);
215         UnprocessedSubVals.push(&D->getLeftSubValue());
216         UnprocessedSubVals.push(&D->getRightSubValue());
217         break;
218       }
219       case Value::Kind::Negation: {
220         auto *N = cast<NegationValue>(Val);
221         UnprocessedSubVals.push(&N->getSubVal());
222         break;
223       }
224       case Value::Kind::AtomicBool: {
225         Atomics[Var] = cast<AtomicBoolValue>(Val);
226         break;
227       }
228       default:
229         llvm_unreachable("buildBooleanFormula: unhandled value kind");
230       }
231     }
232   }
233 
234   auto GetVar = [&SubValsToVar](const BoolValue *Val) {
235     auto ValIt = SubValsToVar.find(Val);
236     assert(ValIt != SubValsToVar.end());
237     return ValIt->second;
238   };
239 
240   BooleanFormula Formula(NextVar - 1, std::move(Atomics));
241   std::vector<bool> ProcessedSubVals(NextVar, false);
242 
243   // Add a conjunct for each variable that represents a top-level conjunction
244   // value in `Vals`.
245   for (BoolValue *Val : Vals)
246     Formula.addClause(posLit(GetVar(Val)));
247 
248   // Add conjuncts that represent the mapping between newly-created variables
249   // and their corresponding sub-values.
250   std::queue<BoolValue *> UnprocessedSubVals;
251   for (BoolValue *Val : Vals)
252     UnprocessedSubVals.push(Val);
253   while (!UnprocessedSubVals.empty()) {
254     const BoolValue *Val = UnprocessedSubVals.front();
255     UnprocessedSubVals.pop();
256     const Variable Var = GetVar(Val);
257 
258     if (ProcessedSubVals[Var])
259       continue;
260     ProcessedSubVals[Var] = true;
261 
262     if (auto *C = dyn_cast<ConjunctionValue>(Val)) {
263       const Variable LeftSubVar = GetVar(&C->getLeftSubValue());
264       const Variable RightSubVar = GetVar(&C->getRightSubValue());
265 
266       // `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v !B)`
267       // which is already in conjunctive normal form. Below we add each of the
268       // conjuncts of the latter expression to the result.
269       Formula.addClause(negLit(Var), posLit(LeftSubVar));
270       Formula.addClause(negLit(Var), posLit(RightSubVar));
271       Formula.addClause(posLit(Var), negLit(LeftSubVar), negLit(RightSubVar));
272 
273       // Visit the sub-values of `Val`.
274       UnprocessedSubVals.push(&C->getLeftSubValue());
275       UnprocessedSubVals.push(&C->getRightSubValue());
276     } else if (auto *D = dyn_cast<DisjunctionValue>(Val)) {
277       const Variable LeftSubVar = GetVar(&D->getLeftSubValue());
278       const Variable RightSubVar = GetVar(&D->getRightSubValue());
279 
280       // `X <=> (A v B)` is equivalent to `(!X v A v B) ^ (X v !A) ^ (X v !B)`
281       // which is already in conjunctive normal form. Below we add each of the
282       // conjuncts of the latter expression to the result.
283       Formula.addClause(negLit(Var), posLit(LeftSubVar), posLit(RightSubVar));
284       Formula.addClause(posLit(Var), negLit(LeftSubVar));
285       Formula.addClause(posLit(Var), negLit(RightSubVar));
286 
287       // Visit the sub-values of `Val`.
288       UnprocessedSubVals.push(&D->getLeftSubValue());
289       UnprocessedSubVals.push(&D->getRightSubValue());
290     } else if (auto *N = dyn_cast<NegationValue>(Val)) {
291       const Variable SubVar = GetVar(&N->getSubVal());
292 
293       // `X <=> !Y` is equivalent to `(!X v !Y) ^ (X v Y)` which is already in
294       // conjunctive normal form. Below we add each of the conjuncts of the
295       // latter expression to the result.
296       Formula.addClause(negLit(Var), negLit(SubVar));
297       Formula.addClause(posLit(Var), posLit(SubVar));
298 
299       // Visit the sub-values of `Val`.
300       UnprocessedSubVals.push(&N->getSubVal());
301     }
302   }
303 
304   return Formula;
305 }
306 
307 class WatchedLiteralsSolverImpl {
308   /// A boolean formula in conjunctive normal form that the solver will attempt
309   /// to prove satisfiable. The formula will be modified in the process.
310   BooleanFormula Formula;
311 
312   /// The search for a satisfying assignment of the variables in `Formula` will
313   /// proceed in levels, starting from 1 and going up to `Formula.LargestVar`
314   /// (inclusive). The current level is stored in `Level`. At each level the
315   /// solver will assign a value to an unassigned variable. If this leads to a
316   /// consistent partial assignment, `Level` will be incremented. Otherwise, if
317   /// it results in a conflict, the solver will backtrack by decrementing
318   /// `Level` until it reaches the most recent level where a decision was made.
319   size_t Level = 0;
320 
321   /// Maps levels (indices of the vector) to variables (elements of the vector)
322   /// that are assigned values at the respective levels.
323   ///
324   /// The element at index 0 isn't used. Variables start from the element at
325   /// index 1.
326   std::vector<Variable> LevelVars;
327 
328   /// State of the solver at a particular level.
329   enum class State : uint8_t {
330     /// Indicates that the solver made a decision.
331     Decision = 0,
332 
333     /// Indicates that the solver made a forced move.
334     Forced = 1,
335   };
336 
337   /// State of the solver at a particular level. It keeps track of previous
338   /// decisions that the solver can refer to when backtracking.
339   ///
340   /// The element at index 0 isn't used. States start from the element at index
341   /// 1.
342   std::vector<State> LevelStates;
343 
344   enum class Assignment : int8_t {
345     Unassigned = -1,
346     AssignedFalse = 0,
347     AssignedTrue = 1
348   };
349 
350   /// Maps variables (indices of the vector) to their assignments (elements of
351   /// the vector).
352   ///
353   /// The element at index 0 isn't used. Variable assignments start from the
354   /// element at index 1.
355   std::vector<Assignment> VarAssignments;
356 
357   /// A set of unassigned variables that appear in watched literals in
358   /// `Formula`. The vector is guaranteed to contain unique elements.
359   std::vector<Variable> ActiveVars;
360 
361 public:
362   explicit WatchedLiteralsSolverImpl(const llvm::DenseSet<BoolValue *> &Vals)
363       : Formula(buildBooleanFormula(Vals)), LevelVars(Formula.LargestVar + 1),
364         LevelStates(Formula.LargestVar + 1) {
365     assert(!Vals.empty());
366 
367     // Initialize the state at the root level to a decision so that in
368     // `reverseForcedMoves` we don't have to check that `Level >= 0` on each
369     // iteration.
370     LevelStates[0] = State::Decision;
371 
372     // Initialize all variables as unassigned.
373     VarAssignments.resize(Formula.LargestVar + 1, Assignment::Unassigned);
374 
375     // Initialize the active variables.
376     for (Variable Var = Formula.LargestVar; Var != NullVar; --Var) {
377       if (isWatched(posLit(Var)) || isWatched(negLit(Var)))
378         ActiveVars.push_back(Var);
379     }
380   }
381 
382   Solver::Result solve() && {
383     size_t I = 0;
384     while (I < ActiveVars.size()) {
385       // Assert that the following invariants hold:
386       // 1. All active variables are unassigned.
387       // 2. All active variables form watched literals.
388       // 3. Unassigned variables that form watched literals are active.
389       // FIXME: Consider replacing these with test cases that fail if the any
390       // of the invariants is broken. That might not be easy due to the
391       // transformations performed by `buildBooleanFormula`.
392       assert(activeVarsAreUnassigned());
393       assert(activeVarsFormWatchedLiterals());
394       assert(unassignedVarsFormingWatchedLiteralsAreActive());
395 
396       const Variable ActiveVar = ActiveVars[I];
397 
398       // Look for unit clauses that contain the active variable.
399       const bool unitPosLit = watchedByUnitClause(posLit(ActiveVar));
400       const bool unitNegLit = watchedByUnitClause(negLit(ActiveVar));
401       if (unitPosLit && unitNegLit) {
402         // We found a conflict!
403 
404         // Backtrack and rewind the `Level` until the most recent non-forced
405         // assignment.
406         reverseForcedMoves();
407 
408         // If the root level is reached, then all possible assignments lead to
409         // a conflict.
410         if (Level == 0)
411           return Solver::Result::Unsatisfiable();
412 
413         // Otherwise, take the other branch at the most recent level where a
414         // decision was made.
415         LevelStates[Level] = State::Forced;
416         const Variable Var = LevelVars[Level];
417         VarAssignments[Var] = VarAssignments[Var] == Assignment::AssignedTrue
418                                   ? Assignment::AssignedFalse
419                                   : Assignment::AssignedTrue;
420 
421         updateWatchedLiterals();
422       } else if (unitPosLit || unitNegLit) {
423         // We found a unit clause! The value of its unassigned variable is
424         // forced.
425         ++Level;
426 
427         LevelVars[Level] = ActiveVar;
428         LevelStates[Level] = State::Forced;
429         VarAssignments[ActiveVar] =
430             unitPosLit ? Assignment::AssignedTrue : Assignment::AssignedFalse;
431 
432         // Remove the variable that was just assigned from the set of active
433         // variables.
434         if (I + 1 < ActiveVars.size()) {
435           // Replace the variable that was just assigned with the last active
436           // variable for efficient removal.
437           ActiveVars[I] = ActiveVars.back();
438         } else {
439           // This was the last active variable. Repeat the process from the
440           // beginning.
441           I = 0;
442         }
443         ActiveVars.pop_back();
444 
445         updateWatchedLiterals();
446       } else if (I + 1 == ActiveVars.size()) {
447         // There are no remaining unit clauses in the formula! Make a decision
448         // for one of the active variables at the current level.
449         ++Level;
450 
451         LevelVars[Level] = ActiveVar;
452         LevelStates[Level] = State::Decision;
453         VarAssignments[ActiveVar] = decideAssignment(ActiveVar);
454 
455         // Remove the variable that was just assigned from the set of active
456         // variables.
457         ActiveVars.pop_back();
458 
459         updateWatchedLiterals();
460 
461         // This was the last active variable. Repeat the process from the
462         // beginning.
463         I = 0;
464       } else {
465         ++I;
466       }
467     }
468     return Solver::Result::Satisfiable(buildSolution());
469   }
470 
471 private:
472   /// Returns a satisfying truth assignment to the atomic values in the boolean
473   /// formula.
474   llvm::DenseMap<AtomicBoolValue *, Solver::Result::Assignment>
475   buildSolution() {
476     llvm::DenseMap<AtomicBoolValue *, Solver::Result::Assignment> Solution;
477     for (auto &Atomic : Formula.Atomics) {
478       // A variable may have a definite true/false assignment, or it may be
479       // unassigned indicating its truth value does not affect the result of
480       // the formula. Unassigned variables are assigned to true as a default.
481       Solution[Atomic.second] =
482           VarAssignments[Atomic.first] == Assignment::AssignedFalse
483               ? Solver::Result::Assignment::AssignedFalse
484               : Solver::Result::Assignment::AssignedTrue;
485     }
486     return Solution;
487   }
488 
489   /// Reverses forced moves until the most recent level where a decision was
490   /// made on the assignment of a variable.
491   void reverseForcedMoves() {
492     for (; LevelStates[Level] == State::Forced; --Level) {
493       const Variable Var = LevelVars[Level];
494 
495       VarAssignments[Var] = Assignment::Unassigned;
496 
497       // If the variable that we pass through is watched then we add it to the
498       // active variables.
499       if (isWatched(posLit(Var)) || isWatched(negLit(Var)))
500         ActiveVars.push_back(Var);
501     }
502   }
503 
504   /// Updates watched literals that are affected by a variable assignment.
505   void updateWatchedLiterals() {
506     const Variable Var = LevelVars[Level];
507 
508     // Update the watched literals of clauses that currently watch the literal
509     // that falsifies `Var`.
510     const Literal FalseLit = VarAssignments[Var] == Assignment::AssignedTrue
511                                  ? negLit(Var)
512                                  : posLit(Var);
513     ClauseID FalseLitWatcher = Formula.WatchedHead[FalseLit];
514     Formula.WatchedHead[FalseLit] = NullClause;
515     while (FalseLitWatcher != NullClause) {
516       const ClauseID NextFalseLitWatcher = Formula.NextWatched[FalseLitWatcher];
517 
518       // Pick the first non-false literal as the new watched literal.
519       const size_t FalseLitWatcherStart = Formula.ClauseStarts[FalseLitWatcher];
520       size_t NewWatchedLitIdx = FalseLitWatcherStart + 1;
521       while (isCurrentlyFalse(Formula.Clauses[NewWatchedLitIdx]))
522         ++NewWatchedLitIdx;
523       const Literal NewWatchedLit = Formula.Clauses[NewWatchedLitIdx];
524       const Variable NewWatchedLitVar = var(NewWatchedLit);
525 
526       // Swap the old watched literal for the new one in `FalseLitWatcher` to
527       // maintain the invariant that the watched literal is at the beginning of
528       // the clause.
529       Formula.Clauses[NewWatchedLitIdx] = FalseLit;
530       Formula.Clauses[FalseLitWatcherStart] = NewWatchedLit;
531 
532       // If the new watched literal isn't watched by any other clause and its
533       // variable isn't assigned we need to add it to the active variables.
534       if (!isWatched(NewWatchedLit) && !isWatched(notLit(NewWatchedLit)) &&
535           VarAssignments[NewWatchedLitVar] == Assignment::Unassigned)
536         ActiveVars.push_back(NewWatchedLitVar);
537 
538       Formula.NextWatched[FalseLitWatcher] = Formula.WatchedHead[NewWatchedLit];
539       Formula.WatchedHead[NewWatchedLit] = FalseLitWatcher;
540 
541       // Go to the next clause that watches `FalseLit`.
542       FalseLitWatcher = NextFalseLitWatcher;
543     }
544   }
545 
546   /// Returns true if and only if one of the clauses that watch `Lit` is a unit
547   /// clause.
548   bool watchedByUnitClause(Literal Lit) const {
549     for (ClauseID LitWatcher = Formula.WatchedHead[Lit];
550          LitWatcher != NullClause;
551          LitWatcher = Formula.NextWatched[LitWatcher]) {
552       llvm::ArrayRef<Literal> Clause = Formula.clauseLiterals(LitWatcher);
553 
554       // Assert the invariant that the watched literal is always the first one
555       // in the clause.
556       // FIXME: Consider replacing this with a test case that fails if the
557       // invariant is broken by `updateWatchedLiterals`. That might not be easy
558       // due to the transformations performed by `buildBooleanFormula`.
559       assert(Clause.front() == Lit);
560 
561       if (isUnit(Clause))
562         return true;
563     }
564     return false;
565   }
566 
567   /// Returns true if and only if `Clause` is a unit clause.
568   bool isUnit(llvm::ArrayRef<Literal> Clause) const {
569     return llvm::all_of(Clause.drop_front(),
570                         [this](Literal L) { return isCurrentlyFalse(L); });
571   }
572 
573   /// Returns true if and only if `Lit` evaluates to `false` in the current
574   /// partial assignment.
575   bool isCurrentlyFalse(Literal Lit) const {
576     return static_cast<int8_t>(VarAssignments[var(Lit)]) ==
577            static_cast<int8_t>(Lit & 1);
578   }
579 
580   /// Returns true if and only if `Lit` is watched by a clause in `Formula`.
581   bool isWatched(Literal Lit) const {
582     return Formula.WatchedHead[Lit] != NullClause;
583   }
584 
585   /// Returns an assignment for an unassigned variable.
586   Assignment decideAssignment(Variable Var) const {
587     return !isWatched(posLit(Var)) || isWatched(negLit(Var))
588                ? Assignment::AssignedFalse
589                : Assignment::AssignedTrue;
590   }
591 
592   /// Returns a set of all watched literals.
593   llvm::DenseSet<Literal> watchedLiterals() const {
594     llvm::DenseSet<Literal> WatchedLiterals;
595     for (Literal Lit = 2; Lit < Formula.WatchedHead.size(); Lit++) {
596       if (Formula.WatchedHead[Lit] == NullClause)
597         continue;
598       WatchedLiterals.insert(Lit);
599     }
600     return WatchedLiterals;
601   }
602 
603   /// Returns true if and only if all active variables are unassigned.
604   bool activeVarsAreUnassigned() const {
605     return llvm::all_of(ActiveVars, [this](Variable Var) {
606       return VarAssignments[Var] == Assignment::Unassigned;
607     });
608   }
609 
610   /// Returns true if and only if all active variables form watched literals.
611   bool activeVarsFormWatchedLiterals() const {
612     const llvm::DenseSet<Literal> WatchedLiterals = watchedLiterals();
613     return llvm::all_of(ActiveVars, [&WatchedLiterals](Variable Var) {
614       return WatchedLiterals.contains(posLit(Var)) ||
615              WatchedLiterals.contains(negLit(Var));
616     });
617   }
618 
619   /// Returns true if and only if all unassigned variables that are forming
620   /// watched literals are active.
621   bool unassignedVarsFormingWatchedLiteralsAreActive() const {
622     const llvm::DenseSet<Variable> ActiveVarsSet(ActiveVars.begin(),
623                                                  ActiveVars.end());
624     for (Literal Lit : watchedLiterals()) {
625       const Variable Var = var(Lit);
626       if (VarAssignments[Var] != Assignment::Unassigned)
627         continue;
628       if (ActiveVarsSet.contains(Var))
629         continue;
630       return false;
631     }
632     return true;
633   }
634 };
635 
636 Solver::Result WatchedLiteralsSolver::solve(llvm::DenseSet<BoolValue *> Vals) {
637   return Vals.empty() ? Solver::Result::Satisfiable({{}})
638                       : WatchedLiteralsSolverImpl(Vals).solve();
639 }
640 
641 } // namespace dataflow
642 } // namespace clang
643