<div dir="ltr">Hi!<br><br>In an earlier email I wrote about how LivenessAnalysis works in Clang [1], and hinted at how the static analyzer takes advantage of it. I incorrectly advertised Liveness and UninitializedVariables to be the only two dataflow analyses written in Clang, whereas consumed annotation checking [2] and thread safety analysis [3] are also utiliting dataflow. Lifetime analysis hasn't landed yet [24-28], but is also great to study.<br><br>The point of this mail is to take an objective look at these algorithms in terms of their "dataflowness", identify their similarities and differences, and what techniques they implement that could benefit all of them. To be clear, dataflow describes a wide ranges of analyses -- we're looking at flow sensitive, intraprocedural ones.<br><br>I invite you to point out any and all the incomplet and inkorrek items in this survey.<br><br>---=== The many struggles of C++ data flow analysis in Clang ===---<br><br>Not all data flow struggles are C/C++, or Clang specific, but some are, and universal difficulties (aliasing, for instance) might be obfuscated by them more than usual. The following is a non-comprehensive list of such issues all data flow algorithms in Clang face.<br><br>---  Reads/writes ---<br><br>A common theme among data flow algorithms is looking for gens (generations, or in other words "reads" or "loads") or kills (in other words "writes" or "stores") of either variables or values. When we say GEN or KILL set, we mean a set of variables generated, or killed at a given statement. GEN and KILL sets can be defined for CFGBlocks as well from the sets of the contained statements. Many data flow analyses are defined with a fixpoint algorithm on GEN/KILL sets. In literature, we assume that these sets are precalculated, but that is rarely a case for Clang.<br><br>In literature, most data flow algorithms are defined and showcased on either some simple pseudo code, or an instruction set in a three address form:<br><br>x <- y + z<br><br>This is a very significant simplification, as the appearance of a variable's in Clang's AST (DeclRefExprs) is not very telling of its context. [10, 11, 13] all mention this a very significant difficulty in Clang: only the surrounding context, and even that with great difficulties, can tell whether a variable is written or read. LLVM IR is largely void of this problem, but in [14] Chris Lattner provides a lengthy reasoning why it'd be next to impossible to lower to LLVM IR, conduct analysis, but still produce diagnostics in the original source code. LLVM IR is still tempting enough though that we have ongoing projects to get some use out of it [15].<div><br></div><div>This poses another problem: in literature, transfer functions are responsible for the flow of dataflow information through a statement. For liveness, a transfer function for "x = a;" would tell that "a" should be added to liveness set, and "x" should be removed. In clang however, where transfer functions are implemented with statement visitors, the fact that we need substantial contextual information for any given statement is sometimes a problem.</div><div><br>There is a push for an MLIR dialect for C++. You can find a discussion in [19], and there will also be talk on the next dev meeting, but that will happen after this mail [17, 18].<br><br>--- Classic data flow issues: Aliasing, function calls, unfeasible execution paths ---<br><br>Aliasing is an often discussed, unavoidable obstacle for C/C++, and intraprocedural of most dataflow algorithms is also problematic.<div><br><font face="monospace">int a = 5;<br>int *p = &a;<br>foo(a, p);<br>// foo can not know that using the second parameter affects the first.<br>// Also: will foo write these arguments? Will it read them?</font><br><br>This naturally allows a third category next to gen/kill: unknown. On such a statement, the variable may be read or written, maybe neither, maybe both. Literature solves this by:<div>* Overestimating: If we intend to emit diagnostics for values computed but never read (dead values), we say that it is not read only if it is killed without ever being read, or occuring is such an unknown statement (we overestimate the liveness sets),</div><div>* Underestimating: For uninitialized variable misuse, we only look for variables that were read, but never killed up to that point or appeared in an unknown context (we underestimate the uninitialized variable sets).</div><div>However, in practice, its worth keeping track of such unknown events. Some analyses go further, and assign a sort of confidence level: "we're not absolutely sure whether this is kill, but its reasonable to believe that it isn't".<br><br>Unfeasible execution paths are also an inherent problem for dataflow.</div><div><font face="monospace"><br></font></div><div><font face="monospace">if (a)</font></div><div><font face="monospace">  x = 0;</font></div><div><font face="monospace">if (!a)</font></div><div><font face="monospace">  10 / x;</font><br><br>Sure the flow of control will never go through both of these then branches (in a single threaded environment), but that is an undecidable problem in dataflow. The solution here is the same as above, under or over approximation. The foundation of this lies in lattice theory, which is explained in [30, 31].<br><br>--- Records, fields, methods ---<br><br>Suppose you need to conduct data flow analysis on the following code in clang, and need to identify variables in the code:<br><br>voi<font face="monospace">d A::foo(int u) {<br>  int i;<br>  this->a = 5;<br>  S s;<br>  s.a->get().b = 6;<br>  (*s.a).c = 9;<br>  // ...<br>}</font><br><br>The parameter "u" and "i" are easy enough, they are both VarDecls, and so is the implicit this parameter. "s" is also a VarDecl, but its fields aren't, they are FieldDelcs. An option would be to keep record of a chain of fields -- for s.a.b.x.z, a pair like this would indeed identify which memory region we're describing: (s, [a, b, x, z]). However, there are a lot of ways to obfuscate this specific memory region, for example, if we ever support some aliasing the variety of ways dereferencing can be expressed will pose a challenge. Simply put, its difficult to compare expressions [16].<br><br>---=== 1. LivenessAnalysis ===---<br><br>Liveness answers the question whether value computed at one point will ever be used before being overwritten:<br><br><font face="monospace">int a = 5;<br>a = 6;<br>if (rand())<br>  process(a);<br>//...</font><br><br>The value 5 from 'a' will never be read, meaning that 'a' is not live from the point of its initialization until it is assigned 6. After that point it is live until the next time it's assigned, because there exists a path from the assignment to a read of 'a' without any interleaving assignments.<br><br>The product of the analysis is liveness sets (sets of variables or sets of expressions). They are calculated for each statement, and transitively, each CFGBlock. If a variable/expression is found in this set, it means that they are live (will be read from later) at that point. The algorithm is described and implemented as a</div><div>* Backward analysis: whether a value will be read is a property of the future</div><div>* May analysis: we're interested whether it *could* be read from, not whether its guaranteed. Coupled with the fact that infeasible execution paths are also analyzed, this will overapproxiate the actual liveness sets.</div><div><div><br></div><div>It was mentioned above that transfer functions require considerable context to know whether a statement writes/reads a variable. Transfer functions for DeclRefExpr that look for variables usages have a problem, namely that by the time a statement visitor reaches a DeclRefExpr the read/write information is already lost. So, how does Liveness solve this issue? Does it implement a pass that categorizes DeclRefExprs before the main analysis runs? It turns out, the fact that Liveness is a backward analysis allows it to gather this information on the go [34]:<br><br>For the following code snippet:</div><div><br><font face="monospace">void f() {<br>  int i;<br><br>  i = 5;<br>}</font><br></div></div><div><br></div><div>This is the generated CFG:</div><div><br></div><div><font face="monospace">void f()<br> [B2 (ENTRY)]<br>   Succs (1): B1<br><br> [B1]<br>   1: int i;<br>   2: 5<br>   3: i<br>   4: [B1.3] = [B1.2]<br>   Preds (1): B2<br>   Succs (1): B0<br><br> [B0 (EXIT)]<br>   Preds (1): B1</font><br></div><div><br></div><div>In B1, the 4th element, which is the assignment, is visited before the 3rd, where the written variable is, meaning that by the time the transfer function for DeclRefExpr is ran, Liveness could've already noted it as a write.</div><div><br></div><div>The analysis, as described in [4], which Clang follows closely, ignores the worst of the read/write problem. Only variable declarations and assignments are regarded as writes. If a DeclRefExpr pops up in any other context, it is seen as a read, even if its passed variables to function call as a non-const reference, etc. Also, the algorithm doesn't respect aliasing, and doesn't regard the fields of a record as a distinct, writable memory regions. However, there is still value in the analysis interpreted this way. The Static Analyzer conducts liveness analysis with some relaxations [1], and its results are used, with a few other techniques, to know how long a variable's memory region needs to be kept in the Environment. This simplicity also allows the algorithm to have a very simple implementation.<br></div><div><br>The way the Static Analyzer utilizes this analysis requires clang to keep the liveness sets for a while, making it the only dataflow analysis that doesn't immediately discard its results. This might explain the choice of data structures, which is, contrary to what many literature suggests (bitvectors), are ImmutableSets. Since these sets are accessed far more regularly then the result of other analyses, its a non-trivial claim that either solution is faster than the other.<div></div><div><br></div><div>[1] is purely dedicated to Clang's Liveness, and is a great source for further reading.</div><div><div><br></div><div>--- Strengths / Deficiencies ---<br><br>+ Straightforward implementation without many cornercase handling or struggle with the difficult read/write problem.</div><div>+ The result of the analysis is cached through clang::ManagedAnalysis, and is easily to query.</div><div><br></div><div>- Has some crude hacks, the code is a bit challenging to follow and is rather poorly documented.</div><div>- Non-relaxed liveness analysis has tests, but isn't actually used anywhere in the codebase.</div><div>- The choice of data structures is probably inefficient.</div></div><br>---=== 2. UninitializedVariables ===---<br><br>The point of this analysis is self explanatory -- catch the usage of a variable that has been initialized. There are a variety of severities we can define: a variable is uninitialized on all paths leading to the usage, or only on some (which can be divided into further subcategories).<br><br>Some literature, like [4], talks about uninitialized variable analysis as a side product of liveness analysis, while others, like [30], describe it as a distinct analysis. [4] isn't necessarily wrong, if a variable is known to be uninitialized but is live, then an uninitialized value is read on some path of execution. However, liveness is an over-approximating algorithm, meaning this path of execution might be infeasible. For diagnostics, uninitialized variables should be under-approximating to avoid false positives. On the implementation side, the categorization of statements as variable reading/writing requires far more sophistication then what liveness offers. For this reason, this is a</div><div>* Forward analysis: Initializedness is a property of the past.</div><div>* Must analysis: We want to be sure that the variable is uninitialized. However, in practice, we're a bit more lenient on this, as we shall see.</div><div><br>Uninitialized variables doesn't enjoy the advantage Liveness does regarding the categorization of statements as variable reading/writing, so it implements multiple passes:<br><br>--- First pass: ---<br><br>Clang doesn't have any precalculated KILL/GEN sets, though UninitializedVariables stops just short of doing that. As a distinct pass, it scans the code associated with the CFG (for the most part, that is a FunctionDecl), and classifies each DeclRefExpr whether its an initialization/write, read, read as a const reference, self initialization (int x = x;), or should be ignored by the analysis.<br><br><font face="monospace">void use(int x); // note that this is a pass-by-value parameter</font><br><font face="monospace"><br>int x;<br>if (rand())<br>  x = 5; // Write of x<br>use(x); // Read of x</font><br><br>--- Second pass: ---<br><br>This is where uninitialized variable usages are actually calculated. Indeed, this is reminiscent of liveness analysis: we assign an uninitialized variables set to each statement, initially with the information gathered from the first pass, then propagating it with a fixpoint algorithm. We found an uninitialized variable use, when the fixpoint algorithm halts, and a set associated with a statement notes a variable as uninitialized, yet the same statement also reads this variable.</div><div><br></div><div>During the fixpoint calculation, there are a few extra steps to be taken that are absent in LivenessAnalysis:<br><br>* Variable declarations (which are not DeclRefExprs, and as such won't be classified in the first pass), and their lack of initialization are noted here.<br>* Handling of special cases: inline asm, ObjectiveCMessageExpr, OMPExecutableDirective<br>* If a variable read is found where the variable is sometimes uninitialized (not on all paths leading to the read), we'll look for block edges that unconditionally lead to an uninitialized variable. This is used to say stronger than 'may be uninitialized', namely that 'either it's used uninitialized or you have dead code'. There is a great block of comments that details this in the actual code [5].<br><br>--- Third pass ---<br><br>Though technically this is an implementation detail, a third pass is used to emit diagnostics. Block visitations can be accompanied with a callback object, which is a caching object in the second pass, and a report emission object in the third.</div><div><br></div><div>--- Strengths / Deficiencies ---<br><br>+ Has a far more sophisticated understanding of when a variable is read from / written to.</div><div>+ Has a great categorization system. Variables that are maybe uninitialized can be analyzed further to judge how likely the lack of initialization is.</div><div><br></div><div>- Lacks support for record fields.</div><div>- The third pass looks like a hack, and could probably be factored out.</div><div>- The analysis results are non-reusable. Is not a clang::ManagedAnalysis.<br><br>---=== 3. Thread Safety analysis ===---<br><br>Clang's oldest dataflow analysis, Liveness, was committed on the 6th of September, 2007 [6]. Thread safety analysis isn't much younger though, the earliest proposals and discussions popped up in July, 2008 on the GCC mailing lists [7-8]. Its eventual port to clang came a few years later in June 2011, which was proposed by Caitlin Sadowski [9], and was presented at the 2011 LLVM Developers' Meeting [10].<br><br>The analysis is a subject of a 2014 article [11], notably after the analysis matured some. It is an amazing piece of literature, very easily digestible, but doesn't sacrifice anything for readability. If you want to learn more about many of the challenges data flow presents in Clang, or thread safety checking in general, I highly recommend you read it. You can assume that anything I write about this analysis is cited from either this paper or the similarly amazing dev talk.<br><br>The domain of the analysis is different this time: Liveness looks for expressions, and both Liveness and UninitializedValue look for local variables. The domain of Thread Safety analysis is on _annotated_ member or non-member functions in addition to _annotated_ variables.<br><br>Annotations are a very important component of this analysis. The user annotates which variable or function is guarded by which mutex. Functions that lock or unlock a mutex are annotated likewise. Annotations on functions have an interesting effect; though the analysis is still intraprocedural, it will be able to argue across function calls and achieve some path-sensitivity [25 at 3:27]: If a function's precondition is to have a set of mutexes locked, that must be annotated (otherwise Clang will assume said mutexes are unlocked), and this precondition can be checked on the caller side. If the precondition and the postcondition have different set of lucked mutexes, that must be annotated as well (otherwise Clang will emit a warning), so the callee can check whether the post condition holds.</div><div><br></div><div>A set of locked mutexes are computed for each statement in a block. The set for the last statement in the block becomes the set associated with the block.<br><br><font face="monospace">// Some CFGBlock, suppose that no mutexes are locked before reaching it<br>{<br>  /*{}      */ std::mutex mu, um;<br>  /*{}      */ int a GUARDED_BY(mu);<br>  /*{mu}    */ mu.lock();<br>  /*{mu, um}*/ um.lock();<br>  /*{mu, um}*/ foo();<br>  /*{um}    */ mu.unlock();<br>}<br>// {um} is the lock set associated with this block</font><br><br>Suppose you have the following CFG:<br>   <font face="monospace"><br>             -> [B3] -><br>           /            \<br>[B1] -> [B2] -> [B4] -> [B5] -> [B6]</font><br><br>Suppose the blocks lock the following mutexes before propagating this information with the use of dataflow:<br><font face="monospace"><br>             -> {mu} -><br>           /            \<br>{  } -> {  } -> {mu} -> {  } -> {(unlocks mu)}</font><br><br>How do we propagate this information throughout the graph? Following the classic fixpoint algorithms most dataflow analyses implement, this is simple enough; since all ascendant blocks to B5 locks "mu", it must be locked in B5 as well (there is no need to think about under/over approximation). Since B6 unlocks mu, it won't be present in its lock set.<br><font face="monospace"><br>             -> {mu} -><br>           /            \<br>{  } -> {  } -> {mu} -> {mu} -> {  }</font><br><br>Suppose B4 doesn't lock "mu" (for instance, B2 branches on mu.try_lock()). In that case, the joint point at B5 will have differing incoming lock sets:<br><font face="monospace"><br>             -> {mu} -><br>           /            \<br>{  } -> {  } -> {  } -> {  } -> {(unlocks mu)}</font><br><br>What should the lock set of B5 be after the analysis? What if we introduce a loop:<br><font face="monospace"><br>             -> {mu} -><br>           /            \<br>{  } -> {  } -> {  } -> {  } -> {(unlocks mu)}<br>          \              /<br>           <-------------</font><br><br>We could decide that for each cases where we need to merge differing lock sets:<br><br>* We merge the sets (a may analysis, the lock sets will be overestimated)<br>* We intersect them (a must analysis, the lock sets will be underestimated)<br>* Note that the lock may be either locked/unlocked, similarly to uninitialized variables analysis.<br><br>Thread safety analysis cuts the Gordian knot [12] by asserting that code that allows differing lock sets on merge points is error prone, and emits a warning. This is a very significant simplification, since there is no longer a need for a fixpoint algorithm, the sets can be calculated and propagated in O(N) time for a CFG with N blocks. It could be argued that this is too restrictive, but [11 p5.] is confident that that allowing such constructs doesn't have a real practical benefit, and is a sign of code smell.</div><div><br>--- Thread Safety's own intermediate language ---<br><br>Thread Safety analysis allows the annotation of methods and pointees. This poses a very big problem: the comparison of expressions [16].<br><font face="monospace"><br> class A { Mutex mu; int dat GUARDED_BY(this->mu); }<br> class B { A a; }<br><br> void foo(B* b) {<br>   (*b).a.mu.lock();     // locks (*b).<a href="http://a.mu" target="_blank">a.mu</a><br>   b->a.dat = 0;         // substitute &b->a for 'this';<br>                         // requires lock on (&b->a)->mu<br>   (b-><a href="http://a.mu" target="_blank">a.mu</a>).unlock();   // unlocks (b-><a href="http://a.mu" target="_blank">a.mu</a>)<br> }</font><br><br>There is only a single mutex that is locked/unlocked, but the AST makes this difficult to understand. Just as the code states, knowing that b->a.dat is guarded by b-><a href="http://a.mu" target="_blank">a.mu</a> is a non-trivial step as well. For this reason, stunningly, Thread Safety Analysis lowers Clang expressions, implementing its very own IR, a Typed Intermediate Language, or TIL.<br><br>Quoting from [20] (this has changed a lot since then, but captures the essence of it):<br><br>"Unlike a clang Expr, a SExpr does not capture surface syntax, and it does not distinguish between C++ concepts, like pointers and references, that have no real semantic differences. This simplicity allows SExprs to be meaningfully compared, e.g.<br>        (x)          =  x<br>        (*this).foo  =  this->foo<br>        *&a          =  a"<br><br>The implementing code is well documented, but I failed to find discussion previous to the first commit, or some high level description of it. [40] offers some, but is very in medias res. I'm honestly not confident enough in my knowledge of IRs to talk about this much. If you have any pointers, any and all would be appreciated!</div><div><br></div><div>--- Some dataflow aspects ---</div><div><br></div><div>Thread safety is a forward analysis. To detect an improper write on a variable that should be guarded by a mutex implies that the read/write problem needs to be solved. However, unlike UninitializedVariables analysis which is also a forward analysis, this isn't done in a distinct pass. The reason behind this is that thread safety doesn't have a transfer function for DeclRefExpr. Instead, it has a transfer function for each context that might access a variable: unary/binary operators, lvalue-to-rvalue casts, call expressions, etc, translates its argument to TIL, and checks whether it was a variable of interest.</div><div><br></div><div>Whenever a function that locks/unlocks a mutex is found, the corresponding mutex expression (for "a.b.Lock()", this is "a.b", for a function annotated with "ACQUIRE(mu)", this is "mu") is translated to TIL. These TIL expressions form the actual lock sets. When a variable is found to have been read/written, the analyzer checks whether the guarding mutex is in the lock set.</div><div><br></div><div>This analysis doesn't care about the aliasing issue. This can cause false positives, but the rationale is that these kinds of reports are an acceptable sacrifice for greater coverage.</div><div><br></div><div>That is all I was interested -- I can't recommend [11] and [10] enough if you wanna dive deeper, or peek at the code, it practically reads itself aloud.</div><div><div></div><div><div><br></div><div>--- Strengths / Deficiencies ---<br><br>+ Exceptional documentation. Articles, design discussions are readily (and without charge!) available on  the web.<br>+ Has strong C++ support, it is able to translate Exprs into its own intermediate language. Seriously, that is nuts.</div><div>+ Actively maintained.</div><div>+ O(n) analysis time for a CFG with n blocks.</div><div>+ Solves the read/write issue without a distinct pass.<br></div><div><br></div><div><div></div><div>- The analysis results are non-reusable. Is not a clang::ManagedAnalysis.</div></div><div>- TIL seems to be severely undertested. You can litter a lot of llvm_unreachables in the code, and no tests will fail.</div><div>- It seems like you can't annotate subfields, but that might as well be a feature:</div><div><font face="monospace"><br></font></div><div><font face="monospace">struct A { int i; };</font></div><div><font face="monospace">struct B {</font></div><div><font face="monospace">  A a; // how to annotate B::a.i?</font></div><div><font face="monospace">};</font></div></div><br>---=== 4. Consumed analysis ===---<br><br>Before its implementation, consumed analysis was called uniqueness analysis [21]. In his proposal, Christian Wailes explains the motivations in great depths in [22]. In terms of development, this analysis laid dormant for about 5 years, but has received a few improvements last year.<br><br>Consumed analysis is very similar, but not as high-tech as Thread Safety is; it is also a single-pass, annotation based algorithm, that tracks a set of consumed/unconsumed variables, instead of a set of locked mutexes. While I didn't devote too much time to this analysis (party because it doesn't have as much available discussion as Thread Safety, and party because it seemed really similar to it), I personally think this is the least mature of the bunch.<br><br>---=== 5. Lifetime analysis ===---<br><br>There is a fifth major data flow analysis in clang I'm aware of, though it isn't a part of upstream clang: Lifetime analysis. This was based largely on Herb Sutter's paper [29], and has been the subject of numerous talks [24-28].<br><br>[29] is an amazing, step-by-step description on the lifetime algorithm. [25] is a great talk about how this was implemented in Clang specifically, which was preceded by design discussion on the mailing list [32, 33]. Herb's paper and the dev talk alone are so thorough, I can't really do it any justice in this survey. As such, this mail will focus on the "dataflowness" of the algorithm, largely ignoring non-flow sensitive lifetime analyses and the kinds of ownership categories that were proposed with annotations, etc. This simplification quickly boils the discussion down to what is essentially a points-to analysis.</div><div><br></div><div>Points-to analysis collects a set of memory regions for each pointer it might point to at different points of the program. If this set contains null or invalid, that is a sign of a programmer error. This implies a</div><div><br></div><div>* Forward analysis: what a pointer will point to is a property of the future</div><div>* May analysis: we are interested in the set of memory regions the pointer might point to across all paths in the CFG, meaning that we're overapproximating the real points-to set.</div><div><br></div><div>The analysis thoroughly defines the semantics of the points-to sets, or psets, as literature calls it. Similarly to thread safety analysis with try_lock(), these sets may change at a condition point as well, should the a pointer in the pmap (which maps pointers to their psets) participate in them:</div><div><br></div><div><font face="monospace">if (p == q) {</font></div><div><font face="monospace">  // pset(p) == pset(q)</font></div><div><font face="monospace">}</font></div><div><font face="monospace">if (p) {</font></div><div><font face="monospace">  // pset(</font><span style="font-family:monospace">p) doesn't contain null</span></div><div><font face="monospace">}</font></div><div><br></div><div>They are affected by, well, lifetime:</div><div><br></div><div><font face="monospace">int *p; // pset(p) == {invalid}</font></div><div><font face="monospace">{</font></div><div><font face="monospace">  int x;</font></div><div><font face="monospace">  p = &x // pset(p) == {&x}</font></div><div><font face="monospace">} // pset(p) == {invalid}</font></div><div><font face="monospace">*p = 5; // warning</font></div><div><br></div><div>Asserts pose a serious problem for lifetime analysis in particular. Suppose you have the following assert:</div><div><br></div><div><font face="monospace">assert(p && q);</font></div><div><font face="monospace">...</font></div><div><font face="monospace"><br></font></div><div><font face="monospace">(bool)(p && q) ? 0 : abort(); // assert macro expanded</font></div><div><font face="monospace">...</font></div><div><br></div><div>And the CFG would look like this:</div><div><font face="monospace"><br></font></div><div><font face="monospace">    ------------>           ----> [abort()]</font></div><div><font face="monospace">  /              \        /</font></div><div><font face="monospace">[p] -> [q] -> [(bool)(p && q)] -> [...]</font></div><div><br></div><div>The path on which pset(p) == {null} merges with the path where pset(p) doesn't contain null, before the nonreturn abort() block is reached. Lifetime analysis solves this by an amazing technique; when it encounters such a pattern, both psets for the false and true branches are kept, doing a sort of local pathsensivity. Later, on the next branch, the the appropriate set is propagated to the true/false paths.</div><div><br></div><div>Thread safety neatly avoids with a distinct annotation (ASSERT_EXCLUSIVE_LOCK) that can be used instead of the standard assert. Liveness, UninitializedVariables sets don't change on conditions, so they aren't affected.<br></div><div><div><br></div><div>A may analysis in this context is risky. The set may have included null or invalid from an infeasible path of execution. To help filter out the reports, lifetime analysis employs an array of great tricks to find reports that are far more likely to be true positives. Such is the case when an assignment of null to a pointer and a dereference of that pointer is in a dominance or post-dominance relationship, similar to what was written about UninitializedValues. Its hard to tell whether a statement that adds null/invalid to a pset is a reaching definition to the dereference point, but there is no reaching definitions in clang yet, so dominance sets must suffice for the time being.</div></div><div><br></div><div>Lifetime analysis was conceptualized with strong C++ support from the get-go. Records object that have an Owner data member are Owners themselves, non-Owner record objects that have a Pointer data member are Pointers, and non-Owner, non-Pointer record objects are Aggregates (I left a lot of rules out, see [29 p8-10] for details). Owners and Pointers are modeled as a single variable like any other non-record object, and aggregates are exploded, each field is regarded as a variable:</div><div><font face="monospace"><br></font></div><div><font face="monospace">struct A { int x, y; };</font></div><div><font face="monospace">struct B { A a; int z; };</font></div><div><font face="monospace"><br></font></div><div><font face="monospace">B b; // variables: b.a.x, b.a.y, b.a, b.z, b</font></div><div><br></div><div>The Variable [25] class accurately captures the domain of the analysis. It gracefully handles CXXThis, temporaries and local variables.</div><div><br></div><div>As the psets are calculated, the read/write problem pops up naturally. [29 p12-24] thoroughly explains what the solution is; lets see an example before the explanation:</div><div><br></div><div><font face="monospace">a = &b.a;</font></div><div><br></div><div>Relevant part of the CFGBlock:</div><div><br></div><div><font face="monospace">4: b<br></font></div><div><font face="monospace">5: [B1.4].a<br>6: &[B1.5]<br>7: aptr<br>8: [B1.7] = [B1.6]</font><br></div><div><br></div><div>The created psets:</div><div><font face="monospace"><br></font></div><div><font face="monospace">Set RefersTo[DeclRefExpr] = (b)<br>Set RefersTo[MemberExpr] = (b.a)<br>Set PSetsOfExpr[UnaryOperator] = (b.a)<br>Set RefersTo[DeclRefExpr] = (aptr)<br>PMap[(aptr)] = (b.a)<br>Set RefersTo[BinaryOperator] = (aptr)</font><br></div><div><br></div><div>At CFGElement 4, "b" is assigned the pset {b}, at E5 "b.a" is assigned {b.a}, at E6 "&b.a" is assigned {b.a}, and at last, at E7 "aptr" is assigned {aptr}. The transfer function for the assignment sees that the pset on the LHS, {aptr}, resolves to the Variable "aptr", and assigns it the pset on the RHS, {b.a}.<br></div><div><br></div><div>In essence, the transfer function for each expression calculates their respective psets, while the transfer function for some expressions propagate these sets. This implies that at the point of a DeclRefExpr, the analysis doesn't need to know whether the pset is in the context of an read or write.</div><div><br></div><div>The domain of this analysis is entirely different than liveness or uninitialized variables, so what was previously mentioned as GEN/KILL sets don't make sense here. Also, [29] calls a variable killed when it goes out of scope, not when it is written.</div><div><div><br></div><div>--- Strengths / Deficiencies ---</div></div><div><br></div><div>+ Unlike other analyses, the relevant literature is centered around C++, so the challenges that the language poses doesn't present an immediate engineering problem.<br></div><div>+ Exceptionally well documented in literature/talks.<br></div><div>+ The same algorithm is already implemented in MSVC, so it is battle-tested.<br></div><div>+ Excellent support for C++ via the Variable class.<br></div><div>+ Solves the read/write problem in a single pass as a forward analysis.<br></div><div><div><br></div><div><div></div><div>- The analysis results are non-reusable. Is not a clang::ManagedAnalysis.</div></div></div><div>- Still WIP, it uses inefficient data structures, and has a lot of TODOs/FIXMEs.</div><div>- Has to compensate for the fact that psets are overestimated, but lacks the toolset to do it particularly well.</div><div><br></div><div>---=== 6. Reaching definitions? ===---</div><div><br></div><div>If you wanna see how would somebody implement a dataflow algorithm without knowing what on earth dataflow even is, or have done any meaningful research, I recommend looking through my earlier works. The idea to implement this was first fetched in a GSoC meeting in June 11th, 2019, and the first mail on the list was [36]. Conversations about using it as a part of my GSoC to help on the static analyzer's report generation followed in [37, 41]. Since then, it popped up as an idea here and there, the above mentioned links will guide you to them, if you care.</div><div><br></div><div>At this point, I was confident in my ability to implement this algorithm, because I read the relevant wikipedia article, and [4]'s relevant chapter. I never understood what transfer functions are, let alone what lattice theory is, and never bothered to look at other dataflow analyses. [38] is the latest version I uploaded, and the questions raised made me realize how far behind I was truly lagging. Hence this survey!</div><div><br></div><div>---=== Conclusion ===---</div><div><br></div><div>[31 chapter 9.3] describes a dataflow analysis framework as follows: it is a (D, V, ^, F) quadruple, where</div><div>* D is the direction of the dataflow,<br>* V is the lattice, which includes the domain of the analysis,</div><div>* ^ is the meet operator,</div><div>* F: V -> V, a family of transfer functions.</div><div><br></div><div>Out of these 4, we have D factored out [39], and F, if we regard statement visitors as such. As for the other two, an agreement on the most efficient data structure with a merge/intersect operation would tie things together. All dataflow algorithms above need to manage sets for each statement in the CFG, and these sets are usually created from one another. Uninitialized variables and thread safety, and literature in general agree that bitvectors are a great choice, yet both of these analyses implement their own solution.</div><div><br></div><div>No analyses but liveness is reusable.</div><div><br></div><div>Support for the fields of a record are only supported by thread safety and lifetime. Thread safety's TIL is amazing, but it is also TIL's only user, and it only uses a tiny fraction of it. Also, as a compiler novice myself, I found that it drastically increased the barrier of entry to its codebase, though I'm yet to study IRs in depth. Lifetime's approach is much simpler, and I admit to have not understood what really justifies TIL.</div><div><br></div><div>For GEN/KILL analyses, such as liveness, uninitialized variables and reaching definitions, it should be possible to factor a lot of knowledge out about what statements read/write a variable. However, these analyses don't always agree on what is a GEN or KILL, so any attempt at refactoring must be configurable to some extent.</div><div><br>---=== Further reading ===---<br><br>I'm hardly a scholar on dataflow analyses, and I haven't taken all of the available compiler studies related courses in my uni. Though I'm trying to make a decent dent in all the great books and scholarly articles I have access to, I've got more to go; here are some sources I used and can recommend if you are looking for more dataflow knowledge:<br><br>* Engineering a Compiler [4] is an excellent book on compiler design. It starts scanners, parsers, talks about intermediate representations, various forms of dataflow analyses, optimization all the way to code generation. As one can tell, this isn't laser focused on static analysis for diagnostic purposes, and definitely aims to use the fruits of static analysis mainly for optimization. Nevertheless, static analyses engineered for optimization are still an invaluable tool for spotting programming errors. Chapters on intermediate representations and dataflow analyses are a great read, though in my view they don't trivially translate to how one can implement them in Clang.<br><br>* Static Program Analysis [30] is an amazing and completely free book on static analysis. It takes a large step towards formality compared to [4], and offers a numerous exercises for the reader, though isn't quite as thorough as [31]. It presents lattice theory, a foundation of the presented analyses, and shows that building on this theory gracefully handles the problem of over/under approximation. This book gave me a far better understanding of dataflow, and stands a lot closer to what I've observed in Clang. Up to this point, this has definitely been my favourite book to learn from regarding this subject.<br><br>* Compilers: Principles, Techniques and Tools [31], AKA the second edition of the infamous dragon book. As I understand it, its a bigger and better version of [4], but doesn't have same target audience. [4] is a lot friendlier to beginners, and doesn't delve into the theoretical background of a topic unless its necessary to understand the chapter. It is more formal, laying out the mathematical foundations for most items. Chapter 9. "Machine independent optimizations" is a dataflow treasure chest, practically a must read, but as a novice, I definitely appreciated that I already read up on dataflow before.<br><br>* For practical applications of dataflow analyses, all the references below are great; they are mostly a sample of design discussions/patches of the past 12 years in Clang.<br><br>---=== Closing words ===---<br><br>Special thanks to Gábor Horváth and Gábor Márton for helping me collect some relevant literature and discussions! I definitely plan to spin parts of this mail into a paper of some sort in the future, please don't beat me to it :)<br><br>Cheers!<br>Kristóf Umann<br><br>---=== References ===---<br><br>[1] [cfe-dev] [analyzer] An in-depth look at Liveness Analysis in the Static Analyzer, <a href="http://lists.llvm.org/pipermail/cfe-dev/2020-July/066330.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2020-July/066330.html</a><br>[2] <a href="https://clang.llvm.org/docs/AttributeReference.html#consumed-annotation-checking" target="_blank">https://clang.llvm.org/docs/AttributeReference.html#consumed-annotation-checking</a>, clang/test/SemaCXX/warn-consumed-analysis.cpp<br>[3] <a href="https://clang.llvm.org/docs/ThreadSafetyAnalysis.html" target="_blank">https://clang.llvm.org/docs/ThreadSafetyAnalysis.html</a><br>[4] Cooper, Keith, and Linda Torczon. Engineering a compiler, second edition. Elsevier, 2011.<br>[5] <a href="https://github.com/llvm/llvm-project/blob/054704082b461418d3dac3a379792cdaf52d40b3/clang/lib/Analysis/UninitializedValues.cpp#L511" target="_blank">https://github.com/llvm/llvm-project/blob/054704082b461418d3dac3a379792cdaf52d40b3/clang/lib/Analysis/UninitializedValues.cpp#L511</a><br>[6] Added an early implementation of Live-Variables analysis built on source-level CFGs. This code may change significantly in the near future as we explore different means to implement dataflow analyses. <a href="https://reviews.llvm.org/rGb56a9909556aee1670e88adcf8b0a56dc25c5c9e" target="_blank">https://reviews.llvm.org/rGb56a9909556aee1670e88adcf8b0a56dc25c5c9e</a><br>[7] Thread safety annotations and analysis in GCC, <a href="https://gcc.gnu.org/pipermail/gcc/2008-June/177461.html" target="_blank">https://gcc.gnu.org/pipermail/gcc/2008-June/177461.html</a>, continuing in <a href="https://gcc.gnu.org/pipermail/gcc/2008-July/178359.html" target="_blank">https://gcc.gnu.org/pipermail/gcc/2008-July/178359.html</a><br>[8] C/C++ Thread Safety Annotations proposal, <a href="https://docs.google.com/document/d/1_d9MvYX3LpjTk3nlubM5LE4dFmU91SDabVdWp9-VDxc/edit" target="_blank">https://docs.google.com/document/d/1_d9MvYX3LpjTk3nlubM5LE4dFmU91SDabVdWp9-VDxc/edit</a><br>[9] [cfe-dev] Proposal for thread safety attributes for Clang, <a href="http://lists.llvm.org/pipermail/cfe-dev/2011-June/015899.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2011-June/015899.html</a>, continuing in <a href="http://lists.llvm.org/pipermail/cfe-dev/2011-July/015906.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2011-July/015906.html</a><br>[10] 2011 LLVM Developers’ Meeting: D. Hutchins “Thread Safety Annotations in Clang”, <a href="https://www.youtube.com/watch?v=1em66mRozm0&ab_channel=LLVM" target="_blank">https://www.youtube.com/watch?v=1em66mRozm0&ab_channel=LLVM</a><br>[11] Hutchins, DeLesley, Aaron Ballman, and Dean Sutherland. "C/c++ thread safety analysis." 2014 IEEE 14th International Working Conference on Source Code Analysis and Manipulation. IEEE, 2014.,<br>[12] <a href="https://en.wikipedia.org/wiki/Gordian_Knot" target="_blank">https://en.wikipedia.org/wiki/Gordian_Knot</a><br>[13] 2019 EuroLLVM Developers’ Meeting: T. Shpeisman & C. Lattner “MLIR: Multi-Level Intermediate Representation for Compiler Infrastructure, <a href="https://www.youtube.com/watch?v=qzljG6DKgic" target="_blank">https://www.youtube.com/watch?v=qzljG6DKgic</a><br>[14] [cfe-dev] LLVM Dev meeting: Slides & Minutes from the Static Analyzer BoF (2015. November) <a href="http://lists.llvm.org/pipermail/cfe-dev/2015-November/045872.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2015-November/045872.html</a><br>[15] [cfe-dev] [analyzer][RFC] Get info from the LLVM IR for precision, <a href="http://lists.llvm.org/pipermail/cfe-dev/2020-August/066537.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2020-August/066537.html</a><br>[16] <a href="https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h#L27" target="_blank">https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h#L27</a><br>[17] [cfe-dev] [analyzer][RFC] Get info from the LLVM IR for precision, mentioning the talk, <a href="http://lists.llvm.org/pipermail/cfe-dev/2020-August/066611.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2020-August/066611.html</a><br>[18] CIL : Common MLIR Dialect for C/C++ and Fortran, 2020 Virtual LLVM Developers' Meeting.<br>[19] [llvm-dev] MLIR for clang <a href="http://lists.llvm.org/pipermail/llvm-dev/2020-February/139192.html" target="_blank">http://lists.llvm.org/pipermail/llvm-dev/2020-February/139192.html</a><br>[20] Thread safety analysis: refactor to support more sophisticated handling. <a href="https://reviews.llvm.org/rC161690" target="_blank">https://reviews.llvm.org/rC161690</a><br>[21] [patch] Adding Consumed Analysis to Clang,  <a href="https://reviews.llvm.org/D1233" target="_blank">https://reviews.llvm.org/D1233</a><br>[22] [cfe-dev] Proposal for Uniqueness Analysis, <a href="http://lists.llvm.org/pipermail/cfe-dev/2013-July/030635.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2013-July/030635.html</a>, continuing in <a href="http://lists.llvm.org/pipermail/cfe-dev/2013-August/031331.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2013-August/031331.html</a><br>[23] <a href="https://github.com/mgehre/llvm-project/tree/lifetime" target="_blank">https://github.com/mgehre/llvm-project/tree/lifetime</a><br>[24] CppCon 2018: Herb Sutter “Thoughts on a more powerful and simpler C++ (5 of N)” <a href="https://youtu.be/80BZxujhY38?t=1095" target="_blank">https://youtu.be/80BZxujhY38?t=1095</a><br>[25] 2019 EuroLLVM Developers’ Meeting: G. Horvath & M. Gehre: Implementing the C++ Core Guidelines' Lifetime Safety Profile in Clang <a href="https://www.youtube.com/watch?v=VynWyOIb6Bk&ab_channel=LLVM" target="_blank">https://www.youtube.com/watch?v=VynWyOIb6Bk&ab_channel=LLVM</a><br>[26] CppCon 2018: “Implementing the C++ Core Guidelines’ Lifetime Safety Profile in Clang” <a href="https://www.youtube.com/watch?v=sjnp3P9x5jA&ab_channel=CppCon" target="_blank">https://www.youtube.com/watch?v=sjnp3P9x5jA&ab_channel=CppCon</a><br>[27] CppCon 2019: Gábor Horváth, Matthias Gehre “Lifetime analysis for everyone”, <a href="https://www.youtube.com/watch?v=d67kfSnhbpA&ab_channel=CppCon" target="_blank">https://www.youtube.com/watch?v=d67kfSnhbpA&ab_channel=CppCon</a><br>[28] Update on C++ Core Guidelines Lifetime Analysis. Gábor Horváth. CoreHard Spring 2019, <a href="https://www.youtube.com/watch?v=EeEjgT4OJ3E&ab_channel=corehard" target="_blank">https://www.youtube.com/watch?v=EeEjgT4OJ3E&ab_channel=corehard</a><br>[29] Herb Sutter: Lifetime profile v1.0 posted. <a href="https://herbsutter.com/2018/09/20/lifetime-profile-v1-0-posted/" target="_blank">https://herbsutter.com/2018/09/20/lifetime-profile-v1-0-posted/</a><br>[30] Møller, Anders, and Michael I. Schwartzbach. "Static program analysis." Notes. Feb (2012). <a href="https://users-cs.au.dk/amoeller/spa/spa.pdf" target="_blank">https://users-cs.au.dk/amoeller/spa/spa.pdf</a><br>[31] A. V. Aho, Monica S. Lam, R. Sethi, Jeffrey D. Ullman. "Compilers: Principles, Techniques and Tools", Pearson New International Edition, 2nd Edition</div></div></div><div>[32] [cfe-dev] [RFC] Adding lifetime analysis to clang, <a href="http://clang-developers.42468.n3.nabble.com/RFC-Adding-lifetime-analysis-to-clang-tt4063068.html" target="_blank">http://clang-developers.42468.n3.nabble.com/RFC-Adding-lifetime-analysis-to-clang-tt4063068.html</a> (the thread is very hard to follow on cfe-dev, so this site is a better bet)</div><div>[33] [cfe-dev] [RFC] Upstreaming Lifetime Function Annotations <a href="http://lists.llvm.org/pipermail/cfe-dev/2019-December/064067.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2019-December/064067.html</a><br>[34][analyzer][Liveness][NFC] Remove an unneeded pass to collect variables that appear in an assignment, <a href="https://reviews.llvm.org/D87518" target="_blank">https://reviews.llvm.org/D87518</a></div><div>[35] <a href="https://github.com/mgehre/llvm-project/blob/5fe46e6702499ec95280a46b3a56c7092ab44660/clang/include/clang/Analysis/Analyses/LifetimePset.h#L23" target="_blank">https://github.com/mgehre/llvm-project/blob/5fe46e6702499ec95280a46b3a56c7092ab44660/clang/include/clang/Analysis/Analyses/LifetimePset.h#L23</a></div><div>[36] [cfe-dev] [analyzer] Speaking about reaching definitions... <a href="http://lists.llvm.org/pipermail/cfe-dev/2019-June/062733.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2019-June/062733.html</a><br>[37] [cfe-dev] [analyzer] Using reaching definitions analysis for bug     report construction, <a href="http://lists.llvm.org/pipermail/cfe-dev/2019-July/062885.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2019-July/062885.html</a></div><div>[38] [analysis][analyzer] Introduce the skeleton of a reaching definitions calculator <a href="https://reviews.llvm.org/D76287" target="_blank">https://reviews.llvm.org/D76287</a></div><div>[39] [DataFlow] Factor two worklist implementations out, <a href="https://reviews.llvm.org/D72380" target="_blank">https://reviews.llvm.org/D72380</a></div><div>[40] [cfe-dev] Next step (discussion on TIL) <a href="http://lists.llvm.org/pipermail/cfe-dev/2014-May/036983.html" target="_blank">http://lists.llvm.org/pipermail/cfe-dev/2014-May/036983.html</a><br>[41] GSoC 2019: Enhancing bug reports in the Clang Static Analyzer, <a href="https://szelethus.github.io/gsoc2019/" target="_blank">https://szelethus.github.io/gsoc2019/</a></div></div>