1 //===---------- ExprSequence.cpp - clang-tidy -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ExprSequence.h"
10 #include "clang/AST/ParentMapContext.h"
11 
12 namespace clang {
13 namespace tidy {
14 namespace utils {
15 
16 // Returns the Stmt nodes that are parents of 'S', skipping any potential
17 // intermediate non-Stmt nodes.
18 //
19 // In almost all cases, this function returns a single parent or no parents at
20 // all.
21 //
22 // The case that a Stmt has multiple parents is rare but does actually occur in
23 // the parts of the AST that we're interested in. Specifically, InitListExpr
24 // nodes cause ASTContext::getParent() to return multiple parents for certain
25 // nodes in their subtree because RecursiveASTVisitor visits both the syntactic
26 // and semantic forms of InitListExpr, and the parent-child relationships are
27 // different between the two forms.
getParentStmts(const Stmt * S,ASTContext * Context)28 static SmallVector<const Stmt *, 1> getParentStmts(const Stmt *S,
29                                                    ASTContext *Context) {
30   SmallVector<const Stmt *, 1> Result;
31 
32   TraversalKindScope RAII(*Context, TK_AsIs);
33   DynTypedNodeList Parents = Context->getParents(*S);
34 
35   SmallVector<DynTypedNode, 1> NodesToProcess(Parents.begin(), Parents.end());
36 
37   while (!NodesToProcess.empty()) {
38     DynTypedNode Node = NodesToProcess.back();
39     NodesToProcess.pop_back();
40 
41     if (const auto *S = Node.get<Stmt>()) {
42       Result.push_back(S);
43     } else {
44       Parents = Context->getParents(Node);
45       NodesToProcess.append(Parents.begin(), Parents.end());
46     }
47   }
48 
49   return Result;
50 }
51 
52 namespace {
isDescendantOrEqual(const Stmt * Descendant,const Stmt * Ancestor,ASTContext * Context)53 bool isDescendantOrEqual(const Stmt *Descendant, const Stmt *Ancestor,
54                          ASTContext *Context) {
55   if (Descendant == Ancestor)
56     return true;
57   for (const Stmt *Parent : getParentStmts(Descendant, Context)) {
58     if (isDescendantOrEqual(Parent, Ancestor, Context))
59       return true;
60   }
61 
62   return false;
63 }
64 } // namespace
65 
ExprSequence(const CFG * TheCFG,const Stmt * Root,ASTContext * TheContext)66 ExprSequence::ExprSequence(const CFG *TheCFG, const Stmt *Root,
67                            ASTContext *TheContext)
68     : Context(TheContext), Root(Root) {
69   for (const auto &SyntheticStmt : TheCFG->synthetic_stmts()) {
70     SyntheticStmtSourceMap[SyntheticStmt.first] = SyntheticStmt.second;
71   }
72 }
73 
inSequence(const Stmt * Before,const Stmt * After) const74 bool ExprSequence::inSequence(const Stmt *Before, const Stmt *After) const {
75   Before = resolveSyntheticStmt(Before);
76   After = resolveSyntheticStmt(After);
77 
78   // If 'After' is in the subtree of the siblings that follow 'Before' in the
79   // chain of successors, we know that 'After' is sequenced after 'Before'.
80   for (const Stmt *Successor = getSequenceSuccessor(Before); Successor;
81        Successor = getSequenceSuccessor(Successor)) {
82     if (isDescendantOrEqual(After, Successor, Context))
83       return true;
84   }
85 
86   // If 'After' is a parent of 'Before' or is sequenced after one of these
87   // parents, we know that it is sequenced after 'Before'.
88   for (const Stmt *Parent : getParentStmts(Before, Context)) {
89     if (Parent == After || inSequence(Parent, After))
90       return true;
91   }
92 
93   return false;
94 }
95 
potentiallyAfter(const Stmt * After,const Stmt * Before) const96 bool ExprSequence::potentiallyAfter(const Stmt *After,
97                                     const Stmt *Before) const {
98   return !inSequence(After, Before);
99 }
100 
getSequenceSuccessor(const Stmt * S) const101 const Stmt *ExprSequence::getSequenceSuccessor(const Stmt *S) const {
102   for (const Stmt *Parent : getParentStmts(S, Context)) {
103     // If a statement has multiple parents, make sure we're using the parent
104     // that lies within the sub-tree under Root.
105     if (!isDescendantOrEqual(Parent, Root, Context))
106       continue;
107 
108     if (const auto *BO = dyn_cast<BinaryOperator>(Parent)) {
109       // Comma operator: Right-hand side is sequenced after the left-hand side.
110       if (BO->getLHS() == S && BO->getOpcode() == BO_Comma)
111         return BO->getRHS();
112     } else if (const auto *InitList = dyn_cast<InitListExpr>(Parent)) {
113       // Initializer list: Each initializer clause is sequenced after the
114       // clauses that precede it.
115       for (unsigned I = 1; I < InitList->getNumInits(); ++I) {
116         if (InitList->getInit(I - 1) == S)
117           return InitList->getInit(I);
118       }
119     } else if (const auto *Compound = dyn_cast<CompoundStmt>(Parent)) {
120       // Compound statement: Each sub-statement is sequenced after the
121       // statements that precede it.
122       const Stmt *Previous = nullptr;
123       for (const auto *Child : Compound->body()) {
124         if (Previous == S)
125           return Child;
126         Previous = Child;
127       }
128     } else if (const auto *TheDeclStmt = dyn_cast<DeclStmt>(Parent)) {
129       // Declaration: Every initializer expression is sequenced after the
130       // initializer expressions that precede it.
131       const Expr *PreviousInit = nullptr;
132       for (const Decl *TheDecl : TheDeclStmt->decls()) {
133         if (const auto *TheVarDecl = dyn_cast<VarDecl>(TheDecl)) {
134           if (const Expr *Init = TheVarDecl->getInit()) {
135             if (PreviousInit == S)
136               return Init;
137             PreviousInit = Init;
138           }
139         }
140       }
141     } else if (const auto *ForRange = dyn_cast<CXXForRangeStmt>(Parent)) {
142       // Range-based for: Loop variable declaration is sequenced before the
143       // body. (We need this rule because these get placed in the same
144       // CFGBlock.)
145       if (S == ForRange->getLoopVarStmt())
146         return ForRange->getBody();
147     } else if (const auto *TheIfStmt = dyn_cast<IfStmt>(Parent)) {
148       // If statement:
149       // - Sequence init statement before variable declaration, if present;
150       //   before condition evaluation, otherwise.
151       // - Sequence variable declaration (along with the expression used to
152       //   initialize it) before the evaluation of the condition.
153       if (S == TheIfStmt->getInit()) {
154         if (TheIfStmt->getConditionVariableDeclStmt() != nullptr)
155           return TheIfStmt->getConditionVariableDeclStmt();
156         return TheIfStmt->getCond();
157       }
158       if (S == TheIfStmt->getConditionVariableDeclStmt())
159         return TheIfStmt->getCond();
160     } else if (const auto *TheSwitchStmt = dyn_cast<SwitchStmt>(Parent)) {
161       // Ditto for switch statements.
162       if (S == TheSwitchStmt->getInit()) {
163         if (TheSwitchStmt->getConditionVariableDeclStmt() != nullptr)
164           return TheSwitchStmt->getConditionVariableDeclStmt();
165         return TheSwitchStmt->getCond();
166       }
167       if (S == TheSwitchStmt->getConditionVariableDeclStmt())
168         return TheSwitchStmt->getCond();
169     } else if (const auto *TheWhileStmt = dyn_cast<WhileStmt>(Parent)) {
170       // While statement: Sequence variable declaration (along with the
171       // expression used to initialize it) before the evaluation of the
172       // condition.
173       if (S == TheWhileStmt->getConditionVariableDeclStmt())
174         return TheWhileStmt->getCond();
175     }
176   }
177 
178   return nullptr;
179 }
180 
resolveSyntheticStmt(const Stmt * S) const181 const Stmt *ExprSequence::resolveSyntheticStmt(const Stmt *S) const {
182   if (SyntheticStmtSourceMap.count(S))
183     return SyntheticStmtSourceMap.lookup(S);
184   return S;
185 }
186 
StmtToBlockMap(const CFG * TheCFG,ASTContext * TheContext)187 StmtToBlockMap::StmtToBlockMap(const CFG *TheCFG, ASTContext *TheContext)
188     : Context(TheContext) {
189   for (const auto *B : *TheCFG) {
190     for (const auto &Elem : *B) {
191       if (Optional<CFGStmt> S = Elem.getAs<CFGStmt>())
192         Map[S->getStmt()] = B;
193     }
194   }
195 }
196 
blockContainingStmt(const Stmt * S) const197 const CFGBlock *StmtToBlockMap::blockContainingStmt(const Stmt *S) const {
198   while (!Map.count(S)) {
199     SmallVector<const Stmt *, 1> Parents = getParentStmts(S, Context);
200     if (Parents.empty())
201       return nullptr;
202     S = Parents[0];
203   }
204 
205   return Map.lookup(S);
206 }
207 
208 } // namespace utils
209 } // namespace tidy
210 } // namespace clang
211