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