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