clang-tools  5.0.0
UseAfterMoveCheck.cpp
Go to the documentation of this file.
1 //===--- UseAfterMoveCheck.cpp - clang-tidy -------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "UseAfterMoveCheck.h"
11 
12 #include "clang/Analysis/CFG.h"
13 #include "clang/Lex/Lexer.h"
14 
15 #include "../utils/ExprSequence.h"
16 
17 using namespace clang::ast_matchers;
18 using namespace clang::tidy::utils;
19 
20 
21 namespace clang {
22 namespace tidy {
23 namespace misc {
24 
25 namespace {
26 
27 /// Contains information about a use-after-move.
28 struct UseAfterMove {
29  // The DeclRefExpr that constituted the use of the object.
30  const DeclRefExpr *DeclRef;
31 
32  // Is the order in which the move and the use are evaluated undefined?
34 };
35 
36 /// Finds uses of a variable after a move (and maintains state required by the
37 /// various internal helper functions).
38 class UseAfterMoveFinder {
39 public:
40  UseAfterMoveFinder(ASTContext *TheContext);
41 
42  // Within the given function body, finds the first use of 'MovedVariable' that
43  // occurs after 'MovingCall' (the expression that performs the move). If a
44  // use-after-move is found, writes information about it to 'TheUseAfterMove'.
45  // Returns whether a use-after-move was found.
46  bool find(Stmt *FunctionBody, const Expr *MovingCall,
47  const ValueDecl *MovedVariable, UseAfterMove *TheUseAfterMove);
48 
49 private:
50  bool findInternal(const CFGBlock *Block, const Expr *MovingCall,
51  const ValueDecl *MovedVariable,
52  UseAfterMove *TheUseAfterMove);
53  void getUsesAndReinits(const CFGBlock *Block, const ValueDecl *MovedVariable,
54  llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
55  llvm::SmallPtrSetImpl<const Stmt *> *Reinits);
56  void getDeclRefs(const CFGBlock *Block, const Decl *MovedVariable,
57  llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
58  void getReinits(const CFGBlock *Block, const ValueDecl *MovedVariable,
59  llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
60  llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
61 
62  ASTContext *Context;
63  std::unique_ptr<ExprSequence> Sequence;
64  std::unique_ptr<StmtToBlockMap> BlockMap;
65  llvm::SmallPtrSet<const CFGBlock *, 8> Visited;
66 };
67 
68 } // namespace
69 
70 
71 // Matches nodes that are
72 // - Part of a decltype argument or class template argument (we check this by
73 // seeing if they are children of a TypeLoc), or
74 // - Part of a function template argument (we check this by seeing if they are
75 // children of a DeclRefExpr that references a function template).
76 // DeclRefExprs that fulfill these conditions should not be counted as a use or
77 // move.
78 static StatementMatcher inDecltypeOrTemplateArg() {
79  return anyOf(hasAncestor(typeLoc()),
80  hasAncestor(declRefExpr(
81  to(functionDecl(ast_matchers::isTemplateInstantiation())))));
82 }
83 
84 UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)
85  : Context(TheContext) {}
86 
87 bool UseAfterMoveFinder::find(Stmt *FunctionBody, const Expr *MovingCall,
88  const ValueDecl *MovedVariable,
89  UseAfterMove *TheUseAfterMove) {
90  // Generate the CFG manually instead of through an AnalysisDeclContext because
91  // it seems the latter can't be used to generate a CFG for the body of a
92  // labmda.
93  //
94  // We include implicit and temporary destructors in the CFG so that
95  // destructors marked [[noreturn]] are handled correctly in the control flow
96  // analysis. (These are used in some styles of assertion macros.)
97  CFG::BuildOptions Options;
98  Options.AddImplicitDtors = true;
99  Options.AddTemporaryDtors = true;
100  std::unique_ptr<CFG> TheCFG =
101  CFG::buildCFG(nullptr, FunctionBody, Context, Options);
102  if (!TheCFG)
103  return false;
104 
105  Sequence.reset(new ExprSequence(TheCFG.get(), Context));
106  BlockMap.reset(new StmtToBlockMap(TheCFG.get(), Context));
107  Visited.clear();
108 
109  const CFGBlock *Block = BlockMap->blockContainingStmt(MovingCall);
110  if (!Block)
111  return false;
112 
113  return findInternal(Block, MovingCall, MovedVariable, TheUseAfterMove);
114 }
115 
116 bool UseAfterMoveFinder::findInternal(const CFGBlock *Block,
117  const Expr *MovingCall,
118  const ValueDecl *MovedVariable,
119  UseAfterMove *TheUseAfterMove) {
120  if (Visited.count(Block))
121  return false;
122 
123  // Mark the block as visited (except if this is the block containing the
124  // std::move() and it's being visited the first time).
125  if (!MovingCall)
126  Visited.insert(Block);
127 
128  // Get all uses and reinits in the block.
129  llvm::SmallVector<const DeclRefExpr *, 1> Uses;
130  llvm::SmallPtrSet<const Stmt *, 1> Reinits;
131  getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
132 
133  // Ignore all reinitializations where the move potentially comes after the
134  // reinit.
135  llvm::SmallVector<const Stmt *, 1> ReinitsToDelete;
136  for (const Stmt *Reinit : Reinits) {
137  if (MovingCall && Sequence->potentiallyAfter(MovingCall, Reinit))
138  ReinitsToDelete.push_back(Reinit);
139  }
140  for (const Stmt *Reinit : ReinitsToDelete) {
141  Reinits.erase(Reinit);
142  }
143 
144  // Find all uses that potentially come after the move.
145  for (const DeclRefExpr *Use : Uses) {
146  if (!MovingCall || Sequence->potentiallyAfter(Use, MovingCall)) {
147  // Does the use have a saving reinit? A reinit is saving if it definitely
148  // comes before the use, i.e. if there's no potential that the reinit is
149  // after the use.
150  bool HaveSavingReinit = false;
151  for (const Stmt *Reinit : Reinits) {
152  if (!Sequence->potentiallyAfter(Reinit, Use))
153  HaveSavingReinit = true;
154  }
155 
156  if (!HaveSavingReinit) {
157  TheUseAfterMove->DeclRef = Use;
158 
159  // Is this a use-after-move that depends on order of evaluation?
160  // This is the case if the move potentially comes after the use (and we
161  // already know that use potentially comes after the move, which taken
162  // together tells us that the ordering is unclear).
163  TheUseAfterMove->EvaluationOrderUndefined =
164  MovingCall != nullptr &&
165  Sequence->potentiallyAfter(MovingCall, Use);
166 
167  return true;
168  }
169  }
170  }
171 
172  // If the object wasn't reinitialized, call ourselves recursively on all
173  // successors.
174  if (Reinits.empty()) {
175  for (const auto &Succ : Block->succs()) {
176  if (Succ && findInternal(Succ, nullptr, MovedVariable, TheUseAfterMove))
177  return true;
178  }
179  }
180 
181  return false;
182 }
183 
184 void UseAfterMoveFinder::getUsesAndReinits(
185  const CFGBlock *Block, const ValueDecl *MovedVariable,
186  llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
187  llvm::SmallPtrSetImpl<const Stmt *> *Reinits) {
188  llvm::SmallPtrSet<const DeclRefExpr *, 1> DeclRefs;
189  llvm::SmallPtrSet<const DeclRefExpr *, 1> ReinitDeclRefs;
190 
191  getDeclRefs(Block, MovedVariable, &DeclRefs);
192  getReinits(Block, MovedVariable, Reinits, &ReinitDeclRefs);
193 
194  // All references to the variable that aren't reinitializations are uses.
195  Uses->clear();
196  for (const DeclRefExpr *DeclRef : DeclRefs) {
197  if (!ReinitDeclRefs.count(DeclRef))
198  Uses->push_back(DeclRef);
199  }
200 
201  // Sort the uses by their occurrence in the source code.
202  std::sort(Uses->begin(), Uses->end(),
203  [](const DeclRefExpr *D1, const DeclRefExpr *D2) {
204  return D1->getExprLoc() < D2->getExprLoc();
205  });
206 }
207 
208 bool isStandardSmartPointer(const ValueDecl *VD) {
209  const Type *TheType = VD->getType().getTypePtrOrNull();
210  if (!TheType)
211  return false;
212 
213  const CXXRecordDecl *RecordDecl = TheType->getAsCXXRecordDecl();
214  if (!RecordDecl)
215  return false;
216 
217  const IdentifierInfo *ID = RecordDecl->getIdentifier();
218  if (!ID)
219  return false;
220 
221  StringRef Name = ID->getName();
222  if (Name != "unique_ptr" && Name != "shared_ptr" && Name != "weak_ptr")
223  return false;
224 
225  return RecordDecl->getDeclContext()->isStdNamespace();
226 }
227 
228 void UseAfterMoveFinder::getDeclRefs(
229  const CFGBlock *Block, const Decl *MovedVariable,
230  llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
231  DeclRefs->clear();
232  for (const auto &Elem : *Block) {
233  Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
234  if (!S)
235  continue;
236 
237  auto addDeclRefs = [this, Block,
238  DeclRefs](const ArrayRef<BoundNodes> Matches) {
239  for (const auto &Match : Matches) {
240  const auto *DeclRef = Match.getNodeAs<DeclRefExpr>("declref");
241  const auto *Operator = Match.getNodeAs<CXXOperatorCallExpr>("operator");
242  if (DeclRef && BlockMap->blockContainingStmt(DeclRef) == Block) {
243  // Ignore uses of a standard smart pointer that don't dereference the
244  // pointer.
245  if (Operator || !isStandardSmartPointer(DeclRef->getDecl())) {
246  DeclRefs->insert(DeclRef);
247  }
248  }
249  }
250  };
251 
252  auto DeclRefMatcher = declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
253  unless(inDecltypeOrTemplateArg()))
254  .bind("declref");
255 
256  addDeclRefs(match(findAll(DeclRefMatcher), *S->getStmt(), *Context));
257  addDeclRefs(match(
258  findAll(cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName("*"),
259  hasOverloadedOperatorName("->"),
260  hasOverloadedOperatorName("[]")),
261  hasArgument(0, DeclRefMatcher))
262  .bind("operator")),
263  *S->getStmt(), *Context));
264  }
265 }
266 
267 void UseAfterMoveFinder::getReinits(
268  const CFGBlock *Block, const ValueDecl *MovedVariable,
269  llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
270  llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
271  auto DeclRefMatcher =
272  declRefExpr(hasDeclaration(equalsNode(MovedVariable))).bind("declref");
273 
274  auto StandardContainerTypeMatcher = hasType(cxxRecordDecl(
275  hasAnyName("::std::basic_string", "::std::vector", "::std::deque",
276  "::std::forward_list", "::std::list", "::std::set",
277  "::std::map", "::std::multiset", "::std::multimap",
278  "::std::unordered_set", "::std::unordered_map",
279  "::std::unordered_multiset", "::std::unordered_multimap")));
280 
281  auto StandardSmartPointerTypeMatcher = hasType(cxxRecordDecl(
282  hasAnyName("::std::unique_ptr", "::std::shared_ptr", "::std::weak_ptr")));
283 
284  // Matches different types of reinitialization.
285  auto ReinitMatcher =
286  stmt(anyOf(
287  // Assignment. In addition to the overloaded assignment operator,
288  // test for built-in assignment as well, since template functions
289  // may be instantiated to use std::move() on built-in types.
290  binaryOperator(hasOperatorName("="), hasLHS(DeclRefMatcher)),
291  cxxOperatorCallExpr(hasOverloadedOperatorName("="),
292  hasArgument(0, DeclRefMatcher)),
293  // Declaration. We treat this as a type of reinitialization too,
294  // so we don't need to treat it separately.
295  declStmt(hasDescendant(equalsNode(MovedVariable))),
296  // clear() and assign() on standard containers.
297  cxxMemberCallExpr(
298  on(allOf(DeclRefMatcher, StandardContainerTypeMatcher)),
299  // To keep the matcher simple, we check for assign() calls
300  // on all standard containers, even though only vector,
301  // deque, forward_list and list have assign(). If assign()
302  // is called on any of the other containers, this will be
303  // flagged by a compile error anyway.
304  callee(cxxMethodDecl(hasAnyName("clear", "assign")))),
305  // reset() on standard smart pointers.
306  cxxMemberCallExpr(
307  on(allOf(DeclRefMatcher, StandardSmartPointerTypeMatcher)),
308  callee(cxxMethodDecl(hasName("reset")))),
309  // Passing variable to a function as a non-const pointer.
310  callExpr(forEachArgumentWithParam(
311  unaryOperator(hasOperatorName("&"),
312  hasUnaryOperand(DeclRefMatcher)),
313  unless(parmVarDecl(hasType(pointsTo(isConstQualified())))))),
314  // Passing variable to a function as a non-const lvalue reference
315  // (unless that function is std::move()).
316  callExpr(forEachArgumentWithParam(
317  DeclRefMatcher,
318  unless(parmVarDecl(hasType(
319  references(qualType(isConstQualified())))))),
320  unless(callee(functionDecl(hasName("::std::move")))))))
321  .bind("reinit");
322 
323  Stmts->clear();
324  DeclRefs->clear();
325  for (const auto &Elem : *Block) {
326  Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
327  if (!S)
328  continue;
329 
330  SmallVector<BoundNodes, 1> Matches =
331  match(findAll(ReinitMatcher), *S->getStmt(), *Context);
332 
333  for (const auto &Match : Matches) {
334  const auto *TheStmt = Match.getNodeAs<Stmt>("reinit");
335  const auto *TheDeclRef = Match.getNodeAs<DeclRefExpr>("declref");
336  if (TheStmt && BlockMap->blockContainingStmt(TheStmt) == Block) {
337  Stmts->insert(TheStmt);
338 
339  // We count DeclStmts as reinitializations, but they don't have a
340  // DeclRefExpr associated with them -- so we need to check 'TheDeclRef'
341  // before adding it to the set.
342  if (TheDeclRef)
343  DeclRefs->insert(TheDeclRef);
344  }
345  }
346  }
347 }
348 
349 static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg,
350  const UseAfterMove &Use, ClangTidyCheck *Check,
351  ASTContext *Context) {
352  SourceLocation UseLoc = Use.DeclRef->getExprLoc();
353  SourceLocation MoveLoc = MovingCall->getExprLoc();
354 
355  Check->diag(UseLoc, "'%0' used after it was moved")
356  << MoveArg->getDecl()->getName();
357  Check->diag(MoveLoc, "move occurred here", DiagnosticIDs::Note);
358  if (Use.EvaluationOrderUndefined) {
359  Check->diag(UseLoc,
360  "the use and move are unsequenced, i.e. there is no guarantee "
361  "about the order in which they are evaluated",
362  DiagnosticIDs::Note);
363  } else if (UseLoc < MoveLoc || Use.DeclRef == MoveArg) {
364  Check->diag(UseLoc,
365  "the use happens in a later loop iteration than the move",
366  DiagnosticIDs::Note);
367  }
368 }
369 
370 void UseAfterMoveCheck::registerMatchers(MatchFinder *Finder) {
371  if (!getLangOpts().CPlusPlus11)
372  return;
373 
374  auto CallMoveMatcher =
375  callExpr(callee(functionDecl(hasName("::std::move"))), argumentCountIs(1),
376  hasArgument(0, declRefExpr().bind("arg")),
377  anyOf(hasAncestor(lambdaExpr().bind("containing-lambda")),
378  hasAncestor(functionDecl().bind("containing-func"))),
379  unless(inDecltypeOrTemplateArg()))
380  .bind("call-move");
381 
382  Finder->addMatcher(
383  // To find the Stmt that we assume performs the actual move, we look for
384  // the direct ancestor of the std::move() that isn't one of the node
385  // types ignored by ignoringParenImpCasts().
386  stmt(forEach(expr(ignoringParenImpCasts(CallMoveMatcher))),
387  // Don't allow an InitListExpr to be the moving call. An InitListExpr
388  // has both a syntactic and a semantic form, and the parent-child
389  // relationships are different between the two. This could cause an
390  // InitListExpr to be analyzed as the moving call in addition to the
391  // Expr that we actually want, resulting in two diagnostics with
392  // different code locations for the same move.
393  unless(initListExpr()),
394  unless(expr(ignoringParenImpCasts(equalsBoundNode("call-move")))))
395  .bind("moving-call"),
396  this);
397 }
398 
399 void UseAfterMoveCheck::check(const MatchFinder::MatchResult &Result) {
400  const auto *ContainingLambda =
401  Result.Nodes.getNodeAs<LambdaExpr>("containing-lambda");
402  const auto *ContainingFunc =
403  Result.Nodes.getNodeAs<FunctionDecl>("containing-func");
404  const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>("call-move");
405  const auto *MovingCall = Result.Nodes.getNodeAs<Expr>("moving-call");
406  const auto *Arg = Result.Nodes.getNodeAs<DeclRefExpr>("arg");
407 
408  if (!MovingCall || !MovingCall->getExprLoc().isValid())
409  MovingCall = CallMove;
410 
411  Stmt *FunctionBody = nullptr;
412  if (ContainingLambda)
413  FunctionBody = ContainingLambda->getBody();
414  else if (ContainingFunc)
415  FunctionBody = ContainingFunc->getBody();
416  else
417  return;
418 
419  // Ignore the std::move if the variable that was passed to it isn't a local
420  // variable.
421  if (!Arg->getDecl()->getDeclContext()->isFunctionOrMethod())
422  return;
423 
424  UseAfterMoveFinder finder(Result.Context);
425  UseAfterMove Use;
426  if (finder.find(FunctionBody, MovingCall, Arg->getDecl(), &Use))
427  emitDiagnostic(MovingCall, Arg, Use, this, Result.Context);
428 }
429 
430 } // namespace misc
431 } // namespace tidy
432 } // namespace clang
SetLongJmpCheck & Check
Maps Stmts to the CFGBlock that contains them.
Definition: ExprSequence.h:104
StringHandle Name
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:275
Provides information about the evaluation order of (sub-)expressions within a CFGBlock.
Definition: ExprSequence.h:69
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
ASTContext * Context
static StatementMatcher inDecltypeOrTemplateArg()
llvm::SmallPtrSet< const CFGBlock *, 8 > Visited
static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg, const UseAfterMove &Use, ClangTidyCheck *Check, ASTContext *Context)
bool isStandardSmartPointer(const ValueDecl *VD)
std::unique_ptr< StmtToBlockMap > BlockMap
bool EvaluationOrderUndefined
std::unique_ptr< ExprSequence > Sequence
const DeclRefExpr * DeclRef
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:416