1 // MoveChecker.cpp - Check use of moved-from objects. - 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 defines checker which checks for potential misuses of a moved-from
10 // object. That means method calls on the object or copying it in moved-from
11 // state.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/Checker.h"
21 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24 #include "llvm/ADT/StringSet.h"
25 
26 using namespace clang;
27 using namespace ento;
28 
29 namespace {
30 struct RegionState {
31 private:
32   enum Kind { Moved, Reported } K;
33   RegionState(Kind InK) : K(InK) {}
34 
35 public:
36   bool isReported() const { return K == Reported; }
37   bool isMoved() const { return K == Moved; }
38 
39   static RegionState getReported() { return RegionState(Reported); }
40   static RegionState getMoved() { return RegionState(Moved); }
41 
42   bool operator==(const RegionState &X) const { return K == X.K; }
43   void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
44 };
45 } // end of anonymous namespace
46 
47 namespace {
48 class MoveChecker
49     : public Checker<check::PreCall, check::PostCall,
50                      check::DeadSymbols, check::RegionChanges> {
51 public:
52   void checkPreCall(const CallEvent &MC, CheckerContext &C) const;
53   void checkPostCall(const CallEvent &MC, CheckerContext &C) const;
54   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
55   ProgramStateRef
56   checkRegionChanges(ProgramStateRef State,
57                      const InvalidatedSymbols *Invalidated,
58                      ArrayRef<const MemRegion *> RequestedRegions,
59                      ArrayRef<const MemRegion *> InvalidatedRegions,
60                      const LocationContext *LCtx, const CallEvent *Call) const;
61   void printState(raw_ostream &Out, ProgramStateRef State,
62                   const char *NL, const char *Sep) const override;
63 
64 private:
65   enum MisuseKind { MK_FunCall, MK_Copy, MK_Move, MK_Dereference };
66   enum StdObjectKind { SK_NonStd, SK_Unsafe, SK_Safe, SK_SmartPtr };
67 
68   enum AggressivenessKind { // In any case, don't warn after a reset.
69     AK_Invalid = -1,
70     AK_KnownsOnly = 0,      // Warn only about known move-unsafe classes.
71     AK_KnownsAndLocals = 1, // Also warn about all local objects.
72     AK_All = 2,             // Warn on any use-after-move.
73     AK_NumKinds = AK_All
74   };
75 
76   static bool misuseCausesCrash(MisuseKind MK) {
77     return MK == MK_Dereference;
78   }
79 
80   struct ObjectKind {
81     // Is this a local variable or a local rvalue reference?
82     bool IsLocal;
83     // Is this an STL object? If so, of what kind?
84     StdObjectKind StdKind;
85   };
86 
87   // STL smart pointers are automatically re-initialized to null when moved
88   // from. So we can't warn on many methods, but we can warn when it is
89   // dereferenced, which is UB even if the resulting lvalue never gets read.
90   const llvm::StringSet<> StdSmartPtrClasses = {
91       "shared_ptr",
92       "unique_ptr",
93       "weak_ptr",
94   };
95 
96   // Not all of these are entirely move-safe, but they do provide *some*
97   // guarantees, and it means that somebody is using them after move
98   // in a valid manner.
99   // TODO: We can still try to identify *unsafe* use after move,
100   // like we did with smart pointers.
101   const llvm::StringSet<> StdSafeClasses = {
102       "basic_filebuf",
103       "basic_ios",
104       "future",
105       "optional",
106       "packaged_task",
107       "promise",
108       "shared_future",
109       "shared_lock",
110       "thread",
111       "unique_lock",
112   };
113 
114   // Should we bother tracking the state of the object?
115   bool shouldBeTracked(ObjectKind OK) const {
116     // In non-aggressive mode, only warn on use-after-move of local variables
117     // (or local rvalue references) and of STL objects. The former is possible
118     // because local variables (or local rvalue references) are not tempting
119     // their user to re-use the storage. The latter is possible because STL
120     // objects are known to end up in a valid but unspecified state after the
121     // move and their state-reset methods are also known, which allows us to
122     // predict precisely when use-after-move is invalid.
123     // Some STL objects are known to conform to additional contracts after move,
124     // so they are not tracked. However, smart pointers specifically are tracked
125     // because we can perform extra checking over them.
126     // In aggressive mode, warn on any use-after-move because the user has
127     // intentionally asked us to completely eliminate use-after-move
128     // in his code.
129     return (Aggressiveness == AK_All) ||
130            (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
131            OK.StdKind == SK_Unsafe || OK.StdKind == SK_SmartPtr;
132   }
133 
134   // Some objects only suffer from some kinds of misuses, but we need to track
135   // them anyway because we cannot know in advance what misuse will we find.
136   bool shouldWarnAbout(ObjectKind OK, MisuseKind MK) const {
137     // Additionally, only warn on smart pointers when they are dereferenced (or
138     // local or we are aggressive).
139     return shouldBeTracked(OK) &&
140            ((Aggressiveness == AK_All) ||
141             (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
142             OK.StdKind != SK_SmartPtr || MK == MK_Dereference);
143   }
144 
145   // Obtains ObjectKind of an object. Because class declaration cannot always
146   // be easily obtained from the memory region, it is supplied separately.
147   ObjectKind classifyObject(const MemRegion *MR, const CXXRecordDecl *RD) const;
148 
149   // Classifies the object and dumps a user-friendly description string to
150   // the stream.
151   void explainObject(llvm::raw_ostream &OS, const MemRegion *MR,
152                      const CXXRecordDecl *RD, MisuseKind MK) const;
153 
154   bool belongsTo(const CXXRecordDecl *RD, const llvm::StringSet<> &Set) const;
155 
156   class MovedBugVisitor : public BugReporterVisitor {
157   public:
158     MovedBugVisitor(const MoveChecker &Chk, const MemRegion *R,
159                     const CXXRecordDecl *RD, MisuseKind MK)
160         : Chk(Chk), Region(R), RD(RD), MK(MK), Found(false) {}
161 
162     void Profile(llvm::FoldingSetNodeID &ID) const override {
163       static int X = 0;
164       ID.AddPointer(&X);
165       ID.AddPointer(Region);
166       // Don't add RD because it's, in theory, uniquely determined by
167       // the region. In practice though, it's not always possible to obtain
168       // the declaration directly from the region, that's why we store it
169       // in the first place.
170     }
171 
172     PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
173                                      BugReporterContext &BRC,
174                                      PathSensitiveBugReport &BR) override;
175 
176   private:
177     const MoveChecker &Chk;
178     // The tracked region.
179     const MemRegion *Region;
180     // The class of the tracked object.
181     const CXXRecordDecl *RD;
182     // How exactly the object was misused.
183     const MisuseKind MK;
184     bool Found;
185   };
186 
187   AggressivenessKind Aggressiveness;
188 
189 public:
190   void setAggressiveness(StringRef Str, CheckerManager &Mgr) {
191     Aggressiveness =
192         llvm::StringSwitch<AggressivenessKind>(Str)
193             .Case("KnownsOnly", AK_KnownsOnly)
194             .Case("KnownsAndLocals", AK_KnownsAndLocals)
195             .Case("All", AK_All)
196             .Default(AK_Invalid);
197 
198     if (Aggressiveness == AK_Invalid)
199       Mgr.reportInvalidCheckerOptionValue(this, "WarnOn",
200           "either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value");
201   };
202 
203 private:
204   BugType BT{this, "Use-after-move", categories::CXXMoveSemantics};
205 
206   // Check if the given form of potential misuse of a given object
207   // should be reported. If so, get it reported. The callback from which
208   // this function was called should immediately return after the call
209   // because this function adds one or two transitions.
210   void modelUse(ProgramStateRef State, const MemRegion *Region,
211                 const CXXRecordDecl *RD, MisuseKind MK,
212                 CheckerContext &C) const;
213 
214   // Returns the exploded node against which the report was emitted.
215   // The caller *must* add any further transitions against this node.
216   ExplodedNode *reportBug(const MemRegion *Region, const CXXRecordDecl *RD,
217                           CheckerContext &C, MisuseKind MK) const;
218 
219   bool isInMoveSafeContext(const LocationContext *LC) const;
220   bool isStateResetMethod(const CXXMethodDecl *MethodDec) const;
221   bool isMoveSafeMethod(const CXXMethodDecl *MethodDec) const;
222   const ExplodedNode *getMoveLocation(const ExplodedNode *N,
223                                       const MemRegion *Region,
224                                       CheckerContext &C) const;
225 };
226 } // end anonymous namespace
227 
228 REGISTER_MAP_WITH_PROGRAMSTATE(TrackedRegionMap, const MemRegion *, RegionState)
229 
230 // Define the inter-checker API.
231 namespace clang {
232 namespace ento {
233 namespace move {
234 bool isMovedFrom(ProgramStateRef State, const MemRegion *Region) {
235   const RegionState *RS = State->get<TrackedRegionMap>(Region);
236   return RS && (RS->isMoved() || RS->isReported());
237 }
238 } // namespace move
239 } // namespace ento
240 } // namespace clang
241 
242 // If a region is removed all of the subregions needs to be removed too.
243 static ProgramStateRef removeFromState(ProgramStateRef State,
244                                        const MemRegion *Region) {
245   if (!Region)
246     return State;
247   for (auto &E : State->get<TrackedRegionMap>()) {
248     if (E.first->isSubRegionOf(Region))
249       State = State->remove<TrackedRegionMap>(E.first);
250   }
251   return State;
252 }
253 
254 static bool isAnyBaseRegionReported(ProgramStateRef State,
255                                     const MemRegion *Region) {
256   for (auto &E : State->get<TrackedRegionMap>()) {
257     if (Region->isSubRegionOf(E.first) && E.second.isReported())
258       return true;
259   }
260   return false;
261 }
262 
263 static const MemRegion *unwrapRValueReferenceIndirection(const MemRegion *MR) {
264   if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) {
265     SymbolRef Sym = SR->getSymbol();
266     if (Sym->getType()->isRValueReferenceType())
267       if (const MemRegion *OriginMR = Sym->getOriginRegion())
268         return OriginMR;
269   }
270   return MR;
271 }
272 
273 PathDiagnosticPieceRef
274 MoveChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
275                                         BugReporterContext &BRC,
276                                         PathSensitiveBugReport &BR) {
277   // We need only the last move of the reported object's region.
278   // The visitor walks the ExplodedGraph backwards.
279   if (Found)
280     return nullptr;
281   ProgramStateRef State = N->getState();
282   ProgramStateRef StatePrev = N->getFirstPred()->getState();
283   const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
284   const RegionState *TrackedObjectPrev =
285       StatePrev->get<TrackedRegionMap>(Region);
286   if (!TrackedObject)
287     return nullptr;
288   if (TrackedObjectPrev && TrackedObject)
289     return nullptr;
290 
291   // Retrieve the associated statement.
292   const Stmt *S = N->getStmtForDiagnostics();
293   if (!S)
294     return nullptr;
295   Found = true;
296 
297   SmallString<128> Str;
298   llvm::raw_svector_ostream OS(Str);
299 
300   ObjectKind OK = Chk.classifyObject(Region, RD);
301   switch (OK.StdKind) {
302     case SK_SmartPtr:
303       if (MK == MK_Dereference) {
304         OS << "Smart pointer";
305         Chk.explainObject(OS, Region, RD, MK);
306         OS << " is reset to null when moved from";
307         break;
308       }
309 
310       // If it's not a dereference, we don't care if it was reset to null
311       // or that it is even a smart pointer.
312       [[fallthrough]];
313     case SK_NonStd:
314     case SK_Safe:
315       OS << "Object";
316       Chk.explainObject(OS, Region, RD, MK);
317       OS << " is moved";
318       break;
319     case SK_Unsafe:
320       OS << "Object";
321       Chk.explainObject(OS, Region, RD, MK);
322       OS << " is left in a valid but unspecified state after move";
323       break;
324   }
325 
326   // Generate the extra diagnostic.
327   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
328                              N->getLocationContext());
329   return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true);
330 }
331 
332 const ExplodedNode *MoveChecker::getMoveLocation(const ExplodedNode *N,
333                                                  const MemRegion *Region,
334                                                  CheckerContext &C) const {
335   // Walk the ExplodedGraph backwards and find the first node that referred to
336   // the tracked region.
337   const ExplodedNode *MoveNode = N;
338 
339   while (N) {
340     ProgramStateRef State = N->getState();
341     if (!State->get<TrackedRegionMap>(Region))
342       break;
343     MoveNode = N;
344     N = N->pred_empty() ? nullptr : *(N->pred_begin());
345   }
346   return MoveNode;
347 }
348 
349 void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region,
350                            const CXXRecordDecl *RD, MisuseKind MK,
351                            CheckerContext &C) const {
352   assert(!C.isDifferent() && "No transitions should have been made by now");
353   const RegionState *RS = State->get<TrackedRegionMap>(Region);
354   ObjectKind OK = classifyObject(Region, RD);
355 
356   // Just in case: if it's not a smart pointer but it does have operator *,
357   // we shouldn't call the bug a dereference.
358   if (MK == MK_Dereference && OK.StdKind != SK_SmartPtr)
359     MK = MK_FunCall;
360 
361   if (!RS || !shouldWarnAbout(OK, MK)
362           || isInMoveSafeContext(C.getLocationContext())) {
363     // Finalize changes made by the caller.
364     C.addTransition(State);
365     return;
366   }
367 
368   // Don't report it in case if any base region is already reported.
369   // But still generate a sink in case of UB.
370   // And still finalize changes made by the caller.
371   if (isAnyBaseRegionReported(State, Region)) {
372     if (misuseCausesCrash(MK)) {
373       C.generateSink(State, C.getPredecessor());
374     } else {
375       C.addTransition(State);
376     }
377     return;
378   }
379 
380   ExplodedNode *N = reportBug(Region, RD, C, MK);
381 
382   // If the program has already crashed on this path, don't bother.
383   if (N->isSink())
384     return;
385 
386   State = State->set<TrackedRegionMap>(Region, RegionState::getReported());
387   C.addTransition(State, N);
388 }
389 
390 ExplodedNode *MoveChecker::reportBug(const MemRegion *Region,
391                                      const CXXRecordDecl *RD, CheckerContext &C,
392                                      MisuseKind MK) const {
393   if (ExplodedNode *N = misuseCausesCrash(MK) ? C.generateErrorNode()
394                                               : C.generateNonFatalErrorNode()) {
395     // Uniqueing report to the same object.
396     PathDiagnosticLocation LocUsedForUniqueing;
397     const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
398 
399     if (const Stmt *MoveStmt = MoveNode->getStmtForDiagnostics())
400       LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
401           MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
402 
403     // Creating the error message.
404     llvm::SmallString<128> Str;
405     llvm::raw_svector_ostream OS(Str);
406     switch(MK) {
407       case MK_FunCall:
408         OS << "Method called on moved-from object";
409         explainObject(OS, Region, RD, MK);
410         break;
411       case MK_Copy:
412         OS << "Moved-from object";
413         explainObject(OS, Region, RD, MK);
414         OS << " is copied";
415         break;
416       case MK_Move:
417         OS << "Moved-from object";
418         explainObject(OS, Region, RD, MK);
419         OS << " is moved";
420         break;
421       case MK_Dereference:
422         OS << "Dereference of null smart pointer";
423         explainObject(OS, Region, RD, MK);
424         break;
425     }
426 
427     auto R = std::make_unique<PathSensitiveBugReport>(
428         BT, OS.str(), N, LocUsedForUniqueing,
429         MoveNode->getLocationContext()->getDecl());
430     R->addVisitor(std::make_unique<MovedBugVisitor>(*this, Region, RD, MK));
431     C.emitReport(std::move(R));
432     return N;
433   }
434   return nullptr;
435 }
436 
437 void MoveChecker::checkPostCall(const CallEvent &Call,
438                                 CheckerContext &C) const {
439   const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
440   if (!AFC)
441     return;
442 
443   ProgramStateRef State = C.getState();
444   const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
445   if (!MethodDecl)
446     return;
447 
448   // Check if an object became moved-from.
449   // Object can become moved from after a call to move assignment operator or
450   // move constructor .
451   const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
452   if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
453     return;
454 
455   if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
456     return;
457 
458   const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
459   if (!ArgRegion)
460     return;
461 
462   // Skip moving the object to itself.
463   const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
464   if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
465     return;
466 
467   if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
468     if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
469       return;
470 
471   const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
472   // Skip temp objects because of their short lifetime.
473   if (BaseRegion->getAs<CXXTempObjectRegion>() ||
474       AFC->getArgExpr(0)->isPRValue())
475     return;
476   // If it has already been reported do not need to modify the state.
477 
478   if (State->get<TrackedRegionMap>(ArgRegion))
479     return;
480 
481   const CXXRecordDecl *RD = MethodDecl->getParent();
482   ObjectKind OK = classifyObject(ArgRegion, RD);
483   if (shouldBeTracked(OK)) {
484     // Mark object as moved-from.
485     State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
486     C.addTransition(State);
487     return;
488   }
489   assert(!C.isDifferent() && "Should not have made transitions on this path!");
490 }
491 
492 bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const {
493   // We abandon the cases where bool/void/void* conversion happens.
494   if (const auto *ConversionDec =
495           dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
496     const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
497     if (!Tp)
498       return false;
499     if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType())
500       return true;
501   }
502   // Function call `empty` can be skipped.
503   return (MethodDec && MethodDec->getDeclName().isIdentifier() &&
504       (MethodDec->getName().lower() == "empty" ||
505        MethodDec->getName().lower() == "isempty"));
506 }
507 
508 bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const {
509   if (!MethodDec)
510       return false;
511   if (MethodDec->hasAttr<ReinitializesAttr>())
512       return true;
513   if (MethodDec->getDeclName().isIdentifier()) {
514     std::string MethodName = MethodDec->getName().lower();
515     // TODO: Some of these methods (eg., resize) are not always resetting
516     // the state, so we should consider looking at the arguments.
517     if (MethodName == "assign" || MethodName == "clear" ||
518         MethodName == "destroy" || MethodName == "reset" ||
519         MethodName == "resize" || MethodName == "shrink")
520       return true;
521   }
522   return false;
523 }
524 
525 // Don't report an error inside a move related operation.
526 // We assume that the programmer knows what she does.
527 bool MoveChecker::isInMoveSafeContext(const LocationContext *LC) const {
528   do {
529     const auto *CtxDec = LC->getDecl();
530     auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
531     auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
532     auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
533     if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
534         (MethodDec && MethodDec->isOverloadedOperator() &&
535          MethodDec->getOverloadedOperator() == OO_Equal) ||
536         isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec))
537       return true;
538   } while ((LC = LC->getParent()));
539   return false;
540 }
541 
542 bool MoveChecker::belongsTo(const CXXRecordDecl *RD,
543                             const llvm::StringSet<> &Set) const {
544   const IdentifierInfo *II = RD->getIdentifier();
545   return II && Set.count(II->getName());
546 }
547 
548 MoveChecker::ObjectKind
549 MoveChecker::classifyObject(const MemRegion *MR,
550                             const CXXRecordDecl *RD) const {
551   // Local variables and local rvalue references are classified as "Local".
552   // For the purposes of this checker, we classify move-safe STL types
553   // as not-"STL" types, because that's how the checker treats them.
554   MR = unwrapRValueReferenceIndirection(MR);
555   bool IsLocal = isa_and_nonnull<VarRegion>(MR) &&
556                  isa<StackSpaceRegion>(MR->getMemorySpace());
557 
558   if (!RD || !RD->getDeclContext()->isStdNamespace())
559     return { IsLocal, SK_NonStd };
560 
561   if (belongsTo(RD, StdSmartPtrClasses))
562     return { IsLocal, SK_SmartPtr };
563 
564   if (belongsTo(RD, StdSafeClasses))
565     return { IsLocal, SK_Safe };
566 
567   return { IsLocal, SK_Unsafe };
568 }
569 
570 void MoveChecker::explainObject(llvm::raw_ostream &OS, const MemRegion *MR,
571                                 const CXXRecordDecl *RD, MisuseKind MK) const {
572   // We may need a leading space every time we actually explain anything,
573   // and we never know if we are to explain anything until we try.
574   if (const auto DR =
575           dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) {
576     const auto *RegionDecl = cast<NamedDecl>(DR->getDecl());
577     OS << " '" << RegionDecl->getDeclName() << "'";
578   }
579 
580   ObjectKind OK = classifyObject(MR, RD);
581   switch (OK.StdKind) {
582     case SK_NonStd:
583     case SK_Safe:
584       break;
585     case SK_SmartPtr:
586       if (MK != MK_Dereference)
587         break;
588 
589       // We only care about the type if it's a dereference.
590       [[fallthrough]];
591     case SK_Unsafe:
592       OS << " of type '" << RD->getQualifiedNameAsString() << "'";
593       break;
594   };
595 }
596 
597 void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const {
598   ProgramStateRef State = C.getState();
599 
600   // Remove the MemRegions from the map on which a ctor/dtor call or assignment
601   // happened.
602 
603   // Checking constructor calls.
604   if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
605     State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
606     auto CtorDec = CC->getDecl();
607     // Check for copying a moved-from object and report the bug.
608     if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
609       const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
610       const CXXRecordDecl *RD = CtorDec->getParent();
611       MisuseKind MK = CtorDec->isMoveConstructor() ? MK_Move : MK_Copy;
612       modelUse(State, ArgRegion, RD, MK, C);
613       return;
614     }
615   }
616 
617   const auto IC = dyn_cast<CXXInstanceCall>(&Call);
618   if (!IC)
619     return;
620 
621   const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
622   if (!ThisRegion)
623     return;
624 
625   // The remaining part is check only for method call on a moved-from object.
626   const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
627   if (!MethodDecl)
628     return;
629 
630   // Calling a destructor on a moved object is fine.
631   if (isa<CXXDestructorDecl>(MethodDecl))
632     return;
633 
634   // We want to investigate the whole object, not only sub-object of a parent
635   // class in which the encountered method defined.
636   ThisRegion = ThisRegion->getMostDerivedObjectRegion();
637 
638   if (isStateResetMethod(MethodDecl)) {
639     State = removeFromState(State, ThisRegion);
640     C.addTransition(State);
641     return;
642   }
643 
644   if (isMoveSafeMethod(MethodDecl))
645     return;
646 
647   // Store class declaration as well, for bug reporting purposes.
648   const CXXRecordDecl *RD = MethodDecl->getParent();
649 
650   if (MethodDecl->isOverloadedOperator()) {
651     OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator();
652 
653     if (OOK == OO_Equal) {
654       // Remove the tracked object for every assignment operator, but report bug
655       // only for move or copy assignment's argument.
656       State = removeFromState(State, ThisRegion);
657 
658       if (MethodDecl->isCopyAssignmentOperator() ||
659           MethodDecl->isMoveAssignmentOperator()) {
660         const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
661         MisuseKind MK =
662             MethodDecl->isMoveAssignmentOperator() ? MK_Move : MK_Copy;
663         modelUse(State, ArgRegion, RD, MK, C);
664         return;
665       }
666       C.addTransition(State);
667       return;
668     }
669 
670     if (OOK == OO_Star || OOK == OO_Arrow) {
671       modelUse(State, ThisRegion, RD, MK_Dereference, C);
672       return;
673     }
674   }
675 
676   modelUse(State, ThisRegion, RD, MK_FunCall, C);
677 }
678 
679 void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper,
680                                    CheckerContext &C) const {
681   ProgramStateRef State = C.getState();
682   TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
683   for (auto E : TrackedRegions) {
684     const MemRegion *Region = E.first;
685     bool IsRegDead = !SymReaper.isLiveRegion(Region);
686 
687     // Remove the dead regions from the region map.
688     if (IsRegDead) {
689       State = State->remove<TrackedRegionMap>(Region);
690     }
691   }
692   C.addTransition(State);
693 }
694 
695 ProgramStateRef MoveChecker::checkRegionChanges(
696     ProgramStateRef State, const InvalidatedSymbols *Invalidated,
697     ArrayRef<const MemRegion *> RequestedRegions,
698     ArrayRef<const MemRegion *> InvalidatedRegions,
699     const LocationContext *LCtx, const CallEvent *Call) const {
700   if (Call) {
701     // Relax invalidation upon function calls: only invalidate parameters
702     // that are passed directly via non-const pointers or non-const references
703     // or rvalue references.
704     // In case of an InstanceCall don't invalidate the this-region since
705     // it is fully handled in checkPreCall and checkPostCall.
706     const MemRegion *ThisRegion = nullptr;
707     if (const auto *IC = dyn_cast<CXXInstanceCall>(Call))
708       ThisRegion = IC->getCXXThisVal().getAsRegion();
709 
710     // Requested ("explicit") regions are the regions passed into the call
711     // directly, but not all of them end up being invalidated.
712     // But when they do, they appear in the InvalidatedRegions array as well.
713     for (const auto *Region : RequestedRegions) {
714       if (ThisRegion != Region &&
715           llvm::is_contained(InvalidatedRegions, Region))
716         State = removeFromState(State, Region);
717     }
718   } else {
719     // For invalidations that aren't caused by calls, assume nothing. In
720     // particular, direct write into an object's field invalidates the status.
721     for (const auto *Region : InvalidatedRegions)
722       State = removeFromState(State, Region->getBaseRegion());
723   }
724 
725   return State;
726 }
727 
728 void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State,
729                              const char *NL, const char *Sep) const {
730 
731   TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
732 
733   if (!RS.isEmpty()) {
734     Out << Sep << "Moved-from objects :" << NL;
735     for (auto I: RS) {
736       I.first->dumpToStream(Out);
737       if (I.second.isMoved())
738         Out << ": moved";
739       else
740         Out << ": moved and reported";
741       Out << NL;
742     }
743   }
744 }
745 void ento::registerMoveChecker(CheckerManager &mgr) {
746   MoveChecker *chk = mgr.registerChecker<MoveChecker>();
747   chk->setAggressiveness(
748       mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr);
749 }
750 
751 bool ento::shouldRegisterMoveChecker(const CheckerManager &mgr) {
752   return true;
753 }
754