1 //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
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 //  This file defines a set of BugReporter "visitors" which can be used to
11 //  enhance the diagnostics reported for a bug.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/Stmt.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Analysis/AnalysisDeclContext.h"
26 #include "clang/Analysis/CFG.h"
27 #include "clang/Analysis/CFGStmtMap.h"
28 #include "clang/Analysis/ProgramPoint.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/SourceLocation.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Lex/Lexer.h"
34 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
35 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
36 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
37 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
38 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
39 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
40 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/None.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/SmallPtrSet.h"
53 #include "llvm/ADT/SmallString.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cassert>
61 #include <deque>
62 #include <memory>
63 #include <string>
64 #include <utility>
65 
66 using namespace clang;
67 using namespace ento;
68 
69 //===----------------------------------------------------------------------===//
70 // Utility functions.
71 //===----------------------------------------------------------------------===//
72 
73 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
74   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
75     return DRE->getDecl()->getType()->isReferenceType();
76   return false;
77 }
78 
79 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
80   if (B->isAdditiveOp() && B->getType()->isPointerType()) {
81     if (B->getLHS()->getType()->isPointerType()) {
82       return B->getLHS();
83     } else if (B->getRHS()->getType()->isPointerType()) {
84       return B->getRHS();
85     }
86   }
87   return nullptr;
88 }
89 
90 /// Given that expression S represents a pointer that would be dereferenced,
91 /// try to find a sub-expression from which the pointer came from.
92 /// This is used for tracking down origins of a null or undefined value:
93 /// "this is null because that is null because that is null" etc.
94 /// We wipe away field and element offsets because they merely add offsets.
95 /// We also wipe away all casts except lvalue-to-rvalue casts, because the
96 /// latter represent an actual pointer dereference; however, we remove
97 /// the final lvalue-to-rvalue cast before returning from this function
98 /// because it demonstrates more clearly from where the pointer rvalue was
99 /// loaded. Examples:
100 ///   x->y.z      ==>  x (lvalue)
101 ///   foo()->y.z  ==>  foo() (rvalue)
102 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
103   const auto *E = dyn_cast<Expr>(S);
104   if (!E)
105     return nullptr;
106 
107   while (true) {
108     if (const auto *CE = dyn_cast<CastExpr>(E)) {
109       if (CE->getCastKind() == CK_LValueToRValue) {
110         // This cast represents the load we're looking for.
111         break;
112       }
113       E = CE->getSubExpr();
114     } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
115       // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
116       if (const Expr *Inner = peelOffPointerArithmetic(B)) {
117         E = Inner;
118       } else {
119         // Probably more arithmetic can be pattern-matched here,
120         // but for now give up.
121         break;
122       }
123     } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
124       if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
125           (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
126         // Operators '*' and '&' don't actually mean anything.
127         // We look at casts instead.
128         E = U->getSubExpr();
129       } else {
130         // Probably more arithmetic can be pattern-matched here,
131         // but for now give up.
132         break;
133       }
134     }
135     // Pattern match for a few useful cases: a[0], p->f, *p etc.
136     else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
137       E = ME->getBase();
138     } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
139       E = IvarRef->getBase();
140     } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
141       E = AE->getBase();
142     } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
143       E = PE->getSubExpr();
144     } else {
145       // Other arbitrary stuff.
146       break;
147     }
148   }
149 
150   // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
151   // deeper into the sub-expression. This way we return the lvalue from which
152   // our pointer rvalue was loaded.
153   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
154     if (CE->getCastKind() == CK_LValueToRValue)
155       E = CE->getSubExpr();
156 
157   return E;
158 }
159 
160 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
161   const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
162   if (const auto *BE = dyn_cast<BinaryOperator>(S))
163     return BE->getRHS();
164   return nullptr;
165 }
166 
167 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
168   const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
169   if (const auto *RS = dyn_cast<ReturnStmt>(S))
170     return RS->getRetValue();
171   return nullptr;
172 }
173 
174 //===----------------------------------------------------------------------===//
175 // Definitions for bug reporter visitors.
176 //===----------------------------------------------------------------------===//
177 
178 std::unique_ptr<PathDiagnosticPiece>
179 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
180                                const ExplodedNode *EndPathNode, BugReport &BR) {
181   return nullptr;
182 }
183 
184 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
185     BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
186   PathDiagnosticLocation L =
187     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
188 
189   const auto &Ranges = BR.getRanges();
190 
191   // Only add the statement itself as a range if we didn't specify any
192   // special ranges for this report.
193   auto P = llvm::make_unique<PathDiagnosticEventPiece>(
194       L, BR.getDescription(), Ranges.begin() == Ranges.end());
195   for (SourceRange Range : Ranges)
196     P->addRange(Range);
197 
198   return std::move(P);
199 }
200 
201 /// \return name of the macro inside the location \p Loc.
202 static StringRef getMacroName(SourceLocation Loc,
203     BugReporterContext &BRC) {
204   return Lexer::getImmediateMacroName(
205       Loc,
206       BRC.getSourceManager(),
207       BRC.getASTContext().getLangOpts());
208 }
209 
210 /// \return Whether given spelling location corresponds to an expansion
211 /// of a function-like macro.
212 static bool isFunctionMacroExpansion(SourceLocation Loc,
213                                 const SourceManager &SM) {
214   if (!Loc.isMacroID())
215     return false;
216   while (SM.isMacroArgExpansion(Loc))
217     Loc = SM.getImmediateExpansionRange(Loc).getBegin();
218   std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
219   SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
220   const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
221   return EInfo.isFunctionMacroExpansion();
222 }
223 
224 namespace {
225 
226 /// Put a diagnostic on return statement of all inlined functions
227 /// for which  the region of interest \p RegionOfInterest was passed into,
228 /// but not written inside, and it has caused an undefined read or a null
229 /// pointer dereference outside.
230 class NoStoreFuncVisitor final
231     : public BugReporterVisitorImpl<NoStoreFuncVisitor> {
232   const SubRegion *RegionOfInterest;
233   static constexpr const char *DiagnosticsMsg =
234       "Returning without writing to '";
235 
236   /// Frames writing into \c RegionOfInterest.
237   /// This visitor generates a note only if a function does not write into
238   /// a region of interest. This information is not immediately available
239   /// by looking at the node associated with the exit from the function
240   /// (usually the return statement). To avoid recomputing the same information
241   /// many times (going up the path for each node and checking whether the
242   /// region was written into) we instead lazily compute the
243   /// stack frames along the path which write into the region of interest.
244   llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
245   llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
246 
247 public:
248   NoStoreFuncVisitor(const SubRegion *R) : RegionOfInterest(R) {}
249 
250   void Profile(llvm::FoldingSetNodeID &ID) const override {
251     static int Tag = 0;
252     ID.AddPointer(&Tag);
253   }
254 
255   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
256                                                  const ExplodedNode *PrevN,
257                                                  BugReporterContext &BRC,
258                                                  BugReport &BR) override {
259 
260     const LocationContext *Ctx = N->getLocationContext();
261     const StackFrameContext *SCtx = Ctx->getCurrentStackFrame();
262     ProgramStateRef State = N->getState();
263     auto CallExitLoc = N->getLocationAs<CallExitBegin>();
264 
265     // No diagnostic if region was modified inside the frame.
266     if (!CallExitLoc)
267       return nullptr;
268 
269     CallEventRef<> Call =
270         BRC.getStateManager().getCallEventManager().getCaller(SCtx, State);
271 
272     const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy();
273     const SourceManager &SM = BRC.getSourceManager();
274     if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
275       const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion();
276       if (RegionOfInterest->isSubRegionOf(ThisRegion)
277           && !CCall->getDecl()->isImplicit()
278           && !isRegionOfInterestModifiedInFrame(N))
279         return notModifiedInConstructorDiagnostics(Ctx, SM, PP, *CallExitLoc,
280                                                    CCall, ThisRegion);
281     }
282 
283     ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
284     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
285       const ParmVarDecl *PVD = parameters[I];
286       SVal S = Call->getArgSVal(I);
287       unsigned IndirectionLevel = 1;
288       QualType T = PVD->getType();
289       while (const MemRegion *R = S.getAsRegion()) {
290         if (RegionOfInterest->isSubRegionOf(R)
291             && !isPointerToConst(PVD->getType())) {
292 
293           if (isRegionOfInterestModifiedInFrame(N))
294             return nullptr;
295 
296           return notModifiedDiagnostics(
297               Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel);
298         }
299         QualType PT = T->getPointeeType();
300         if (PT.isNull() || PT->isVoidType()) break;
301         S = State->getSVal(R, PT);
302         T = PT;
303         IndirectionLevel++;
304       }
305     }
306 
307     return nullptr;
308   }
309 
310 private:
311   /// Check and lazily calculate whether the region of interest is
312   /// modified in the stack frame to which \p N belongs.
313   /// The calculation is cached in FramesModifyingRegion.
314   bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
315     const LocationContext *Ctx = N->getLocationContext();
316     const StackFrameContext *SCtx = Ctx->getCurrentStackFrame();
317     if (!FramesModifyingCalculated.count(SCtx))
318       findModifyingFrames(N);
319     return FramesModifyingRegion.count(SCtx);
320   }
321 
322 
323   /// Write to \c FramesModifyingRegion all stack frames along
324   /// the path in the current stack frame which modify \c RegionOfInterest.
325   void findModifyingFrames(const ExplodedNode *N) {
326     assert(N->getLocationAs<CallExitBegin>());
327     ProgramStateRef LastReturnState = N->getState();
328     SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
329     const LocationContext *Ctx = N->getLocationContext();
330     const StackFrameContext *OriginalSCtx = Ctx->getCurrentStackFrame();
331 
332     do {
333       ProgramStateRef State = N->getState();
334       auto CallExitLoc = N->getLocationAs<CallExitBegin>();
335       if (CallExitLoc) {
336         LastReturnState = State;
337         ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
338       }
339 
340       FramesModifyingCalculated.insert(
341         N->getLocationContext()->getCurrentStackFrame());
342 
343       if (wasRegionOfInterestModifiedAt(N, LastReturnState, ValueAtReturn)) {
344         const StackFrameContext *SCtx =
345             N->getLocationContext()->getCurrentStackFrame();
346         while (!SCtx->inTopFrame()) {
347           auto p = FramesModifyingRegion.insert(SCtx);
348           if (!p.second)
349             break; // Frame and all its parents already inserted.
350           SCtx = SCtx->getParent()->getCurrentStackFrame();
351         }
352       }
353 
354       // Stop calculation at the call to the current function.
355       if (auto CE = N->getLocationAs<CallEnter>())
356         if (CE->getCalleeContext() == OriginalSCtx)
357           break;
358 
359       N = N->getFirstPred();
360     } while (N);
361   }
362 
363   /// \return Whether \c RegionOfInterest was modified at \p N,
364   /// where \p ReturnState is a state associated with the return
365   /// from the current frame.
366   bool wasRegionOfInterestModifiedAt(const ExplodedNode *N,
367                                      ProgramStateRef ReturnState,
368                                      SVal ValueAtReturn) {
369     if (!N->getLocationAs<PostStore>()
370         && !N->getLocationAs<PostInitializer>()
371         && !N->getLocationAs<PostStmt>())
372       return false;
373 
374     // Writing into region of interest.
375     if (auto PS = N->getLocationAs<PostStmt>())
376       if (auto *BO = PS->getStmtAs<BinaryOperator>())
377         if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
378                                         N->getSVal(BO->getLHS()).getAsRegion()))
379           return true;
380 
381     // SVal after the state is possibly different.
382     SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
383     if (!ReturnState->areEqual(ValueAtN, ValueAtReturn).isConstrainedTrue() &&
384         (!ValueAtN.isUndef() || !ValueAtReturn.isUndef()))
385       return true;
386 
387     return false;
388   }
389 
390   /// Get parameters associated with runtime definition in order
391   /// to get the correct parameter name.
392   ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
393     // Use runtime definition, if available.
394     RuntimeDefinition RD = Call->getRuntimeDefinition();
395     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
396       return FD->parameters();
397 
398     return Call->parameters();
399   }
400 
401   /// \return whether \p Ty points to a const type, or is a const reference.
402   bool isPointerToConst(QualType Ty) {
403     return !Ty->getPointeeType().isNull() &&
404            Ty->getPointeeType().getCanonicalType().isConstQualified();
405   }
406 
407   std::shared_ptr<PathDiagnosticPiece> notModifiedInConstructorDiagnostics(
408       const LocationContext *Ctx,
409       const SourceManager &SM,
410       const PrintingPolicy &PP,
411       CallExitBegin &CallExitLoc,
412       const CXXConstructorCall *Call,
413       const MemRegion *ArgRegion) {
414     SmallString<256> sbuf;
415     llvm::raw_svector_ostream os(sbuf);
416     os << DiagnosticsMsg;
417     bool out = prettyPrintRegionName(
418         "this", "->", /*IsReference=*/true,
419         /*IndirectionLevel=*/1, ArgRegion, os, PP);
420 
421     // Return nothing if we have failed to pretty-print.
422     if (!out)
423       return nullptr;
424 
425     os << "'";
426     PathDiagnosticLocation L =
427         getPathDiagnosticLocation(nullptr, SM, Ctx, Call);
428     return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
429   }
430 
431   /// \p IndirectionLevel How many times \c ArgRegion has to be dereferenced
432   /// before we get to the super region of \c RegionOfInterest
433   std::shared_ptr<PathDiagnosticPiece>
434   notModifiedDiagnostics(const LocationContext *Ctx,
435                          const SourceManager &SM,
436                          const PrintingPolicy &PP,
437                          CallExitBegin &CallExitLoc,
438                          CallEventRef<> Call,
439                          const ParmVarDecl *PVD,
440                          const MemRegion *ArgRegion,
441                          unsigned IndirectionLevel) {
442     PathDiagnosticLocation L = getPathDiagnosticLocation(
443         CallExitLoc.getReturnStmt(), SM, Ctx, Call);
444     SmallString<256> sbuf;
445     llvm::raw_svector_ostream os(sbuf);
446     os << DiagnosticsMsg;
447     bool IsReference = PVD->getType()->isReferenceType();
448     const char *Sep = IsReference && IndirectionLevel == 1 ? "." : "->";
449     bool Success = prettyPrintRegionName(
450         PVD->getQualifiedNameAsString().c_str(),
451         Sep, IsReference, IndirectionLevel, ArgRegion, os, PP);
452 
453     // Print the parameter name if the pretty-printing has failed.
454     if (!Success)
455       PVD->printQualifiedName(os);
456     os << "'";
457     return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
458   }
459 
460   /// \return a path diagnostic location for the optionally
461   /// present return statement \p RS.
462   PathDiagnosticLocation getPathDiagnosticLocation(const ReturnStmt *RS,
463                                                    const SourceManager &SM,
464                                                    const LocationContext *Ctx,
465                                                    CallEventRef<> Call) {
466     if (RS)
467       return PathDiagnosticLocation::createBegin(RS, SM, Ctx);
468     return PathDiagnosticLocation(
469         Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(), SM);
470   }
471 
472   /// Pretty-print region \p ArgRegion starting from parent to \p os.
473   /// \return whether printing has succeeded
474   bool prettyPrintRegionName(const char *TopRegionName,
475                              const char *Sep,
476                              bool IsReference,
477                              int IndirectionLevel,
478                              const MemRegion *ArgRegion,
479                              llvm::raw_svector_ostream &os,
480                              const PrintingPolicy &PP) {
481     SmallVector<const MemRegion *, 5> Subregions;
482     const MemRegion *R = RegionOfInterest;
483     while (R != ArgRegion) {
484       if (!(isa<FieldRegion>(R) || isa<CXXBaseObjectRegion>(R)))
485         return false; // Pattern-matching failed.
486       Subregions.push_back(R);
487       R = cast<SubRegion>(R)->getSuperRegion();
488     }
489     bool IndirectReference = !Subregions.empty();
490 
491     if (IndirectReference)
492       IndirectionLevel--; // Due to "->" symbol.
493 
494     if (IsReference)
495       IndirectionLevel--; // Due to reference semantics.
496 
497     bool ShouldSurround = IndirectReference && IndirectionLevel > 0;
498 
499     if (ShouldSurround)
500       os << "(";
501     for (int i = 0; i < IndirectionLevel; i++)
502       os << "*";
503     os << TopRegionName;
504     if (ShouldSurround)
505       os << ")";
506 
507     for (auto I = Subregions.rbegin(), E = Subregions.rend(); I != E; ++I) {
508       if (const auto *FR = dyn_cast<FieldRegion>(*I)) {
509         os << Sep;
510         FR->getDecl()->getDeclName().print(os, PP);
511         Sep = ".";
512       } else if (isa<CXXBaseObjectRegion>(*I)) {
513         continue; // Just keep going up to the base region.
514       } else {
515         llvm_unreachable("Previous check has missed an unexpected region");
516       }
517     }
518     return true;
519   }
520 };
521 
522 class MacroNullReturnSuppressionVisitor final
523     : public BugReporterVisitorImpl<MacroNullReturnSuppressionVisitor> {
524   const SubRegion *RegionOfInterest;
525 
526 public:
527   MacroNullReturnSuppressionVisitor(const SubRegion *R) : RegionOfInterest(R) {}
528 
529   static void *getTag() {
530     static int Tag = 0;
531     return static_cast<void *>(&Tag);
532   }
533 
534   void Profile(llvm::FoldingSetNodeID &ID) const override {
535     ID.AddPointer(getTag());
536   }
537 
538   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
539                                                  const ExplodedNode *PrevN,
540                                                  BugReporterContext &BRC,
541                                                  BugReport &BR) override {
542     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
543     if (!BugPoint)
544       return nullptr;
545 
546     const SourceManager &SMgr = BRC.getSourceManager();
547     if (auto Loc = matchAssignment(N, BRC)) {
548       if (isFunctionMacroExpansion(*Loc, SMgr)) {
549         std::string MacroName = getMacroName(*Loc, BRC);
550         SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
551         if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
552           BR.markInvalid(getTag(), MacroName.c_str());
553       }
554     }
555     return nullptr;
556   }
557 
558   static void addMacroVisitorIfNecessary(
559         const ExplodedNode *N, const MemRegion *R,
560         bool EnableNullFPSuppression, BugReport &BR,
561         const SVal V) {
562     AnalyzerOptions &Options = N->getState()->getStateManager()
563         .getOwningEngine()->getAnalysisManager().options;
564     if (EnableNullFPSuppression && Options.shouldSuppressNullReturnPaths()
565           && V.getAs<Loc>())
566       BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
567               R->getAs<SubRegion>()));
568   }
569 
570 private:
571   /// \return Source location of right hand side of an assignment
572   /// into \c RegionOfInterest, empty optional if none found.
573   Optional<SourceLocation> matchAssignment(const ExplodedNode *N,
574                                            BugReporterContext &BRC) {
575     const Stmt *S = PathDiagnosticLocation::getStmt(N);
576     ProgramStateRef State = N->getState();
577     auto *LCtx = N->getLocationContext();
578     if (!S)
579       return None;
580 
581     if (const auto *DS = dyn_cast<DeclStmt>(S)) {
582       if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
583         if (const Expr *RHS = VD->getInit())
584           if (RegionOfInterest->isSubRegionOf(
585                   State->getLValue(VD, LCtx).getAsRegion()))
586             return RHS->getLocStart();
587     } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
588       const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
589       const Expr *RHS = BO->getRHS();
590       if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
591         return RHS->getLocStart();
592       }
593     }
594     return None;
595   }
596 };
597 
598 /// Emits an extra note at the return statement of an interesting stack frame.
599 ///
600 /// The returned value is marked as an interesting value, and if it's null,
601 /// adds a visitor to track where it became null.
602 ///
603 /// This visitor is intended to be used when another visitor discovers that an
604 /// interesting value comes from an inlined function call.
605 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
606   const StackFrameContext *StackFrame;
607   enum {
608     Initial,
609     MaybeUnsuppress,
610     Satisfied
611   } Mode = Initial;
612 
613   bool EnableNullFPSuppression;
614 
615 public:
616   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
617       : StackFrame(Frame), EnableNullFPSuppression(Suppressed) {}
618 
619   static void *getTag() {
620     static int Tag = 0;
621     return static_cast<void *>(&Tag);
622   }
623 
624   void Profile(llvm::FoldingSetNodeID &ID) const override {
625     ID.AddPointer(ReturnVisitor::getTag());
626     ID.AddPointer(StackFrame);
627     ID.AddBoolean(EnableNullFPSuppression);
628   }
629 
630   /// Adds a ReturnVisitor if the given statement represents a call that was
631   /// inlined.
632   ///
633   /// This will search back through the ExplodedGraph, starting from the given
634   /// node, looking for when the given statement was processed. If it turns out
635   /// the statement is a call that was inlined, we add the visitor to the
636   /// bug report, so it can print a note later.
637   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
638                                     BugReport &BR,
639                                     bool InEnableNullFPSuppression) {
640     if (!CallEvent::isCallStmt(S))
641       return;
642 
643     // First, find when we processed the statement.
644     do {
645       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
646         if (CEE->getCalleeContext()->getCallSite() == S)
647           break;
648       if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
649         if (SP->getStmt() == S)
650           break;
651 
652       Node = Node->getFirstPred();
653     } while (Node);
654 
655     // Next, step over any post-statement checks.
656     while (Node && Node->getLocation().getAs<PostStmt>())
657       Node = Node->getFirstPred();
658     if (!Node)
659       return;
660 
661     // Finally, see if we inlined the call.
662     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
663     if (!CEE)
664       return;
665 
666     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
667     if (CalleeContext->getCallSite() != S)
668       return;
669 
670     // Check the return value.
671     ProgramStateRef State = Node->getState();
672     SVal RetVal = Node->getSVal(S);
673 
674     // Handle cases where a reference is returned and then immediately used.
675     if (cast<Expr>(S)->isGLValue())
676       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
677         RetVal = State->getSVal(*LValue);
678 
679     // See if the return value is NULL. If so, suppress the report.
680     SubEngine *Eng = State->getStateManager().getOwningEngine();
681     assert(Eng && "Cannot file a bug report without an owning engine");
682     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
683 
684     bool EnableNullFPSuppression = false;
685     if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
686       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
687         EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
688 
689     BR.markInteresting(CalleeContext);
690     BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
691                                                    EnableNullFPSuppression));
692   }
693 
694   /// Returns true if any counter-suppression heuristics are enabled for
695   /// ReturnVisitor.
696   static bool hasCounterSuppression(AnalyzerOptions &Options) {
697     return Options.shouldAvoidSuppressingNullArgumentPaths();
698   }
699 
700   std::shared_ptr<PathDiagnosticPiece>
701   visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
702                    BugReporterContext &BRC, BugReport &BR) {
703     // Only print a message at the interesting return statement.
704     if (N->getLocationContext() != StackFrame)
705       return nullptr;
706 
707     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
708     if (!SP)
709       return nullptr;
710 
711     const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
712     if (!Ret)
713       return nullptr;
714 
715     // Okay, we're at the right return statement, but do we have the return
716     // value available?
717     ProgramStateRef State = N->getState();
718     SVal V = State->getSVal(Ret, StackFrame);
719     if (V.isUnknownOrUndef())
720       return nullptr;
721 
722     // Don't print any more notes after this one.
723     Mode = Satisfied;
724 
725     const Expr *RetE = Ret->getRetValue();
726     assert(RetE && "Tracking a return value for a void function");
727 
728     // Handle cases where a reference is returned and then immediately used.
729     Optional<Loc> LValue;
730     if (RetE->isGLValue()) {
731       if ((LValue = V.getAs<Loc>())) {
732         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
733         if (RValue.getAs<DefinedSVal>())
734           V = RValue;
735       }
736     }
737 
738     // Ignore aggregate rvalues.
739     if (V.getAs<nonloc::LazyCompoundVal>() ||
740         V.getAs<nonloc::CompoundVal>())
741       return nullptr;
742 
743     RetE = RetE->IgnoreParenCasts();
744 
745     // If we can't prove the return value is 0, just mark it interesting, and
746     // make sure to track it into any further inner functions.
747     if (!State->isNull(V).isConstrainedTrue()) {
748       BR.markInteresting(V);
749       ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
750                                            EnableNullFPSuppression);
751       return nullptr;
752     }
753 
754     // If we're returning 0, we should track where that 0 came from.
755     bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
756                                        EnableNullFPSuppression);
757 
758     // Build an appropriate message based on the return value.
759     SmallString<64> Msg;
760     llvm::raw_svector_ostream Out(Msg);
761 
762     if (V.getAs<Loc>()) {
763       // If we have counter-suppression enabled, make sure we keep visiting
764       // future nodes. We want to emit a path note as well, in case
765       // the report is resurrected as valid later on.
766       ExprEngine &Eng = BRC.getBugReporter().getEngine();
767       AnalyzerOptions &Options = Eng.getAnalysisManager().options;
768       if (EnableNullFPSuppression && hasCounterSuppression(Options))
769         Mode = MaybeUnsuppress;
770 
771       if (RetE->getType()->isObjCObjectPointerType())
772         Out << "Returning nil";
773       else
774         Out << "Returning null pointer";
775     } else {
776       Out << "Returning zero";
777     }
778 
779     if (LValue) {
780       if (const MemRegion *MR = LValue->getAsRegion()) {
781         if (MR->canPrintPretty()) {
782           Out << " (reference to ";
783           MR->printPretty(Out);
784           Out << ")";
785         }
786       }
787     } else {
788       // FIXME: We should have a more generalized location printing mechanism.
789       if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
790         if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
791           Out << " (loaded from '" << *DD << "')";
792     }
793 
794     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
795     if (!L.isValid() || !L.asLocation().isValid())
796       return nullptr;
797 
798     return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
799   }
800 
801   std::shared_ptr<PathDiagnosticPiece>
802   visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
803                            BugReporterContext &BRC, BugReport &BR) {
804 #ifndef NDEBUG
805     ExprEngine &Eng = BRC.getBugReporter().getEngine();
806     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
807     assert(hasCounterSuppression(Options));
808 #endif
809 
810     // Are we at the entry node for this call?
811     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
812     if (!CE)
813       return nullptr;
814 
815     if (CE->getCalleeContext() != StackFrame)
816       return nullptr;
817 
818     Mode = Satisfied;
819 
820     // Don't automatically suppress a report if one of the arguments is
821     // known to be a null pointer. Instead, start tracking /that/ null
822     // value back to its origin.
823     ProgramStateManager &StateMgr = BRC.getStateManager();
824     CallEventManager &CallMgr = StateMgr.getCallEventManager();
825 
826     ProgramStateRef State = N->getState();
827     CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
828     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
829       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
830       if (!ArgV)
831         continue;
832 
833       const Expr *ArgE = Call->getArgExpr(I);
834       if (!ArgE)
835         continue;
836 
837       // Is it possible for this argument to be non-null?
838       if (!State->isNull(*ArgV).isConstrainedTrue())
839         continue;
840 
841       if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
842                                              EnableNullFPSuppression))
843         BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
844 
845       // If we /can't/ track the null pointer, we should err on the side of
846       // false negatives, and continue towards marking this report invalid.
847       // (We will still look at the other arguments, though.)
848     }
849 
850     return nullptr;
851   }
852 
853   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
854                                                  const ExplodedNode *PrevN,
855                                                  BugReporterContext &BRC,
856                                                  BugReport &BR) override {
857     switch (Mode) {
858     case Initial:
859       return visitNodeInitial(N, PrevN, BRC, BR);
860     case MaybeUnsuppress:
861       return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
862     case Satisfied:
863       return nullptr;
864     }
865 
866     llvm_unreachable("Invalid visit mode!");
867   }
868 
869   std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
870                                                   const ExplodedNode *N,
871                                                   BugReport &BR) override {
872     if (EnableNullFPSuppression)
873       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
874     return nullptr;
875   }
876 };
877 
878 } // namespace
879 
880 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
881   static int tag = 0;
882   ID.AddPointer(&tag);
883   ID.AddPointer(R);
884   ID.Add(V);
885   ID.AddBoolean(EnableNullFPSuppression);
886 }
887 
888 /// Returns true if \p N represents the DeclStmt declaring and initializing
889 /// \p VR.
890 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
891   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
892   if (!P)
893     return false;
894 
895   const DeclStmt *DS = P->getStmtAs<DeclStmt>();
896   if (!DS)
897     return false;
898 
899   if (DS->getSingleDecl() != VR->getDecl())
900     return false;
901 
902   const MemSpaceRegion *VarSpace = VR->getMemorySpace();
903   const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
904   if (!FrameSpace) {
905     // If we ever directly evaluate global DeclStmts, this assertion will be
906     // invalid, but this still seems preferable to silently accepting an
907     // initialization that may be for a path-sensitive variable.
908     assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
909     return true;
910   }
911 
912   assert(VR->getDecl()->hasLocalStorage());
913   const LocationContext *LCtx = N->getLocationContext();
914   return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
915 }
916 
917 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
918 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
919                               const MemRegion *R, SVal V, const DeclStmt *DS) {
920   if (R->canPrintPretty()) {
921     R->printPretty(os);
922     os << " ";
923   }
924 
925   if (V.getAs<loc::ConcreteInt>()) {
926     bool b = false;
927     if (R->isBoundable()) {
928       if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
929         if (TR->getValueType()->isObjCObjectPointerType()) {
930           os << action << "nil";
931           b = true;
932         }
933       }
934     }
935     if (!b)
936       os << action << "a null pointer value";
937 
938   } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
939     os << action << CVal->getValue();
940   } else if (DS) {
941     if (V.isUndef()) {
942       if (isa<VarRegion>(R)) {
943         const auto *VD = cast<VarDecl>(DS->getSingleDecl());
944         if (VD->getInit()) {
945           os << (R->canPrintPretty() ? "initialized" : "Initializing")
946             << " to a garbage value";
947         } else {
948           os << (R->canPrintPretty() ? "declared" : "Declaring")
949             << " without an initial value";
950         }
951       }
952     } else {
953       os << (R->canPrintPretty() ? "initialized" : "Initialized")
954         << " here";
955     }
956   }
957 }
958 
959 /// Display diagnostics for passing bad region as a parameter.
960 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
961     const VarRegion *VR,
962     SVal V) {
963   const auto *Param = cast<ParmVarDecl>(VR->getDecl());
964 
965   os << "Passing ";
966 
967   if (V.getAs<loc::ConcreteInt>()) {
968     if (Param->getType()->isObjCObjectPointerType())
969       os << "nil object reference";
970     else
971       os << "null pointer value";
972   } else if (V.isUndef()) {
973     os << "uninitialized value";
974   } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
975     os << "the value " << CI->getValue();
976   } else {
977     os << "value";
978   }
979 
980   // Printed parameter indexes are 1-based, not 0-based.
981   unsigned Idx = Param->getFunctionScopeIndex() + 1;
982   os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
983   if (VR->canPrintPretty()) {
984     os << " ";
985     VR->printPretty(os);
986   }
987 }
988 
989 /// Show default diagnostics for storing bad region.
990 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
991     const MemRegion *R,
992     SVal V) {
993   if (V.getAs<loc::ConcreteInt>()) {
994     bool b = false;
995     if (R->isBoundable()) {
996       if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
997         if (TR->getValueType()->isObjCObjectPointerType()) {
998           os << "nil object reference stored";
999           b = true;
1000         }
1001       }
1002     }
1003     if (!b) {
1004       if (R->canPrintPretty())
1005         os << "Null pointer value stored";
1006       else
1007         os << "Storing null pointer value";
1008     }
1009 
1010   } else if (V.isUndef()) {
1011     if (R->canPrintPretty())
1012       os << "Uninitialized value stored";
1013     else
1014       os << "Storing uninitialized value";
1015 
1016   } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1017     if (R->canPrintPretty())
1018       os << "The value " << CV->getValue() << " is assigned";
1019     else
1020       os << "Assigning " << CV->getValue();
1021 
1022   } else {
1023     if (R->canPrintPretty())
1024       os << "Value assigned";
1025     else
1026       os << "Assigning value";
1027   }
1028 
1029   if (R->canPrintPretty()) {
1030     os << " to ";
1031     R->printPretty(os);
1032   }
1033 }
1034 
1035 std::shared_ptr<PathDiagnosticPiece>
1036 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1037                                   const ExplodedNode *Pred,
1038                                   BugReporterContext &BRC, BugReport &BR) {
1039   if (Satisfied)
1040     return nullptr;
1041 
1042   const ExplodedNode *StoreSite = nullptr;
1043   const Expr *InitE = nullptr;
1044   bool IsParam = false;
1045 
1046   // First see if we reached the declaration of the region.
1047   if (const auto *VR = dyn_cast<VarRegion>(R)) {
1048     if (isInitializationOfVar(Pred, VR)) {
1049       StoreSite = Pred;
1050       InitE = VR->getDecl()->getInit();
1051     }
1052   }
1053 
1054   // If this is a post initializer expression, initializing the region, we
1055   // should track the initializer expression.
1056   if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1057     const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1058     if (FieldReg && FieldReg == R) {
1059       StoreSite = Pred;
1060       InitE = PIP->getInitializer()->getInit();
1061     }
1062   }
1063 
1064   // Otherwise, see if this is the store site:
1065   // (1) Succ has this binding and Pred does not, i.e. this is
1066   //     where the binding first occurred.
1067   // (2) Succ has this binding and is a PostStore node for this region, i.e.
1068   //     the same binding was re-assigned here.
1069   if (!StoreSite) {
1070     if (Succ->getState()->getSVal(R) != V)
1071       return nullptr;
1072 
1073     if (Pred->getState()->getSVal(R) == V) {
1074       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1075       if (!PS || PS->getLocationValue() != R)
1076         return nullptr;
1077     }
1078 
1079     StoreSite = Succ;
1080 
1081     // If this is an assignment expression, we can track the value
1082     // being assigned.
1083     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1084       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1085         if (BO->isAssignmentOp())
1086           InitE = BO->getRHS();
1087 
1088     // If this is a call entry, the variable should be a parameter.
1089     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1090     // 'this' should never be NULL, but this visitor isn't just for NULL and
1091     // UndefinedVal.)
1092     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1093       if (const auto *VR = dyn_cast<VarRegion>(R)) {
1094         const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1095 
1096         ProgramStateManager &StateMgr = BRC.getStateManager();
1097         CallEventManager &CallMgr = StateMgr.getCallEventManager();
1098 
1099         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1100                                                 Succ->getState());
1101         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1102         IsParam = true;
1103       }
1104     }
1105 
1106     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1107     // is wrapped inside of it.
1108     if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1109       InitE = TmpR->getExpr();
1110   }
1111 
1112   if (!StoreSite)
1113     return nullptr;
1114   Satisfied = true;
1115 
1116   // If we have an expression that provided the value, try to track where it
1117   // came from.
1118   if (InitE) {
1119     if (V.isUndef() ||
1120         V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1121       if (!IsParam)
1122         InitE = InitE->IgnoreParenCasts();
1123       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
1124                                          EnableNullFPSuppression);
1125     } else {
1126       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
1127                                            BR, EnableNullFPSuppression);
1128     }
1129   }
1130 
1131   // Okay, we've found the binding. Emit an appropriate message.
1132   SmallString<256> sbuf;
1133   llvm::raw_svector_ostream os(sbuf);
1134 
1135   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1136     const Stmt *S = PS->getStmt();
1137     const char *action = nullptr;
1138     const auto *DS = dyn_cast<DeclStmt>(S);
1139     const auto *VR = dyn_cast<VarRegion>(R);
1140 
1141     if (DS) {
1142       action = R->canPrintPretty() ? "initialized to " :
1143                                      "Initializing to ";
1144     } else if (isa<BlockExpr>(S)) {
1145       action = R->canPrintPretty() ? "captured by block as " :
1146                                      "Captured by block as ";
1147       if (VR) {
1148         // See if we can get the BlockVarRegion.
1149         ProgramStateRef State = StoreSite->getState();
1150         SVal V = StoreSite->getSVal(S);
1151         if (const auto *BDR =
1152               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1153           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1154             if (Optional<KnownSVal> KV =
1155                 State->getSVal(OriginalR).getAs<KnownSVal>())
1156               BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1157                   *KV, OriginalR, EnableNullFPSuppression));
1158           }
1159         }
1160       }
1161     }
1162     if (action)
1163       showBRDiagnostics(action, os, R, V, DS);
1164 
1165   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
1166     if (const auto *VR = dyn_cast<VarRegion>(R))
1167       showBRParamDiagnostics(os, VR, V);
1168   }
1169 
1170   if (os.str().empty())
1171     showBRDefaultDiagnostics(os, R, V);
1172 
1173   // Construct a new PathDiagnosticPiece.
1174   ProgramPoint P = StoreSite->getLocation();
1175   PathDiagnosticLocation L;
1176   if (P.getAs<CallEnter>() && InitE)
1177     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1178                                P.getLocationContext());
1179 
1180   if (!L.isValid() || !L.asLocation().isValid())
1181     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1182 
1183   if (!L.isValid() || !L.asLocation().isValid())
1184     return nullptr;
1185 
1186   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1187 }
1188 
1189 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1190   static int tag = 0;
1191   ID.AddPointer(&tag);
1192   ID.AddBoolean(Assumption);
1193   ID.Add(Constraint);
1194 }
1195 
1196 /// Return the tag associated with this visitor.  This tag will be used
1197 /// to make all PathDiagnosticPieces created by this visitor.
1198 const char *TrackConstraintBRVisitor::getTag() {
1199   return "TrackConstraintBRVisitor";
1200 }
1201 
1202 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1203   if (IsZeroCheck)
1204     return N->getState()->isNull(Constraint).isUnderconstrained();
1205   return (bool)N->getState()->assume(Constraint, !Assumption);
1206 }
1207 
1208 std::shared_ptr<PathDiagnosticPiece>
1209 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
1210                                     const ExplodedNode *PrevN,
1211                                     BugReporterContext &BRC, BugReport &BR) {
1212   if (IsSatisfied)
1213     return nullptr;
1214 
1215   // Start tracking after we see the first state in which the value is
1216   // constrained.
1217   if (!IsTrackingTurnedOn)
1218     if (!isUnderconstrained(N))
1219       IsTrackingTurnedOn = true;
1220   if (!IsTrackingTurnedOn)
1221     return nullptr;
1222 
1223   // Check if in the previous state it was feasible for this constraint
1224   // to *not* be true.
1225   if (isUnderconstrained(PrevN)) {
1226     IsSatisfied = true;
1227 
1228     // As a sanity check, make sure that the negation of the constraint
1229     // was infeasible in the current state.  If it is feasible, we somehow
1230     // missed the transition point.
1231     assert(!isUnderconstrained(N));
1232 
1233     // We found the transition point for the constraint.  We now need to
1234     // pretty-print the constraint. (work-in-progress)
1235     SmallString<64> sbuf;
1236     llvm::raw_svector_ostream os(sbuf);
1237 
1238     if (Constraint.getAs<Loc>()) {
1239       os << "Assuming pointer value is ";
1240       os << (Assumption ? "non-null" : "null");
1241     }
1242 
1243     if (os.str().empty())
1244       return nullptr;
1245 
1246     // Construct a new PathDiagnosticPiece.
1247     ProgramPoint P = N->getLocation();
1248     PathDiagnosticLocation L =
1249       PathDiagnosticLocation::create(P, BRC.getSourceManager());
1250     if (!L.isValid())
1251       return nullptr;
1252 
1253     auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1254     X->setTag(getTag());
1255     return std::move(X);
1256   }
1257 
1258   return nullptr;
1259 }
1260 
1261 SuppressInlineDefensiveChecksVisitor::
1262 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1263     : V(Value) {
1264   // Check if the visitor is disabled.
1265   SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
1266   assert(Eng && "Cannot file a bug report without an owning engine");
1267   AnalyzerOptions &Options = Eng->getAnalysisManager().options;
1268   if (!Options.shouldSuppressInlinedDefensiveChecks())
1269     IsSatisfied = true;
1270 
1271   assert(N->getState()->isNull(V).isConstrainedTrue() &&
1272          "The visitor only tracks the cases where V is constrained to 0");
1273 }
1274 
1275 void SuppressInlineDefensiveChecksVisitor::Profile(
1276     llvm::FoldingSetNodeID &ID) const {
1277   static int id = 0;
1278   ID.AddPointer(&id);
1279   ID.Add(V);
1280 }
1281 
1282 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1283   return "IDCVisitor";
1284 }
1285 
1286 std::shared_ptr<PathDiagnosticPiece>
1287 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1288                                                 const ExplodedNode *Pred,
1289                                                 BugReporterContext &BRC,
1290                                                 BugReport &BR) {
1291   if (IsSatisfied)
1292     return nullptr;
1293 
1294   // Start tracking after we see the first state in which the value is null.
1295   if (!IsTrackingTurnedOn)
1296     if (Succ->getState()->isNull(V).isConstrainedTrue())
1297       IsTrackingTurnedOn = true;
1298   if (!IsTrackingTurnedOn)
1299     return nullptr;
1300 
1301   // Check if in the previous state it was feasible for this value
1302   // to *not* be null.
1303   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1304     IsSatisfied = true;
1305 
1306     assert(Succ->getState()->isNull(V).isConstrainedTrue());
1307 
1308     // Check if this is inlined defensive checks.
1309     const LocationContext *CurLC =Succ->getLocationContext();
1310     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1311     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
1312       BR.markInvalid("Suppress IDC", CurLC);
1313       return nullptr;
1314     }
1315 
1316     // Treat defensive checks in function-like macros as if they were an inlined
1317     // defensive check. If the bug location is not in a macro and the
1318     // terminator for the current location is in a macro then suppress the
1319     // warning.
1320     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1321 
1322     if (!BugPoint)
1323       return nullptr;
1324 
1325     ProgramPoint CurPoint = Succ->getLocation();
1326     const Stmt *CurTerminatorStmt = nullptr;
1327     if (auto BE = CurPoint.getAs<BlockEdge>()) {
1328       CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1329     } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1330       const Stmt *CurStmt = SP->getStmt();
1331       if (!CurStmt->getLocStart().isMacroID())
1332         return nullptr;
1333 
1334       CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1335       CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
1336     } else {
1337       return nullptr;
1338     }
1339 
1340     if (!CurTerminatorStmt)
1341       return nullptr;
1342 
1343     SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
1344     if (TerminatorLoc.isMacroID()) {
1345       SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
1346 
1347       // Suppress reports unless we are in that same macro.
1348       if (!BugLoc.isMacroID() ||
1349           getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1350         BR.markInvalid("Suppress Macro IDC", CurLC);
1351       }
1352       return nullptr;
1353     }
1354   }
1355   return nullptr;
1356 }
1357 
1358 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1359                                                      const ExplodedNode *N) {
1360   if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1361     if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1362       if (!VD->getType()->isReferenceType())
1363         return nullptr;
1364       ProgramStateManager &StateMgr = N->getState()->getStateManager();
1365       MemRegionManager &MRMgr = StateMgr.getRegionManager();
1366       return MRMgr.getVarRegion(VD, N->getLocationContext());
1367     }
1368   }
1369 
1370   // FIXME: This does not handle other kinds of null references,
1371   // for example, references from FieldRegions:
1372   //   struct Wrapper { int &ref; };
1373   //   Wrapper w = { *(int *)0 };
1374   //   w.ref = 1;
1375 
1376   return nullptr;
1377 }
1378 
1379 static const Expr *peelOffOuterExpr(const Expr *Ex,
1380                                     const ExplodedNode *N) {
1381   Ex = Ex->IgnoreParenCasts();
1382   if (const auto *EWC = dyn_cast<ExprWithCleanups>(Ex))
1383     return peelOffOuterExpr(EWC->getSubExpr(), N);
1384   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1385     return peelOffOuterExpr(OVE->getSourceExpr(), N);
1386   if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1387     const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1388     if (PropRef && PropRef->isMessagingGetter()) {
1389       const Expr *GetterMessageSend =
1390           POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1391       assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1392       return peelOffOuterExpr(GetterMessageSend, N);
1393     }
1394   }
1395 
1396   // Peel off the ternary operator.
1397   if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1398     // Find a node where the branching occurred and find out which branch
1399     // we took (true/false) by looking at the ExplodedGraph.
1400     const ExplodedNode *NI = N;
1401     do {
1402       ProgramPoint ProgPoint = NI->getLocation();
1403       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1404         const CFGBlock *srcBlk = BE->getSrc();
1405         if (const Stmt *term = srcBlk->getTerminator()) {
1406           if (term == CO) {
1407             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1408             if (TookTrueBranch)
1409               return peelOffOuterExpr(CO->getTrueExpr(), N);
1410             else
1411               return peelOffOuterExpr(CO->getFalseExpr(), N);
1412           }
1413         }
1414       }
1415       NI = NI->getFirstPred();
1416     } while (NI);
1417   }
1418 
1419   if (auto *BO = dyn_cast<BinaryOperator>(Ex))
1420     if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1421       return peelOffOuterExpr(SubEx, N);
1422 
1423   return Ex;
1424 }
1425 
1426 /// Walk through nodes until we get one that matches the statement exactly.
1427 /// Alternately, if we hit a known lvalue for the statement, we know we've
1428 /// gone too far (though we can likely track the lvalue better anyway).
1429 static const ExplodedNode* findNodeForStatement(const ExplodedNode *N,
1430                                                 const Stmt *S,
1431                                                 const Expr *Inner) {
1432   do {
1433     const ProgramPoint &pp = N->getLocation();
1434     if (auto ps = pp.getAs<StmtPoint>()) {
1435       if (ps->getStmt() == S || ps->getStmt() == Inner)
1436         break;
1437     } else if (auto CEE = pp.getAs<CallExitEnd>()) {
1438       if (CEE->getCalleeContext()->getCallSite() == S ||
1439           CEE->getCalleeContext()->getCallSite() == Inner)
1440         break;
1441     }
1442     N = N->getFirstPred();
1443   } while (N);
1444   return N;
1445 }
1446 
1447 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1448 /// was computed.
1449 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1450     const Expr *Inner) {
1451   while (N) {
1452     if (auto P = N->getLocation().getAs<PostStmt>()) {
1453       if (P->getStmt() == Inner)
1454         break;
1455     }
1456     N = N->getFirstPred();
1457   }
1458   assert(N && "Unable to find the lvalue node.");
1459   return N;
1460 }
1461 
1462 /// Performing operator `&' on an lvalue expression is essentially a no-op.
1463 /// Then, if we are taking addresses of fields or elements, these are also
1464 /// unlikely to matter.
1465 static const Expr* peelOfOuterAddrOf(const Expr* Ex) {
1466   Ex = Ex->IgnoreParenCasts();
1467 
1468   // FIXME: There's a hack in our Store implementation that always computes
1469   // field offsets around null pointers as if they are always equal to 0.
1470   // The idea here is to report accesses to fields as null dereferences
1471   // even though the pointer value that's being dereferenced is actually
1472   // the offset of the field rather than exactly 0.
1473   // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1474   // This code interacts heavily with this hack; otherwise the value
1475   // would not be null at all for most fields, so we'd be unable to track it.
1476   if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
1477     if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
1478       if (const Expr *DerefEx = bugreporter::getDerefExpr(Op->getSubExpr()))
1479         return DerefEx;
1480   return Ex;
1481 }
1482 
1483 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
1484                                         const Stmt *S,
1485                                         BugReport &report, bool IsArg,
1486                                         bool EnableNullFPSuppression) {
1487   if (!S || !N)
1488     return false;
1489 
1490   if (const auto *Ex = dyn_cast<Expr>(S))
1491     S = peelOffOuterExpr(Ex, N);
1492 
1493   const Expr *Inner = nullptr;
1494   if (const auto *Ex = dyn_cast<Expr>(S)) {
1495     Ex = peelOfOuterAddrOf(Ex);
1496     Ex = Ex->IgnoreParenCasts();
1497 
1498     if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex)
1499           || CallEvent::isCallStmt(Ex)))
1500       Inner = Ex;
1501   }
1502 
1503   if (IsArg && !Inner) {
1504     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
1505   } else {
1506     N = findNodeForStatement(N, S, Inner);
1507     if (!N)
1508       return false;
1509   }
1510 
1511   ProgramStateRef state = N->getState();
1512 
1513   // The message send could be nil due to the receiver being nil.
1514   // At this point in the path, the receiver should be live since we are at the
1515   // message send expr. If it is nil, start tracking it.
1516   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
1517     trackNullOrUndefValue(N, Receiver, report, /* IsArg=*/ false,
1518         EnableNullFPSuppression);
1519 
1520   // See if the expression we're interested refers to a variable.
1521   // If so, we can track both its contents and constraints on its value.
1522   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1523     const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
1524     ProgramStateRef LVState = LVNode->getState();
1525     SVal LVal = LVNode->getSVal(Inner);
1526 
1527     const MemRegion *RR = getLocationRegionIfReference(Inner, N);
1528     bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1529 
1530     // If this is a C++ reference to a null pointer, we are tracking the
1531     // pointer. In addition, we should find the store at which the reference
1532     // got initialized.
1533     if (RR && !LVIsNull) {
1534       if (auto KV = LVal.getAs<KnownSVal>())
1535         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1536               *KV, RR, EnableNullFPSuppression));
1537     }
1538 
1539     // In case of C++ references, we want to differentiate between a null
1540     // reference and reference to null pointer.
1541     // If the LVal is null, check if we are dealing with null reference.
1542     // For those, we want to track the location of the reference.
1543     const MemRegion *R = (RR && LVIsNull) ? RR :
1544         LVNode->getSVal(Inner).getAsRegion();
1545 
1546     if (R) {
1547       // Mark both the variable region and its contents as interesting.
1548       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1549       report.addVisitor(
1550           llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
1551 
1552       MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1553           N, R, EnableNullFPSuppression, report, V);
1554 
1555       report.markInteresting(R);
1556       report.markInteresting(V);
1557       report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1558 
1559       // If the contents are symbolic, find out when they became null.
1560       if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1561         report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1562               V.castAs<DefinedSVal>(), false));
1563 
1564       // Add visitor, which will suppress inline defensive checks.
1565       if (auto DV = V.getAs<DefinedSVal>()) {
1566         if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1567             EnableNullFPSuppression) {
1568           report.addVisitor(
1569               llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1570                 LVNode));
1571         }
1572       }
1573 
1574       if (auto KV = V.getAs<KnownSVal>())
1575         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1576               *KV, R, EnableNullFPSuppression));
1577       return true;
1578     }
1579   }
1580 
1581   // If the expression is not an "lvalue expression", we can still
1582   // track the constraints on its contents.
1583   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1584 
1585   // If the value came from an inlined function call, we should at least make
1586   // sure that function isn't pruned in our output.
1587   if (const auto *E = dyn_cast<Expr>(S))
1588     S = E->IgnoreParenCasts();
1589 
1590   ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1591 
1592   // Uncomment this to find cases where we aren't properly getting the
1593   // base value that was dereferenced.
1594   // assert(!V.isUnknownOrUndef());
1595   // Is it a symbolic value?
1596   if (auto L = V.getAs<loc::MemRegionVal>()) {
1597     report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1598 
1599     // At this point we are dealing with the region's LValue.
1600     // However, if the rvalue is a symbolic region, we should track it as well.
1601     // Try to use the correct type when looking up the value.
1602     SVal RVal;
1603     if (const auto *E = dyn_cast<Expr>(S))
1604       RVal = state->getRawSVal(L.getValue(), E->getType());
1605     else
1606       RVal = state->getSVal(L->getRegion());
1607 
1608     if (auto KV = RVal.getAs<KnownSVal>())
1609       report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1610             *KV, L->getRegion(), EnableNullFPSuppression));
1611 
1612     const MemRegion *RegionRVal = RVal.getAsRegion();
1613     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1614       report.markInteresting(RegionRVal);
1615       report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1616             loc::MemRegionVal(RegionRVal), false));
1617     }
1618   }
1619   return true;
1620 }
1621 
1622 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1623                                                  const ExplodedNode *N) {
1624   const auto *ME = dyn_cast<ObjCMessageExpr>(S);
1625   if (!ME)
1626     return nullptr;
1627   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1628     ProgramStateRef state = N->getState();
1629     SVal V = N->getSVal(Receiver);
1630     if (state->isNull(V).isConstrainedTrue())
1631       return Receiver;
1632   }
1633   return nullptr;
1634 }
1635 
1636 std::shared_ptr<PathDiagnosticPiece>
1637 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1638                                 const ExplodedNode *PrevN,
1639                                 BugReporterContext &BRC, BugReport &BR) {
1640   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1641   if (!P)
1642     return nullptr;
1643 
1644   const Stmt *S = P->getStmt();
1645   const Expr *Receiver = getNilReceiver(S, N);
1646   if (!Receiver)
1647     return nullptr;
1648 
1649   llvm::SmallString<256> Buf;
1650   llvm::raw_svector_ostream OS(Buf);
1651 
1652   if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1653     OS << "'";
1654     ME->getSelector().print(OS);
1655     OS << "' not called";
1656   }
1657   else {
1658     OS << "No method is called";
1659   }
1660   OS << " because the receiver is nil";
1661 
1662   // The receiver was nil, and hence the method was skipped.
1663   // Register a BugReporterVisitor to issue a message telling us how
1664   // the receiver was null.
1665   bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1666                                      /*EnableNullFPSuppression*/ false);
1667   // Issue a message saying that the method was skipped.
1668   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1669                                      N->getLocationContext());
1670   return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1671 }
1672 
1673 // Registers every VarDecl inside a Stmt with a last store visitor.
1674 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1675                                                 const Stmt *S,
1676                                                 bool EnableNullFPSuppression) {
1677   const ExplodedNode *N = BR.getErrorNode();
1678   std::deque<const Stmt *> WorkList;
1679   WorkList.push_back(S);
1680 
1681   while (!WorkList.empty()) {
1682     const Stmt *Head = WorkList.front();
1683     WorkList.pop_front();
1684 
1685     ProgramStateManager &StateMgr = N->getState()->getStateManager();
1686 
1687     if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
1688       if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1689         const VarRegion *R =
1690         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1691 
1692         // What did we load?
1693         SVal V = N->getSVal(S);
1694 
1695         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1696           // Register a new visitor with the BugReport.
1697           BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1698               V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1699         }
1700       }
1701     }
1702 
1703     for (const Stmt *SubStmt : Head->children())
1704       WorkList.push_back(SubStmt);
1705   }
1706 }
1707 
1708 //===----------------------------------------------------------------------===//
1709 // Visitor that tries to report interesting diagnostics from conditions.
1710 //===----------------------------------------------------------------------===//
1711 
1712 /// Return the tag associated with this visitor.  This tag will be used
1713 /// to make all PathDiagnosticPieces created by this visitor.
1714 const char *ConditionBRVisitor::getTag() {
1715   return "ConditionBRVisitor";
1716 }
1717 
1718 std::shared_ptr<PathDiagnosticPiece>
1719 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1720                               BugReporterContext &BRC, BugReport &BR) {
1721   auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1722   if (piece) {
1723     piece->setTag(getTag());
1724     if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1725       ev->setPrunable(true, /* override */ false);
1726   }
1727   return piece;
1728 }
1729 
1730 std::shared_ptr<PathDiagnosticPiece>
1731 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1732                                   const ExplodedNode *Prev,
1733                                   BugReporterContext &BRC, BugReport &BR) {
1734   ProgramPoint progPoint = N->getLocation();
1735   ProgramStateRef CurrentState = N->getState();
1736   ProgramStateRef PrevState = Prev->getState();
1737 
1738   // Compare the GDMs of the state, because that is where constraints
1739   // are managed.  Note that ensure that we only look at nodes that
1740   // were generated by the analyzer engine proper, not checkers.
1741   if (CurrentState->getGDM().getRoot() ==
1742       PrevState->getGDM().getRoot())
1743     return nullptr;
1744 
1745   // If an assumption was made on a branch, it should be caught
1746   // here by looking at the state transition.
1747   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1748     const CFGBlock *srcBlk = BE->getSrc();
1749     if (const Stmt *term = srcBlk->getTerminator())
1750       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1751     return nullptr;
1752   }
1753 
1754   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1755     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1756     // violation.
1757     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1758       cast<GRBugReporter>(BRC.getBugReporter()).
1759         getEngine().geteagerlyAssumeBinOpBifurcationTags();
1760 
1761     const ProgramPointTag *tag = PS->getTag();
1762     if (tag == tags.first)
1763       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1764                            BRC, BR, N);
1765     if (tag == tags.second)
1766       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1767                            BRC, BR, N);
1768 
1769     return nullptr;
1770   }
1771 
1772   return nullptr;
1773 }
1774 
1775 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1776     const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1777     const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1778   const Expr *Cond = nullptr;
1779 
1780   // In the code below, Term is a CFG terminator and Cond is a branch condition
1781   // expression upon which the decision is made on this terminator.
1782   //
1783   // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1784   // and "x == 0" is the respective condition.
1785   //
1786   // Another example: in "if (x && y)", we've got two terminators and two
1787   // conditions due to short-circuit nature of operator "&&":
1788   // 1. The "if (x && y)" statement is a terminator,
1789   //    and "y" is the respective condition.
1790   // 2. Also "x && ..." is another terminator,
1791   //    and "x" is its condition.
1792 
1793   switch (Term->getStmtClass()) {
1794   // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1795   // more tricky because there are more than two branches to account for.
1796   default:
1797     return nullptr;
1798   case Stmt::IfStmtClass:
1799     Cond = cast<IfStmt>(Term)->getCond();
1800     break;
1801   case Stmt::ConditionalOperatorClass:
1802     Cond = cast<ConditionalOperator>(Term)->getCond();
1803     break;
1804   case Stmt::BinaryOperatorClass:
1805     // When we encounter a logical operator (&& or ||) as a CFG terminator,
1806     // then the condition is actually its LHS; otherwise, we'd encounter
1807     // the parent, such as if-statement, as a terminator.
1808     const auto *BO = cast<BinaryOperator>(Term);
1809     assert(BO->isLogicalOp() &&
1810            "CFG terminator is not a short-circuit operator!");
1811     Cond = BO->getLHS();
1812     break;
1813   }
1814 
1815   // However, when we encounter a logical operator as a branch condition,
1816   // then the condition is actually its RHS, because LHS would be
1817   // the condition for the logical operator terminator.
1818   while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1819     if (!InnerBO->isLogicalOp())
1820       break;
1821     Cond = InnerBO->getRHS()->IgnoreParens();
1822   }
1823 
1824   assert(Cond);
1825   assert(srcBlk->succ_size() == 2);
1826   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1827   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1828 }
1829 
1830 std::shared_ptr<PathDiagnosticPiece>
1831 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1832                                   BugReporterContext &BRC, BugReport &R,
1833                                   const ExplodedNode *N) {
1834   // These will be modified in code below, but we need to preserve the original
1835   //  values in case we want to throw the generic message.
1836   const Expr *CondTmp = Cond;
1837   bool tookTrueTmp = tookTrue;
1838 
1839   while (true) {
1840     CondTmp = CondTmp->IgnoreParenCasts();
1841     switch (CondTmp->getStmtClass()) {
1842       default:
1843         break;
1844       case Stmt::BinaryOperatorClass:
1845         if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1846                                    tookTrueTmp, BRC, R, N))
1847           return P;
1848         break;
1849       case Stmt::DeclRefExprClass:
1850         if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1851                                    tookTrueTmp, BRC, R, N))
1852           return P;
1853         break;
1854       case Stmt::UnaryOperatorClass: {
1855         const auto *UO = cast<UnaryOperator>(CondTmp);
1856         if (UO->getOpcode() == UO_LNot) {
1857           tookTrueTmp = !tookTrueTmp;
1858           CondTmp = UO->getSubExpr();
1859           continue;
1860         }
1861         break;
1862       }
1863     }
1864     break;
1865   }
1866 
1867   // Condition too complex to explain? Just say something so that the user
1868   // knew we've made some path decision at this point.
1869   const LocationContext *LCtx = N->getLocationContext();
1870   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1871   if (!Loc.isValid() || !Loc.asLocation().isValid())
1872     return nullptr;
1873 
1874   return std::make_shared<PathDiagnosticEventPiece>(
1875       Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1876 }
1877 
1878 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1879                                       const Expr *ParentEx,
1880                                       raw_ostream &Out,
1881                                       BugReporterContext &BRC,
1882                                       BugReport &report,
1883                                       const ExplodedNode *N,
1884                                       Optional<bool> &prunable) {
1885   const Expr *OriginalExpr = Ex;
1886   Ex = Ex->IgnoreParenCasts();
1887 
1888   // Use heuristics to determine if Ex is a macro expending to a literal and
1889   // if so, use the macro's name.
1890   SourceLocation LocStart = Ex->getLocStart();
1891   SourceLocation LocEnd = Ex->getLocEnd();
1892   if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1893       (isa<GNUNullExpr>(Ex) ||
1894        isa<ObjCBoolLiteralExpr>(Ex) ||
1895        isa<CXXBoolLiteralExpr>(Ex) ||
1896        isa<IntegerLiteral>(Ex) ||
1897        isa<FloatingLiteral>(Ex))) {
1898     StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1899       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1900     StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1901       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1902     bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1903 
1904     bool partOfParentMacro = false;
1905     if (ParentEx->getLocStart().isMacroID()) {
1906       StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1907         ParentEx->getLocStart(), BRC.getSourceManager(),
1908         BRC.getASTContext().getLangOpts());
1909       partOfParentMacro = PName.equals(StartName);
1910     }
1911 
1912     if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1913       // Get the location of the macro name as written by the caller.
1914       SourceLocation Loc = LocStart;
1915       while (LocStart.isMacroID()) {
1916         Loc = LocStart;
1917         LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1918       }
1919       StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1920         Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1921 
1922       // Return the macro name.
1923       Out << MacroName;
1924       return false;
1925     }
1926   }
1927 
1928   if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
1929     const bool quotes = isa<VarDecl>(DR->getDecl());
1930     if (quotes) {
1931       Out << '\'';
1932       const LocationContext *LCtx = N->getLocationContext();
1933       const ProgramState *state = N->getState().get();
1934       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1935                                                 LCtx).getAsRegion()) {
1936         if (report.isInteresting(R))
1937           prunable = false;
1938         else {
1939           const ProgramState *state = N->getState().get();
1940           SVal V = state->getSVal(R);
1941           if (report.isInteresting(V))
1942             prunable = false;
1943         }
1944       }
1945     }
1946     Out << DR->getDecl()->getDeclName().getAsString();
1947     if (quotes)
1948       Out << '\'';
1949     return quotes;
1950   }
1951 
1952   if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
1953     QualType OriginalTy = OriginalExpr->getType();
1954     if (OriginalTy->isPointerType()) {
1955       if (IL->getValue() == 0) {
1956         Out << "null";
1957         return false;
1958       }
1959     }
1960     else if (OriginalTy->isObjCObjectPointerType()) {
1961       if (IL->getValue() == 0) {
1962         Out << "nil";
1963         return false;
1964       }
1965     }
1966 
1967     Out << IL->getValue();
1968     return false;
1969   }
1970 
1971   return false;
1972 }
1973 
1974 std::shared_ptr<PathDiagnosticPiece>
1975 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
1976                                   const bool tookTrue, BugReporterContext &BRC,
1977                                   BugReport &R, const ExplodedNode *N) {
1978   bool shouldInvert = false;
1979   Optional<bool> shouldPrune;
1980 
1981   SmallString<128> LhsString, RhsString;
1982   {
1983     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1984     const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
1985                                        BRC, R, N, shouldPrune);
1986     const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
1987                                        BRC, R, N, shouldPrune);
1988 
1989     shouldInvert = !isVarLHS && isVarRHS;
1990   }
1991 
1992   BinaryOperator::Opcode Op = BExpr->getOpcode();
1993 
1994   if (BinaryOperator::isAssignmentOp(Op)) {
1995     // For assignment operators, all that we care about is that the LHS
1996     // evaluates to "true" or "false".
1997     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1998                                   BRC, R, N);
1999   }
2000 
2001   // For non-assignment operations, we require that we can understand
2002   // both the LHS and RHS.
2003   if (LhsString.empty() || RhsString.empty() ||
2004       !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
2005     return nullptr;
2006 
2007   // Should we invert the strings if the LHS is not a variable name?
2008   SmallString<256> buf;
2009   llvm::raw_svector_ostream Out(buf);
2010   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
2011 
2012   // Do we need to invert the opcode?
2013   if (shouldInvert)
2014     switch (Op) {
2015       default: break;
2016       case BO_LT: Op = BO_GT; break;
2017       case BO_GT: Op = BO_LT; break;
2018       case BO_LE: Op = BO_GE; break;
2019       case BO_GE: Op = BO_LE; break;
2020     }
2021 
2022   if (!tookTrue)
2023     switch (Op) {
2024       case BO_EQ: Op = BO_NE; break;
2025       case BO_NE: Op = BO_EQ; break;
2026       case BO_LT: Op = BO_GE; break;
2027       case BO_GT: Op = BO_LE; break;
2028       case BO_LE: Op = BO_GT; break;
2029       case BO_GE: Op = BO_LT; break;
2030       default:
2031         return nullptr;
2032     }
2033 
2034   switch (Op) {
2035     case BO_EQ:
2036       Out << "equal to ";
2037       break;
2038     case BO_NE:
2039       Out << "not equal to ";
2040       break;
2041     default:
2042       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2043       break;
2044   }
2045 
2046   Out << (shouldInvert ? LhsString : RhsString);
2047   const LocationContext *LCtx = N->getLocationContext();
2048   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2049   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2050   if (shouldPrune.hasValue())
2051     event->setPrunable(shouldPrune.getValue());
2052   return event;
2053 }
2054 
2055 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
2056     StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
2057     BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
2058   // FIXME: If there's already a constraint tracker for this variable,
2059   // we shouldn't emit anything here (c.f. the double note in
2060   // test/Analysis/inlining/path-notes.c)
2061   SmallString<256> buf;
2062   llvm::raw_svector_ostream Out(buf);
2063   Out << "Assuming " << LhsString << " is ";
2064 
2065   QualType Ty = CondVarExpr->getType();
2066 
2067   if (Ty->isPointerType())
2068     Out << (tookTrue ? "not null" : "null");
2069   else if (Ty->isObjCObjectPointerType())
2070     Out << (tookTrue ? "not nil" : "nil");
2071   else if (Ty->isBooleanType())
2072     Out << (tookTrue ? "true" : "false");
2073   else if (Ty->isIntegralOrEnumerationType())
2074     Out << (tookTrue ? "non-zero" : "zero");
2075   else
2076     return nullptr;
2077 
2078   const LocationContext *LCtx = N->getLocationContext();
2079   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2080   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2081 
2082   if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
2083     if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2084       const ProgramState *state = N->getState().get();
2085       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2086         if (report.isInteresting(R))
2087           event->setPrunable(false);
2088       }
2089     }
2090   }
2091 
2092   return event;
2093 }
2094 
2095 std::shared_ptr<PathDiagnosticPiece>
2096 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
2097                                   const bool tookTrue, BugReporterContext &BRC,
2098                                   BugReport &report, const ExplodedNode *N) {
2099   const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
2100   if (!VD)
2101     return nullptr;
2102 
2103   SmallString<256> Buf;
2104   llvm::raw_svector_ostream Out(Buf);
2105 
2106   Out << "Assuming '" << VD->getDeclName() << "' is ";
2107 
2108   QualType VDTy = VD->getType();
2109 
2110   if (VDTy->isPointerType())
2111     Out << (tookTrue ? "non-null" : "null");
2112   else if (VDTy->isObjCObjectPointerType())
2113     Out << (tookTrue ? "non-nil" : "nil");
2114   else if (VDTy->isScalarType())
2115     Out << (tookTrue ? "not equal to 0" : "0");
2116   else
2117     return nullptr;
2118 
2119   const LocationContext *LCtx = N->getLocationContext();
2120   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2121   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2122 
2123   const ProgramState *state = N->getState().get();
2124   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2125     if (report.isInteresting(R))
2126       event->setPrunable(false);
2127     else {
2128       SVal V = state->getSVal(R);
2129       if (report.isInteresting(V))
2130         event->setPrunable(false);
2131     }
2132   }
2133   return std::move(event);
2134 }
2135 
2136 const char *const ConditionBRVisitor::GenericTrueMessage =
2137     "Assuming the condition is true";
2138 const char *const ConditionBRVisitor::GenericFalseMessage =
2139     "Assuming the condition is false";
2140 
2141 bool ConditionBRVisitor::isPieceMessageGeneric(
2142     const PathDiagnosticPiece *Piece) {
2143   return Piece->getString() == GenericTrueMessage ||
2144          Piece->getString() == GenericFalseMessage;
2145 }
2146 
2147 std::unique_ptr<PathDiagnosticPiece>
2148 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
2149                                                     const ExplodedNode *N,
2150                                                     BugReport &BR) {
2151   // Here we suppress false positives coming from system headers. This list is
2152   // based on known issues.
2153   ExprEngine &Eng = BRC.getBugReporter().getEngine();
2154   AnalyzerOptions &Options = Eng.getAnalysisManager().options;
2155   const Decl *D = N->getLocationContext()->getDecl();
2156 
2157   if (AnalysisDeclContext::isInStdNamespace(D)) {
2158     // Skip reports within the 'std' namespace. Although these can sometimes be
2159     // the user's fault, we currently don't report them very well, and
2160     // Note that this will not help for any other data structure libraries, like
2161     // TR1, Boost, or llvm/ADT.
2162     if (Options.shouldSuppressFromCXXStandardLibrary()) {
2163       BR.markInvalid(getTag(), nullptr);
2164       return nullptr;
2165     } else {
2166       // If the complete 'std' suppression is not enabled, suppress reports
2167       // from the 'std' namespace that are known to produce false positives.
2168 
2169       // The analyzer issues a false use-after-free when std::list::pop_front
2170       // or std::list::pop_back are called multiple times because we cannot
2171       // reason about the internal invariants of the data structure.
2172       if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2173         const CXXRecordDecl *CD = MD->getParent();
2174         if (CD->getName() == "list") {
2175           BR.markInvalid(getTag(), nullptr);
2176           return nullptr;
2177         }
2178       }
2179 
2180       // The analyzer issues a false positive when the constructor of
2181       // std::__independent_bits_engine from algorithms is used.
2182       if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2183         const CXXRecordDecl *CD = MD->getParent();
2184         if (CD->getName() == "__independent_bits_engine") {
2185           BR.markInvalid(getTag(), nullptr);
2186           return nullptr;
2187         }
2188       }
2189 
2190       for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
2191            LCtx = LCtx->getParent()) {
2192         const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2193         if (!MD)
2194           continue;
2195 
2196         const CXXRecordDecl *CD = MD->getParent();
2197         // The analyzer issues a false positive on
2198         //   std::basic_string<uint8_t> v; v.push_back(1);
2199         // and
2200         //   std::u16string s; s += u'a';
2201         // because we cannot reason about the internal invariants of the
2202         // data structure.
2203         if (CD->getName() == "basic_string") {
2204           BR.markInvalid(getTag(), nullptr);
2205           return nullptr;
2206         }
2207 
2208         // The analyzer issues a false positive on
2209         //    std::shared_ptr<int> p(new int(1)); p = nullptr;
2210         // because it does not reason properly about temporary destructors.
2211         if (CD->getName() == "shared_ptr") {
2212           BR.markInvalid(getTag(), nullptr);
2213           return nullptr;
2214         }
2215       }
2216     }
2217   }
2218 
2219   // Skip reports within the sys/queue.h macros as we do not have the ability to
2220   // reason about data structure shapes.
2221   SourceManager &SM = BRC.getSourceManager();
2222   FullSourceLoc Loc = BR.getLocation(SM).asLocation();
2223   while (Loc.isMacroID()) {
2224     Loc = Loc.getSpellingLoc();
2225     if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2226       BR.markInvalid(getTag(), nullptr);
2227       return nullptr;
2228     }
2229   }
2230 
2231   return nullptr;
2232 }
2233 
2234 std::shared_ptr<PathDiagnosticPiece>
2235 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
2236                                  const ExplodedNode *PrevN,
2237                                  BugReporterContext &BRC, BugReport &BR) {
2238   ProgramStateRef State = N->getState();
2239   ProgramPoint ProgLoc = N->getLocation();
2240 
2241   // We are only interested in visiting CallEnter nodes.
2242   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2243   if (!CEnter)
2244     return nullptr;
2245 
2246   // Check if one of the arguments is the region the visitor is tracking.
2247   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2248   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2249   unsigned Idx = 0;
2250   ArrayRef<ParmVarDecl *> parms = Call->parameters();
2251 
2252   for (const auto ParamDecl : parms) {
2253     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2254     ++Idx;
2255 
2256     // Are we tracking the argument or its subregion?
2257     if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
2258       continue;
2259 
2260     // Check the function parameter type.
2261     assert(ParamDecl && "Formal parameter has no decl?");
2262     QualType T = ParamDecl->getType();
2263 
2264     if (!(T->isAnyPointerType() || T->isReferenceType())) {
2265       // Function can only change the value passed in by address.
2266       continue;
2267     }
2268 
2269     // If it is a const pointer value, the function does not intend to
2270     // change the value.
2271     if (T->getPointeeType().isConstQualified())
2272       continue;
2273 
2274     // Mark the call site (LocationContext) as interesting if the value of the
2275     // argument is undefined or '0'/'NULL'.
2276     SVal BoundVal = State->getSVal(R);
2277     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
2278       BR.markInteresting(CEnter->getCalleeContext());
2279       return nullptr;
2280     }
2281   }
2282   return nullptr;
2283 }
2284 
2285 std::shared_ptr<PathDiagnosticPiece>
2286 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
2287                                       const ExplodedNode *Pred,
2288                                       BugReporterContext &BRC, BugReport &BR) {
2289   if (Satisfied)
2290     return nullptr;
2291 
2292   const auto Edge = Succ->getLocation().getAs<BlockEdge>();
2293   if (!Edge.hasValue())
2294     return nullptr;
2295 
2296   auto Tag = Edge->getTag();
2297   if (!Tag)
2298     return nullptr;
2299 
2300   if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
2301     return nullptr;
2302 
2303   Satisfied = true;
2304 
2305   const auto *Met =
2306       dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
2307   assert(Met && "Not a C++ method.");
2308   assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
2309          "Not a copy/move assignment operator.");
2310 
2311   const auto *LCtx = Edge->getLocationContext();
2312 
2313   const auto &State = Succ->getState();
2314   auto &SVB = State->getStateManager().getSValBuilder();
2315 
2316   const auto Param =
2317       State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
2318   const auto This =
2319       State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
2320 
2321   auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
2322 
2323   if (!L.isValid() || !L.asLocation().isValid())
2324     return nullptr;
2325 
2326   SmallString<256> Buf;
2327   llvm::raw_svector_ostream Out(Buf);
2328 
2329   Out << "Assuming " << Met->getParamDecl(0)->getName() <<
2330     ((Param == This) ? " == " : " != ") << "*this";
2331 
2332   auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
2333   Piece->addRange(Met->getSourceRange());
2334 
2335   return std::move(Piece);
2336 }
2337 
2338 std::shared_ptr<PathDiagnosticPiece>
2339 TaintBugVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN,
2340                            BugReporterContext &BRC, BugReport &BR) {
2341 
2342   // Find the ExplodedNode where the taint was first introduced
2343   if (!N->getState()->isTainted(V) || PrevN->getState()->isTainted(V))
2344     return nullptr;
2345 
2346   const Stmt *S = PathDiagnosticLocation::getStmt(N);
2347   if (!S)
2348     return nullptr;
2349 
2350   const LocationContext *NCtx = N->getLocationContext();
2351   PathDiagnosticLocation L =
2352       PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
2353   if (!L.isValid() || !L.asLocation().isValid())
2354     return nullptr;
2355 
2356   return std::make_shared<PathDiagnosticEventPiece>(L, "Taint originated here");
2357 }
2358 
2359 static bool
2360 areConstraintsUnfeasible(BugReporterContext &BRC,
2361                          const llvm::SmallVector<ConstraintRangeTy, 32> &Cs) {
2362   // Create a refutation manager
2363   std::unique_ptr<ConstraintManager> RefutationMgr = CreateZ3ConstraintManager(
2364       BRC.getStateManager(), BRC.getStateManager().getOwningEngine());
2365 
2366   SMTConstraintManager *SMTRefutationMgr =
2367       static_cast<SMTConstraintManager *>(RefutationMgr.get());
2368 
2369   // Add constraints to the solver
2370   for (const auto &C : Cs)
2371     SMTRefutationMgr->addRangeConstraints(C);
2372 
2373   // And check for satisfiability
2374   return SMTRefutationMgr->isModelFeasible().isConstrainedFalse();
2375 }
2376 
2377 std::shared_ptr<PathDiagnosticPiece>
2378 FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
2379                                             const ExplodedNode *PrevN,
2380                                             BugReporterContext &BRC,
2381                                             BugReport &BR) {
2382   // Collect the constraint for the current state
2383   const ConstraintRangeTy &CR = N->getState()->get<ConstraintRange>();
2384   Constraints.push_back(CR);
2385 
2386   // If there are no predecessor, we reached the root node. In this point,
2387   // a new refutation manager will be created and the path will be checked
2388   // for reachability
2389   if (PrevN->pred_size() == 0 && areConstraintsUnfeasible(BRC, Constraints)) {
2390     BR.markInvalid("Infeasible constraints", N->getLocationContext());
2391   }
2392 
2393   return nullptr;
2394 }
2395 
2396 void FalsePositiveRefutationBRVisitor::Profile(
2397     llvm::FoldingSetNodeID &ID) const {
2398   static int Tag = 0;
2399   ID.AddPointer(&Tag);
2400 }
2401