]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
Merge ^/head r314129 through r314177.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / StaticAnalyzer / Core / BugReporterVisitors.cpp
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/BugReporterVisitor.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 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
46   // Pattern match for a few useful cases:
47   //   a[0], p->f, *p
48   const Expr *E = dyn_cast<Expr>(S);
49   if (!E)
50     return nullptr;
51   E = E->IgnoreParenCasts();
52
53   while (true) {
54     if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
55       assert(B->isAssignmentOp());
56       E = B->getLHS()->IgnoreParenCasts();
57       continue;
58     }
59     else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
60       if (U->getOpcode() == UO_Deref)
61         return U->getSubExpr()->IgnoreParenCasts();
62     }
63     else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
64       if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
65         return ME->getBase()->IgnoreParenCasts();
66       } else {
67         // If we have a member expr with a dot, the base must have been
68         // dereferenced.
69         return getDerefExpr(ME->getBase());
70       }
71     }
72     else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
73       return IvarRef->getBase()->IgnoreParenCasts();
74     }
75     else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
76       return AE->getBase();
77     }
78     else if (isDeclRefExprToReference(E)) {
79       return E;
80     }
81     break;
82   }
83
84   return nullptr;
85 }
86
87 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
88   const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
89   if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
90     return BE->getRHS();
91   return nullptr;
92 }
93
94 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
95   const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
96   if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
97     return RS->getRetValue();
98   return nullptr;
99 }
100
101 //===----------------------------------------------------------------------===//
102 // Definitions for bug reporter visitors.
103 //===----------------------------------------------------------------------===//
104
105 std::unique_ptr<PathDiagnosticPiece>
106 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
107                                const ExplodedNode *EndPathNode, BugReport &BR) {
108   return nullptr;
109 }
110
111 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
112     BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
113   PathDiagnosticLocation L =
114     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
115
116   const auto &Ranges = BR.getRanges();
117
118   // Only add the statement itself as a range if we didn't specify any
119   // special ranges for this report.
120   auto P = llvm::make_unique<PathDiagnosticEventPiece>(
121       L, BR.getDescription(), Ranges.begin() == Ranges.end());
122   for (SourceRange Range : Ranges)
123     P->addRange(Range);
124
125   return std::move(P);
126 }
127
128
129 namespace {
130 /// Emits an extra note at the return statement of an interesting stack frame.
131 ///
132 /// The returned value is marked as an interesting value, and if it's null,
133 /// adds a visitor to track where it became null.
134 ///
135 /// This visitor is intended to be used when another visitor discovers that an
136 /// interesting value comes from an inlined function call.
137 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
138   const StackFrameContext *StackFrame;
139   enum {
140     Initial,
141     MaybeUnsuppress,
142     Satisfied
143   } Mode;
144
145   bool EnableNullFPSuppression;
146
147 public:
148   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
149     : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
150
151   static void *getTag() {
152     static int Tag = 0;
153     return static_cast<void *>(&Tag);
154   }
155
156   void Profile(llvm::FoldingSetNodeID &ID) const override {
157     ID.AddPointer(ReturnVisitor::getTag());
158     ID.AddPointer(StackFrame);
159     ID.AddBoolean(EnableNullFPSuppression);
160   }
161
162   /// Adds a ReturnVisitor if the given statement represents a call that was
163   /// inlined.
164   ///
165   /// This will search back through the ExplodedGraph, starting from the given
166   /// node, looking for when the given statement was processed. If it turns out
167   /// the statement is a call that was inlined, we add the visitor to the
168   /// bug report, so it can print a note later.
169   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
170                                     BugReport &BR,
171                                     bool InEnableNullFPSuppression) {
172     if (!CallEvent::isCallStmt(S))
173       return;
174
175     // First, find when we processed the statement.
176     do {
177       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
178         if (CEE->getCalleeContext()->getCallSite() == S)
179           break;
180       if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
181         if (SP->getStmt() == S)
182           break;
183
184       Node = Node->getFirstPred();
185     } while (Node);
186
187     // Next, step over any post-statement checks.
188     while (Node && Node->getLocation().getAs<PostStmt>())
189       Node = Node->getFirstPred();
190     if (!Node)
191       return;
192
193     // Finally, see if we inlined the call.
194     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
195     if (!CEE)
196       return;
197
198     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
199     if (CalleeContext->getCallSite() != S)
200       return;
201
202     // Check the return value.
203     ProgramStateRef State = Node->getState();
204     SVal RetVal = State->getSVal(S, Node->getLocationContext());
205
206     // Handle cases where a reference is returned and then immediately used.
207     if (cast<Expr>(S)->isGLValue())
208       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
209         RetVal = State->getSVal(*LValue);
210
211     // See if the return value is NULL. If so, suppress the report.
212     SubEngine *Eng = State->getStateManager().getOwningEngine();
213     assert(Eng && "Cannot file a bug report without an owning engine");
214     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
215
216     bool EnableNullFPSuppression = false;
217     if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
218       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
219         EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
220
221     BR.markInteresting(CalleeContext);
222     BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
223                                                    EnableNullFPSuppression));
224   }
225
226   /// Returns true if any counter-suppression heuristics are enabled for
227   /// ReturnVisitor.
228   static bool hasCounterSuppression(AnalyzerOptions &Options) {
229     return Options.shouldAvoidSuppressingNullArgumentPaths();
230   }
231
232   std::shared_ptr<PathDiagnosticPiece>
233   visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
234                    BugReporterContext &BRC, BugReport &BR) {
235     // Only print a message at the interesting return statement.
236     if (N->getLocationContext() != StackFrame)
237       return nullptr;
238
239     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
240     if (!SP)
241       return nullptr;
242
243     const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
244     if (!Ret)
245       return nullptr;
246
247     // Okay, we're at the right return statement, but do we have the return
248     // value available?
249     ProgramStateRef State = N->getState();
250     SVal V = State->getSVal(Ret, StackFrame);
251     if (V.isUnknownOrUndef())
252       return nullptr;
253
254     // Don't print any more notes after this one.
255     Mode = Satisfied;
256
257     const Expr *RetE = Ret->getRetValue();
258     assert(RetE && "Tracking a return value for a void function");
259
260     // Handle cases where a reference is returned and then immediately used.
261     Optional<Loc> LValue;
262     if (RetE->isGLValue()) {
263       if ((LValue = V.getAs<Loc>())) {
264         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
265         if (RValue.getAs<DefinedSVal>())
266           V = RValue;
267       }
268     }
269
270     // Ignore aggregate rvalues.
271     if (V.getAs<nonloc::LazyCompoundVal>() ||
272         V.getAs<nonloc::CompoundVal>())
273       return nullptr;
274
275     RetE = RetE->IgnoreParenCasts();
276
277     // If we can't prove the return value is 0, just mark it interesting, and
278     // make sure to track it into any further inner functions.
279     if (!State->isNull(V).isConstrainedTrue()) {
280       BR.markInteresting(V);
281       ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
282                                            EnableNullFPSuppression);
283       return nullptr;
284     }
285
286     // If we're returning 0, we should track where that 0 came from.
287     bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
288                                        EnableNullFPSuppression);
289
290     // Build an appropriate message based on the return value.
291     SmallString<64> Msg;
292     llvm::raw_svector_ostream Out(Msg);
293
294     if (V.getAs<Loc>()) {
295       // If we have counter-suppression enabled, make sure we keep visiting
296       // future nodes. We want to emit a path note as well, in case
297       // the report is resurrected as valid later on.
298       ExprEngine &Eng = BRC.getBugReporter().getEngine();
299       AnalyzerOptions &Options = Eng.getAnalysisManager().options;
300       if (EnableNullFPSuppression && hasCounterSuppression(Options))
301         Mode = MaybeUnsuppress;
302
303       if (RetE->getType()->isObjCObjectPointerType())
304         Out << "Returning nil";
305       else
306         Out << "Returning null pointer";
307     } else {
308       Out << "Returning zero";
309     }
310
311     if (LValue) {
312       if (const MemRegion *MR = LValue->getAsRegion()) {
313         if (MR->canPrintPretty()) {
314           Out << " (reference to ";
315           MR->printPretty(Out);
316           Out << ")";
317         }
318       }
319     } else {
320       // FIXME: We should have a more generalized location printing mechanism.
321       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
322         if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
323           Out << " (loaded from '" << *DD << "')";
324     }
325
326     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
327     if (!L.isValid() || !L.asLocation().isValid())
328       return nullptr;
329
330     return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
331   }
332
333   std::shared_ptr<PathDiagnosticPiece>
334   visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
335                            BugReporterContext &BRC, BugReport &BR) {
336 #ifndef NDEBUG
337     ExprEngine &Eng = BRC.getBugReporter().getEngine();
338     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
339     assert(hasCounterSuppression(Options));
340 #endif
341
342     // Are we at the entry node for this call?
343     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
344     if (!CE)
345       return nullptr;
346
347     if (CE->getCalleeContext() != StackFrame)
348       return nullptr;
349
350     Mode = Satisfied;
351
352     // Don't automatically suppress a report if one of the arguments is
353     // known to be a null pointer. Instead, start tracking /that/ null
354     // value back to its origin.
355     ProgramStateManager &StateMgr = BRC.getStateManager();
356     CallEventManager &CallMgr = StateMgr.getCallEventManager();
357
358     ProgramStateRef State = N->getState();
359     CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
360     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
361       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
362       if (!ArgV)
363         continue;
364
365       const Expr *ArgE = Call->getArgExpr(I);
366       if (!ArgE)
367         continue;
368
369       // Is it possible for this argument to be non-null?
370       if (!State->isNull(*ArgV).isConstrainedTrue())
371         continue;
372
373       if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
374                                              EnableNullFPSuppression))
375         BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
376
377       // If we /can't/ track the null pointer, we should err on the side of
378       // false negatives, and continue towards marking this report invalid.
379       // (We will still look at the other arguments, though.)
380     }
381
382     return nullptr;
383   }
384
385   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
386                                                  const ExplodedNode *PrevN,
387                                                  BugReporterContext &BRC,
388                                                  BugReport &BR) override {
389     switch (Mode) {
390     case Initial:
391       return visitNodeInitial(N, PrevN, BRC, BR);
392     case MaybeUnsuppress:
393       return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
394     case Satisfied:
395       return nullptr;
396     }
397
398     llvm_unreachable("Invalid visit mode!");
399   }
400
401   std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
402                                                   const ExplodedNode *N,
403                                                   BugReport &BR) override {
404     if (EnableNullFPSuppression)
405       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
406     return nullptr;
407   }
408 };
409 } // end anonymous namespace
410
411
412 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
413   static int tag = 0;
414   ID.AddPointer(&tag);
415   ID.AddPointer(R);
416   ID.Add(V);
417   ID.AddBoolean(EnableNullFPSuppression);
418 }
419
420 /// Returns true if \p N represents the DeclStmt declaring and initializing
421 /// \p VR.
422 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
423   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
424   if (!P)
425     return false;
426
427   const DeclStmt *DS = P->getStmtAs<DeclStmt>();
428   if (!DS)
429     return false;
430
431   if (DS->getSingleDecl() != VR->getDecl())
432     return false;
433
434   const MemSpaceRegion *VarSpace = VR->getMemorySpace();
435   const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
436   if (!FrameSpace) {
437     // If we ever directly evaluate global DeclStmts, this assertion will be
438     // invalid, but this still seems preferable to silently accepting an
439     // initialization that may be for a path-sensitive variable.
440     assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
441     return true;
442   }
443
444   assert(VR->getDecl()->hasLocalStorage());
445   const LocationContext *LCtx = N->getLocationContext();
446   return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
447 }
448
449 std::shared_ptr<PathDiagnosticPiece>
450 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
451                                   const ExplodedNode *Pred,
452                                   BugReporterContext &BRC, BugReport &BR) {
453
454   if (Satisfied)
455     return nullptr;
456
457   const ExplodedNode *StoreSite = nullptr;
458   const Expr *InitE = nullptr;
459   bool IsParam = false;
460
461   // First see if we reached the declaration of the region.
462   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
463     if (isInitializationOfVar(Pred, VR)) {
464       StoreSite = Pred;
465       InitE = VR->getDecl()->getInit();
466     }
467   }
468
469   // If this is a post initializer expression, initializing the region, we
470   // should track the initializer expression.
471   if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
472     const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
473     if (FieldReg && FieldReg == R) {
474       StoreSite = Pred;
475       InitE = PIP->getInitializer()->getInit();
476     }
477   }
478
479   // Otherwise, see if this is the store site:
480   // (1) Succ has this binding and Pred does not, i.e. this is
481   //     where the binding first occurred.
482   // (2) Succ has this binding and is a PostStore node for this region, i.e.
483   //     the same binding was re-assigned here.
484   if (!StoreSite) {
485     if (Succ->getState()->getSVal(R) != V)
486       return nullptr;
487
488     if (Pred->getState()->getSVal(R) == V) {
489       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
490       if (!PS || PS->getLocationValue() != R)
491         return nullptr;
492     }
493
494     StoreSite = Succ;
495
496     // If this is an assignment expression, we can track the value
497     // being assigned.
498     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
499       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
500         if (BO->isAssignmentOp())
501           InitE = BO->getRHS();
502
503     // If this is a call entry, the variable should be a parameter.
504     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
505     // 'this' should never be NULL, but this visitor isn't just for NULL and
506     // UndefinedVal.)
507     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
508       if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
509         const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
510
511         ProgramStateManager &StateMgr = BRC.getStateManager();
512         CallEventManager &CallMgr = StateMgr.getCallEventManager();
513
514         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
515                                                 Succ->getState());
516         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
517         IsParam = true;
518       }
519     }
520
521     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
522     // is wrapped inside of it.
523     if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
524       InitE = TmpR->getExpr();
525   }
526
527   if (!StoreSite)
528     return nullptr;
529   Satisfied = true;
530
531   // If we have an expression that provided the value, try to track where it
532   // came from.
533   if (InitE) {
534     if (V.isUndef() ||
535         V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
536       if (!IsParam)
537         InitE = InitE->IgnoreParenCasts();
538       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
539                                          EnableNullFPSuppression);
540     } else {
541       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
542                                            BR, EnableNullFPSuppression);
543     }
544   }
545
546   // Okay, we've found the binding. Emit an appropriate message.
547   SmallString<256> sbuf;
548   llvm::raw_svector_ostream os(sbuf);
549
550   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
551     const Stmt *S = PS->getStmt();
552     const char *action = nullptr;
553     const DeclStmt *DS = dyn_cast<DeclStmt>(S);
554     const VarRegion *VR = dyn_cast<VarRegion>(R);
555
556     if (DS) {
557       action = R->canPrintPretty() ? "initialized to " :
558                                      "Initializing to ";
559     } else if (isa<BlockExpr>(S)) {
560       action = R->canPrintPretty() ? "captured by block as " :
561                                      "Captured by block as ";
562       if (VR) {
563         // See if we can get the BlockVarRegion.
564         ProgramStateRef State = StoreSite->getState();
565         SVal V = State->getSVal(S, PS->getLocationContext());
566         if (const BlockDataRegion *BDR =
567               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
568           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
569             if (Optional<KnownSVal> KV =
570                 State->getSVal(OriginalR).getAs<KnownSVal>())
571               BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
572                   *KV, OriginalR, EnableNullFPSuppression));
573           }
574         }
575       }
576     }
577
578     if (action) {
579       if (R->canPrintPretty()) {
580         R->printPretty(os);
581         os << " ";
582       }
583
584       if (V.getAs<loc::ConcreteInt>()) {
585         bool b = false;
586         if (R->isBoundable()) {
587           if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
588             if (TR->getValueType()->isObjCObjectPointerType()) {
589               os << action << "nil";
590               b = true;
591             }
592           }
593         }
594
595         if (!b)
596           os << action << "a null pointer value";
597       } else if (Optional<nonloc::ConcreteInt> CVal =
598                      V.getAs<nonloc::ConcreteInt>()) {
599         os << action << CVal->getValue();
600       }
601       else if (DS) {
602         if (V.isUndef()) {
603           if (isa<VarRegion>(R)) {
604             const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
605             if (VD->getInit()) {
606               os << (R->canPrintPretty() ? "initialized" : "Initializing")
607                  << " to a garbage value";
608             } else {
609               os << (R->canPrintPretty() ? "declared" : "Declaring")
610                  << " without an initial value";
611             }
612           }
613         }
614         else {
615           os << (R->canPrintPretty() ? "initialized" : "Initialized")
616              << " here";
617         }
618       }
619     }
620   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
621     if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
622       const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
623
624       os << "Passing ";
625
626       if (V.getAs<loc::ConcreteInt>()) {
627         if (Param->getType()->isObjCObjectPointerType())
628           os << "nil object reference";
629         else
630           os << "null pointer value";
631       } else if (V.isUndef()) {
632         os << "uninitialized value";
633       } else if (Optional<nonloc::ConcreteInt> CI =
634                      V.getAs<nonloc::ConcreteInt>()) {
635         os << "the value " << CI->getValue();
636       } else {
637         os << "value";
638       }
639
640       // Printed parameter indexes are 1-based, not 0-based.
641       unsigned Idx = Param->getFunctionScopeIndex() + 1;
642       os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
643       if (R->canPrintPretty()) {
644         os << " ";
645         R->printPretty(os);
646       }
647     }
648   }
649
650   if (os.str().empty()) {
651     if (V.getAs<loc::ConcreteInt>()) {
652       bool b = false;
653       if (R->isBoundable()) {
654         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
655           if (TR->getValueType()->isObjCObjectPointerType()) {
656             os << "nil object reference stored";
657             b = true;
658           }
659         }
660       }
661       if (!b) {
662         if (R->canPrintPretty())
663           os << "Null pointer value stored";
664         else
665           os << "Storing null pointer value";
666       }
667
668     } else if (V.isUndef()) {
669       if (R->canPrintPretty())
670         os << "Uninitialized value stored";
671       else
672         os << "Storing uninitialized value";
673
674     } else if (Optional<nonloc::ConcreteInt> CV =
675                    V.getAs<nonloc::ConcreteInt>()) {
676       if (R->canPrintPretty())
677         os << "The value " << CV->getValue() << " is assigned";
678       else
679         os << "Assigning " << CV->getValue();
680
681     } else {
682       if (R->canPrintPretty())
683         os << "Value assigned";
684       else
685         os << "Assigning value";
686     }
687
688     if (R->canPrintPretty()) {
689       os << " to ";
690       R->printPretty(os);
691     }
692   }
693
694   // Construct a new PathDiagnosticPiece.
695   ProgramPoint P = StoreSite->getLocation();
696   PathDiagnosticLocation L;
697   if (P.getAs<CallEnter>() && InitE)
698     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
699                                P.getLocationContext());
700
701   if (!L.isValid() || !L.asLocation().isValid())
702     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
703
704   if (!L.isValid() || !L.asLocation().isValid())
705     return nullptr;
706
707   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
708 }
709
710 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
711   static int tag = 0;
712   ID.AddPointer(&tag);
713   ID.AddBoolean(Assumption);
714   ID.Add(Constraint);
715 }
716
717 /// Return the tag associated with this visitor.  This tag will be used
718 /// to make all PathDiagnosticPieces created by this visitor.
719 const char *TrackConstraintBRVisitor::getTag() {
720   return "TrackConstraintBRVisitor";
721 }
722
723 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
724   if (IsZeroCheck)
725     return N->getState()->isNull(Constraint).isUnderconstrained();
726   return (bool)N->getState()->assume(Constraint, !Assumption);
727 }
728
729 std::shared_ptr<PathDiagnosticPiece>
730 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
731                                     const ExplodedNode *PrevN,
732                                     BugReporterContext &BRC, BugReport &BR) {
733   if (IsSatisfied)
734     return nullptr;
735
736   // Start tracking after we see the first state in which the value is
737   // constrained.
738   if (!IsTrackingTurnedOn)
739     if (!isUnderconstrained(N))
740       IsTrackingTurnedOn = true;
741   if (!IsTrackingTurnedOn)
742     return nullptr;
743
744   // Check if in the previous state it was feasible for this constraint
745   // to *not* be true.
746   if (isUnderconstrained(PrevN)) {
747
748     IsSatisfied = true;
749
750     // As a sanity check, make sure that the negation of the constraint
751     // was infeasible in the current state.  If it is feasible, we somehow
752     // missed the transition point.
753     assert(!isUnderconstrained(N));
754
755     // We found the transition point for the constraint.  We now need to
756     // pretty-print the constraint. (work-in-progress)
757     SmallString<64> sbuf;
758     llvm::raw_svector_ostream os(sbuf);
759
760     if (Constraint.getAs<Loc>()) {
761       os << "Assuming pointer value is ";
762       os << (Assumption ? "non-null" : "null");
763     }
764
765     if (os.str().empty())
766       return nullptr;
767
768     // Construct a new PathDiagnosticPiece.
769     ProgramPoint P = N->getLocation();
770     PathDiagnosticLocation L =
771       PathDiagnosticLocation::create(P, BRC.getSourceManager());
772     if (!L.isValid())
773       return nullptr;
774
775     auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
776     X->setTag(getTag());
777     return std::move(X);
778   }
779
780   return nullptr;
781 }
782
783 SuppressInlineDefensiveChecksVisitor::
784 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
785   : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
786
787     // Check if the visitor is disabled.
788     SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
789     assert(Eng && "Cannot file a bug report without an owning engine");
790     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
791     if (!Options.shouldSuppressInlinedDefensiveChecks())
792       IsSatisfied = true;
793
794     assert(N->getState()->isNull(V).isConstrainedTrue() &&
795            "The visitor only tracks the cases where V is constrained to 0");
796 }
797
798 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
799   static int id = 0;
800   ID.AddPointer(&id);
801   ID.Add(V);
802 }
803
804 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
805   return "IDCVisitor";
806 }
807
808 std::shared_ptr<PathDiagnosticPiece>
809 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
810                                                 const ExplodedNode *Pred,
811                                                 BugReporterContext &BRC,
812                                                 BugReport &BR) {
813   if (IsSatisfied)
814     return nullptr;
815
816   // Start tracking after we see the first state in which the value is null.
817   if (!IsTrackingTurnedOn)
818     if (Succ->getState()->isNull(V).isConstrainedTrue())
819       IsTrackingTurnedOn = true;
820   if (!IsTrackingTurnedOn)
821     return nullptr;
822
823   // Check if in the previous state it was feasible for this value
824   // to *not* be null.
825   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
826     IsSatisfied = true;
827
828     assert(Succ->getState()->isNull(V).isConstrainedTrue());
829
830     // Check if this is inlined defensive checks.
831     const LocationContext *CurLC =Succ->getLocationContext();
832     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
833     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
834       BR.markInvalid("Suppress IDC", CurLC);
835       return nullptr;
836     }
837
838     // Treat defensive checks in function-like macros as if they were an inlined
839     // defensive check. If the bug location is not in a macro and the
840     // terminator for the current location is in a macro then suppress the
841     // warning.
842     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
843
844     if (!BugPoint)
845       return nullptr;
846
847     SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
848     if (BugLoc.isMacroID())
849       return nullptr;
850
851     ProgramPoint CurPoint = Succ->getLocation();
852     const Stmt *CurTerminatorStmt = nullptr;
853     if (auto BE = CurPoint.getAs<BlockEdge>()) {
854       CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
855     } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
856       const Stmt *CurStmt = SP->getStmt();
857       if (!CurStmt->getLocStart().isMacroID())
858         return nullptr;
859
860       CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
861       CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
862     } else {
863       return nullptr;
864     }
865
866     if (!CurTerminatorStmt)
867       return nullptr;
868
869     SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
870     if (TerminatorLoc.isMacroID()) {
871       const SourceManager &SMgr = BRC.getSourceManager();
872       std::pair<FileID, unsigned> TLInfo = SMgr.getDecomposedLoc(TerminatorLoc);
873       SrcMgr::SLocEntry SE = SMgr.getSLocEntry(TLInfo.first);
874       const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
875       if (EInfo.isFunctionMacroExpansion()) {
876         BR.markInvalid("Suppress Macro IDC", CurLC);
877         return nullptr;
878       }
879     }
880   }
881   return nullptr;
882 }
883
884 static const MemRegion *getLocationRegionIfReference(const Expr *E,
885                                                      const ExplodedNode *N) {
886   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
887     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
888       if (!VD->getType()->isReferenceType())
889         return nullptr;
890       ProgramStateManager &StateMgr = N->getState()->getStateManager();
891       MemRegionManager &MRMgr = StateMgr.getRegionManager();
892       return MRMgr.getVarRegion(VD, N->getLocationContext());
893     }
894   }
895
896   // FIXME: This does not handle other kinds of null references,
897   // for example, references from FieldRegions:
898   //   struct Wrapper { int &ref; };
899   //   Wrapper w = { *(int *)0 };
900   //   w.ref = 1;
901
902   return nullptr;
903 }
904
905 static const Expr *peelOffOuterExpr(const Expr *Ex,
906                                     const ExplodedNode *N) {
907   Ex = Ex->IgnoreParenCasts();
908   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
909     return peelOffOuterExpr(EWC->getSubExpr(), N);
910   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
911     return peelOffOuterExpr(OVE->getSourceExpr(), N);
912   if (auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
913     auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
914     if (PropRef && PropRef->isMessagingGetter()) {
915       const Expr *GetterMessageSend =
916           POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
917       assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
918       return peelOffOuterExpr(GetterMessageSend, N);
919     }
920   }
921
922   // Peel off the ternary operator.
923   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
924     // Find a node where the branching occurred and find out which branch
925     // we took (true/false) by looking at the ExplodedGraph.
926     const ExplodedNode *NI = N;
927     do {
928       ProgramPoint ProgPoint = NI->getLocation();
929       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
930         const CFGBlock *srcBlk = BE->getSrc();
931         if (const Stmt *term = srcBlk->getTerminator()) {
932           if (term == CO) {
933             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
934             if (TookTrueBranch)
935               return peelOffOuterExpr(CO->getTrueExpr(), N);
936             else
937               return peelOffOuterExpr(CO->getFalseExpr(), N);
938           }
939         }
940       }
941       NI = NI->getFirstPred();
942     } while (NI);
943   }
944   return Ex;
945 }
946
947 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
948                                         const Stmt *S,
949                                         BugReport &report, bool IsArg,
950                                         bool EnableNullFPSuppression) {
951   if (!S || !N)
952     return false;
953
954   if (const Expr *Ex = dyn_cast<Expr>(S)) {
955     Ex = Ex->IgnoreParenCasts();
956     const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
957     if (Ex != PeeledEx)
958       S = PeeledEx;
959   }
960
961   const Expr *Inner = nullptr;
962   if (const Expr *Ex = dyn_cast<Expr>(S)) {
963     Ex = Ex->IgnoreParenCasts();
964     if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
965       Inner = Ex;
966   }
967
968   if (IsArg && !Inner) {
969     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
970   } else {
971     // Walk through nodes until we get one that matches the statement exactly.
972     // Alternately, if we hit a known lvalue for the statement, we know we've
973     // gone too far (though we can likely track the lvalue better anyway).
974     do {
975       const ProgramPoint &pp = N->getLocation();
976       if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
977         if (ps->getStmt() == S || ps->getStmt() == Inner)
978           break;
979       } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
980         if (CEE->getCalleeContext()->getCallSite() == S ||
981             CEE->getCalleeContext()->getCallSite() == Inner)
982           break;
983       }
984       N = N->getFirstPred();
985     } while (N);
986
987     if (!N)
988       return false;
989   }
990
991   ProgramStateRef state = N->getState();
992
993   // The message send could be nil due to the receiver being nil.
994   // At this point in the path, the receiver should be live since we are at the
995   // message send expr. If it is nil, start tracking it.
996   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
997     trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
998
999
1000   // See if the expression we're interested refers to a variable.
1001   // If so, we can track both its contents and constraints on its value.
1002   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1003     const MemRegion *R = nullptr;
1004
1005     // Find the ExplodedNode where the lvalue (the value of 'Ex')
1006     // was computed.  We need this for getting the location value.
1007     const ExplodedNode *LVNode = N;
1008     while (LVNode) {
1009       if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
1010         if (P->getStmt() == Inner)
1011           break;
1012       }
1013       LVNode = LVNode->getFirstPred();
1014     }
1015     assert(LVNode && "Unable to find the lvalue node.");
1016     ProgramStateRef LVState = LVNode->getState();
1017     SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
1018
1019     if (LVState->isNull(LVal).isConstrainedTrue()) {
1020       // In case of C++ references, we want to differentiate between a null
1021       // reference and reference to null pointer.
1022       // If the LVal is null, check if we are dealing with null reference.
1023       // For those, we want to track the location of the reference.
1024       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
1025         R = RR;
1026     } else {
1027       R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
1028
1029       // If this is a C++ reference to a null pointer, we are tracking the
1030       // pointer. In additon, we should find the store at which the reference
1031       // got initialized.
1032       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
1033         if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
1034           report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1035               *KV, RR, EnableNullFPSuppression));
1036       }
1037     }
1038
1039     if (R) {
1040       // Mark both the variable region and its contents as interesting.
1041       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1042
1043       report.markInteresting(R);
1044       report.markInteresting(V);
1045       report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1046
1047       // If the contents are symbolic, find out when they became null.
1048       if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1049         report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1050             V.castAs<DefinedSVal>(), false));
1051
1052       // Add visitor, which will suppress inline defensive checks.
1053       if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
1054         if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1055             EnableNullFPSuppression) {
1056           report.addVisitor(
1057               llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1058                                                                       LVNode));
1059         }
1060       }
1061
1062       if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1063         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1064             *KV, R, EnableNullFPSuppression));
1065       return true;
1066     }
1067   }
1068
1069   // If the expression is not an "lvalue expression", we can still
1070   // track the constraints on its contents.
1071   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1072
1073   // If the value came from an inlined function call, we should at least make
1074   // sure that function isn't pruned in our output.
1075   if (const Expr *E = dyn_cast<Expr>(S))
1076     S = E->IgnoreParenCasts();
1077
1078   ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1079
1080   // Uncomment this to find cases where we aren't properly getting the
1081   // base value that was dereferenced.
1082   // assert(!V.isUnknownOrUndef());
1083   // Is it a symbolic value?
1084   if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1085     // At this point we are dealing with the region's LValue.
1086     // However, if the rvalue is a symbolic region, we should track it as well.
1087     // Try to use the correct type when looking up the value.
1088     SVal RVal;
1089     if (const Expr *E = dyn_cast<Expr>(S))
1090       RVal = state->getRawSVal(L.getValue(), E->getType());
1091     else
1092       RVal = state->getSVal(L->getRegion());
1093
1094     const MemRegion *RegionRVal = RVal.getAsRegion();
1095     report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1096
1097     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1098       report.markInteresting(RegionRVal);
1099       report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1100           loc::MemRegionVal(RegionRVal), false));
1101     }
1102   }
1103
1104   return true;
1105 }
1106
1107 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1108                                                  const ExplodedNode *N) {
1109   const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1110   if (!ME)
1111     return nullptr;
1112   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1113     ProgramStateRef state = N->getState();
1114     SVal V = state->getSVal(Receiver, N->getLocationContext());
1115     if (state->isNull(V).isConstrainedTrue())
1116       return Receiver;
1117   }
1118   return nullptr;
1119 }
1120
1121 std::shared_ptr<PathDiagnosticPiece>
1122 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1123                                 const ExplodedNode *PrevN,
1124                                 BugReporterContext &BRC, BugReport &BR) {
1125   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1126   if (!P)
1127     return nullptr;
1128
1129   const Stmt *S = P->getStmt();
1130   const Expr *Receiver = getNilReceiver(S, N);
1131   if (!Receiver)
1132     return nullptr;
1133
1134   llvm::SmallString<256> Buf;
1135   llvm::raw_svector_ostream OS(Buf);
1136
1137   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1138     OS << "'";
1139     ME->getSelector().print(OS);
1140     OS << "' not called";
1141   }
1142   else {
1143     OS << "No method is called";
1144   }
1145   OS << " because the receiver is nil";
1146
1147   // The receiver was nil, and hence the method was skipped.
1148   // Register a BugReporterVisitor to issue a message telling us how
1149   // the receiver was null.
1150   bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1151                                      /*EnableNullFPSuppression*/ false);
1152   // Issue a message saying that the method was skipped.
1153   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1154                                      N->getLocationContext());
1155   return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1156 }
1157
1158 // Registers every VarDecl inside a Stmt with a last store visitor.
1159 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1160                                                 const Stmt *S,
1161                                                 bool EnableNullFPSuppression) {
1162   const ExplodedNode *N = BR.getErrorNode();
1163   std::deque<const Stmt *> WorkList;
1164   WorkList.push_back(S);
1165
1166   while (!WorkList.empty()) {
1167     const Stmt *Head = WorkList.front();
1168     WorkList.pop_front();
1169
1170     ProgramStateRef state = N->getState();
1171     ProgramStateManager &StateMgr = state->getStateManager();
1172
1173     if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1174       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1175         const VarRegion *R =
1176         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1177
1178         // What did we load?
1179         SVal V = state->getSVal(S, N->getLocationContext());
1180
1181         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1182           // Register a new visitor with the BugReport.
1183           BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1184               V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1185         }
1186       }
1187     }
1188
1189     for (const Stmt *SubStmt : Head->children())
1190       WorkList.push_back(SubStmt);
1191   }
1192 }
1193
1194 //===----------------------------------------------------------------------===//
1195 // Visitor that tries to report interesting diagnostics from conditions.
1196 //===----------------------------------------------------------------------===//
1197
1198 /// Return the tag associated with this visitor.  This tag will be used
1199 /// to make all PathDiagnosticPieces created by this visitor.
1200 const char *ConditionBRVisitor::getTag() {
1201   return "ConditionBRVisitor";
1202 }
1203
1204 std::shared_ptr<PathDiagnosticPiece>
1205 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1206                               BugReporterContext &BRC, BugReport &BR) {
1207   auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1208   if (piece) {
1209     piece->setTag(getTag());
1210     if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1211       ev->setPrunable(true, /* override */ false);
1212   }
1213   return piece;
1214 }
1215
1216 std::shared_ptr<PathDiagnosticPiece>
1217 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1218                                   const ExplodedNode *Prev,
1219                                   BugReporterContext &BRC, BugReport &BR) {
1220
1221   ProgramPoint progPoint = N->getLocation();
1222   ProgramStateRef CurrentState = N->getState();
1223   ProgramStateRef PrevState = Prev->getState();
1224
1225   // Compare the GDMs of the state, because that is where constraints
1226   // are managed.  Note that ensure that we only look at nodes that
1227   // were generated by the analyzer engine proper, not checkers.
1228   if (CurrentState->getGDM().getRoot() ==
1229       PrevState->getGDM().getRoot())
1230     return nullptr;
1231
1232   // If an assumption was made on a branch, it should be caught
1233   // here by looking at the state transition.
1234   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1235     const CFGBlock *srcBlk = BE->getSrc();
1236     if (const Stmt *term = srcBlk->getTerminator())
1237       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1238     return nullptr;
1239   }
1240
1241   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1242     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1243     // violation.
1244     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1245       cast<GRBugReporter>(BRC.getBugReporter()).
1246         getEngine().geteagerlyAssumeBinOpBifurcationTags();
1247
1248     const ProgramPointTag *tag = PS->getTag();
1249     if (tag == tags.first)
1250       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1251                            BRC, BR, N);
1252     if (tag == tags.second)
1253       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1254                            BRC, BR, N);
1255
1256     return nullptr;
1257   }
1258
1259   return nullptr;
1260 }
1261
1262 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1263     const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1264     const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1265   const Expr *Cond = nullptr;
1266
1267   // In the code below, Term is a CFG terminator and Cond is a branch condition
1268   // expression upon which the decision is made on this terminator.
1269   //
1270   // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1271   // and "x == 0" is the respective condition.
1272   //
1273   // Another example: in "if (x && y)", we've got two terminators and two
1274   // conditions due to short-circuit nature of operator "&&":
1275   // 1. The "if (x && y)" statement is a terminator,
1276   //    and "y" is the respective condition.
1277   // 2. Also "x && ..." is another terminator,
1278   //    and "x" is its condition.
1279
1280   switch (Term->getStmtClass()) {
1281   // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1282   // more tricky because there are more than two branches to account for.
1283   default:
1284     return nullptr;
1285   case Stmt::IfStmtClass:
1286     Cond = cast<IfStmt>(Term)->getCond();
1287     break;
1288   case Stmt::ConditionalOperatorClass:
1289     Cond = cast<ConditionalOperator>(Term)->getCond();
1290     break;
1291   case Stmt::BinaryOperatorClass:
1292     // When we encounter a logical operator (&& or ||) as a CFG terminator,
1293     // then the condition is actually its LHS; otheriwse, we'd encounter
1294     // the parent, such as if-statement, as a terminator.
1295     const auto *BO = cast<BinaryOperator>(Term);
1296     assert(BO->isLogicalOp() &&
1297            "CFG terminator is not a short-circuit operator!");
1298     Cond = BO->getLHS();
1299     break;
1300   }
1301
1302   // However, when we encounter a logical operator as a branch condition,
1303   // then the condition is actually its RHS, because LHS would be
1304   // the condition for the logical operator terminator.
1305   while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1306     if (!InnerBO->isLogicalOp())
1307       break;
1308     Cond = InnerBO->getRHS()->IgnoreParens();
1309   }
1310
1311   assert(Cond);
1312   assert(srcBlk->succ_size() == 2);
1313   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1314   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1315 }
1316
1317 std::shared_ptr<PathDiagnosticPiece>
1318 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1319                                   BugReporterContext &BRC, BugReport &R,
1320                                   const ExplodedNode *N) {
1321   // These will be modified in code below, but we need to preserve the original
1322   //  values in case we want to throw the generic message.
1323   const Expr *CondTmp = Cond;
1324   bool tookTrueTmp = tookTrue;
1325
1326   while (true) {
1327     CondTmp = CondTmp->IgnoreParenCasts();
1328     switch (CondTmp->getStmtClass()) {
1329       default:
1330         break;
1331       case Stmt::BinaryOperatorClass:
1332         if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1333                                    tookTrueTmp, BRC, R, N))
1334           return P;
1335         break;
1336       case Stmt::DeclRefExprClass:
1337         if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1338                                    tookTrueTmp, BRC, R, N))
1339           return P;
1340         break;
1341       case Stmt::UnaryOperatorClass: {
1342         const UnaryOperator *UO = cast<UnaryOperator>(CondTmp);
1343         if (UO->getOpcode() == UO_LNot) {
1344           tookTrueTmp = !tookTrueTmp;
1345           CondTmp = UO->getSubExpr();
1346           continue;
1347         }
1348         break;
1349       }
1350     }
1351     break;
1352   }
1353
1354   // Condition too complex to explain? Just say something so that the user
1355   // knew we've made some path decision at this point.
1356   const LocationContext *LCtx = N->getLocationContext();
1357   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1358   if (!Loc.isValid() || !Loc.asLocation().isValid())
1359     return nullptr;
1360
1361   return std::make_shared<PathDiagnosticEventPiece>(
1362       Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1363 }
1364
1365 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1366                                       const Expr *ParentEx,
1367                                       raw_ostream &Out,
1368                                       BugReporterContext &BRC,
1369                                       BugReport &report,
1370                                       const ExplodedNode *N,
1371                                       Optional<bool> &prunable) {
1372   const Expr *OriginalExpr = Ex;
1373   Ex = Ex->IgnoreParenCasts();
1374
1375   // Use heuristics to determine if Ex is a macro expending to a literal and
1376   // if so, use the macro's name.
1377   SourceLocation LocStart = Ex->getLocStart();
1378   SourceLocation LocEnd = Ex->getLocEnd();
1379   if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1380       (isa<GNUNullExpr>(Ex) ||
1381        isa<ObjCBoolLiteralExpr>(Ex) ||
1382        isa<CXXBoolLiteralExpr>(Ex) ||
1383        isa<IntegerLiteral>(Ex) ||
1384        isa<FloatingLiteral>(Ex))) {
1385
1386     StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1387       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1388     StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1389       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1390     bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1391
1392     bool partOfParentMacro = false;
1393     if (ParentEx->getLocStart().isMacroID()) {
1394       StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1395         ParentEx->getLocStart(), BRC.getSourceManager(),
1396         BRC.getASTContext().getLangOpts());
1397       partOfParentMacro = PName.equals(StartName);
1398     }
1399
1400     if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1401       // Get the location of the macro name as written by the caller.
1402       SourceLocation Loc = LocStart;
1403       while (LocStart.isMacroID()) {
1404         Loc = LocStart;
1405         LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1406       }
1407       StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1408         Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1409
1410       // Return the macro name.
1411       Out << MacroName;
1412       return false;
1413     }
1414   }
1415
1416   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1417     const bool quotes = isa<VarDecl>(DR->getDecl());
1418     if (quotes) {
1419       Out << '\'';
1420       const LocationContext *LCtx = N->getLocationContext();
1421       const ProgramState *state = N->getState().get();
1422       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1423                                                 LCtx).getAsRegion()) {
1424         if (report.isInteresting(R))
1425           prunable = false;
1426         else {
1427           const ProgramState *state = N->getState().get();
1428           SVal V = state->getSVal(R);
1429           if (report.isInteresting(V))
1430             prunable = false;
1431         }
1432       }
1433     }
1434     Out << DR->getDecl()->getDeclName().getAsString();
1435     if (quotes)
1436       Out << '\'';
1437     return quotes;
1438   }
1439
1440   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1441     QualType OriginalTy = OriginalExpr->getType();
1442     if (OriginalTy->isPointerType()) {
1443       if (IL->getValue() == 0) {
1444         Out << "null";
1445         return false;
1446       }
1447     }
1448     else if (OriginalTy->isObjCObjectPointerType()) {
1449       if (IL->getValue() == 0) {
1450         Out << "nil";
1451         return false;
1452       }
1453     }
1454
1455     Out << IL->getValue();
1456     return false;
1457   }
1458
1459   return false;
1460 }
1461
1462 std::shared_ptr<PathDiagnosticPiece>
1463 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
1464                                   const bool tookTrue, BugReporterContext &BRC,
1465                                   BugReport &R, const ExplodedNode *N) {
1466
1467   bool shouldInvert = false;
1468   Optional<bool> shouldPrune;
1469
1470   SmallString<128> LhsString, RhsString;
1471   {
1472     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1473     const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
1474                                        BRC, R, N, shouldPrune);
1475     const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
1476                                        BRC, R, N, shouldPrune);
1477
1478     shouldInvert = !isVarLHS && isVarRHS;
1479   }
1480
1481   BinaryOperator::Opcode Op = BExpr->getOpcode();
1482
1483   if (BinaryOperator::isAssignmentOp(Op)) {
1484     // For assignment operators, all that we care about is that the LHS
1485     // evaluates to "true" or "false".
1486     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1487                                   BRC, R, N);
1488   }
1489
1490   // For non-assignment operations, we require that we can understand
1491   // both the LHS and RHS.
1492   if (LhsString.empty() || RhsString.empty() ||
1493       !BinaryOperator::isComparisonOp(Op))
1494     return nullptr;
1495
1496   // Should we invert the strings if the LHS is not a variable name?
1497   SmallString<256> buf;
1498   llvm::raw_svector_ostream Out(buf);
1499   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1500
1501   // Do we need to invert the opcode?
1502   if (shouldInvert)
1503     switch (Op) {
1504       default: break;
1505       case BO_LT: Op = BO_GT; break;
1506       case BO_GT: Op = BO_LT; break;
1507       case BO_LE: Op = BO_GE; break;
1508       case BO_GE: Op = BO_LE; break;
1509     }
1510
1511   if (!tookTrue)
1512     switch (Op) {
1513       case BO_EQ: Op = BO_NE; break;
1514       case BO_NE: Op = BO_EQ; break;
1515       case BO_LT: Op = BO_GE; break;
1516       case BO_GT: Op = BO_LE; break;
1517       case BO_LE: Op = BO_GT; break;
1518       case BO_GE: Op = BO_LT; break;
1519       default:
1520         return nullptr;
1521     }
1522
1523   switch (Op) {
1524     case BO_EQ:
1525       Out << "equal to ";
1526       break;
1527     case BO_NE:
1528       Out << "not equal to ";
1529       break;
1530     default:
1531       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1532       break;
1533   }
1534
1535   Out << (shouldInvert ? LhsString : RhsString);
1536   const LocationContext *LCtx = N->getLocationContext();
1537   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1538   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1539   if (shouldPrune.hasValue())
1540     event->setPrunable(shouldPrune.getValue());
1541   return event;
1542 }
1543
1544 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
1545     StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
1546     BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
1547   // FIXME: If there's already a constraint tracker for this variable,
1548   // we shouldn't emit anything here (c.f. the double note in
1549   // test/Analysis/inlining/path-notes.c)
1550   SmallString<256> buf;
1551   llvm::raw_svector_ostream Out(buf);
1552   Out << "Assuming " << LhsString << " is ";
1553
1554   QualType Ty = CondVarExpr->getType();
1555
1556   if (Ty->isPointerType())
1557     Out << (tookTrue ? "not null" : "null");
1558   else if (Ty->isObjCObjectPointerType())
1559     Out << (tookTrue ? "not nil" : "nil");
1560   else if (Ty->isBooleanType())
1561     Out << (tookTrue ? "true" : "false");
1562   else if (Ty->isIntegralOrEnumerationType())
1563     Out << (tookTrue ? "non-zero" : "zero");
1564   else
1565     return nullptr;
1566
1567   const LocationContext *LCtx = N->getLocationContext();
1568   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1569   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1570
1571   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1572     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1573       const ProgramState *state = N->getState().get();
1574       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1575         if (report.isInteresting(R))
1576           event->setPrunable(false);
1577       }
1578     }
1579   }
1580
1581   return event;
1582 }
1583
1584 std::shared_ptr<PathDiagnosticPiece>
1585 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
1586                                   const bool tookTrue, BugReporterContext &BRC,
1587                                   BugReport &report, const ExplodedNode *N) {
1588
1589   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1590   if (!VD)
1591     return nullptr;
1592
1593   SmallString<256> Buf;
1594   llvm::raw_svector_ostream Out(Buf);
1595
1596   Out << "Assuming '" << VD->getDeclName() << "' is ";
1597
1598   QualType VDTy = VD->getType();
1599
1600   if (VDTy->isPointerType())
1601     Out << (tookTrue ? "non-null" : "null");
1602   else if (VDTy->isObjCObjectPointerType())
1603     Out << (tookTrue ? "non-nil" : "nil");
1604   else if (VDTy->isScalarType())
1605     Out << (tookTrue ? "not equal to 0" : "0");
1606   else
1607     return nullptr;
1608
1609   const LocationContext *LCtx = N->getLocationContext();
1610   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1611   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1612
1613   const ProgramState *state = N->getState().get();
1614   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1615     if (report.isInteresting(R))
1616       event->setPrunable(false);
1617     else {
1618       SVal V = state->getSVal(R);
1619       if (report.isInteresting(V))
1620         event->setPrunable(false);
1621     }
1622   }
1623   return std::move(event);
1624 }
1625
1626 const char *const ConditionBRVisitor::GenericTrueMessage =
1627     "Assuming the condition is true";
1628 const char *const ConditionBRVisitor::GenericFalseMessage =
1629     "Assuming the condition is false";
1630
1631 bool ConditionBRVisitor::isPieceMessageGeneric(
1632     const PathDiagnosticPiece *Piece) {
1633   return Piece->getString() == GenericTrueMessage ||
1634          Piece->getString() == GenericFalseMessage;
1635 }
1636
1637 std::unique_ptr<PathDiagnosticPiece>
1638 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1639                                                     const ExplodedNode *N,
1640                                                     BugReport &BR) {
1641   // Here we suppress false positives coming from system headers. This list is
1642   // based on known issues.
1643   ExprEngine &Eng = BRC.getBugReporter().getEngine();
1644   AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1645   const Decl *D = N->getLocationContext()->getDecl();
1646
1647   if (AnalysisDeclContext::isInStdNamespace(D)) {
1648     // Skip reports within the 'std' namespace. Although these can sometimes be
1649     // the user's fault, we currently don't report them very well, and
1650     // Note that this will not help for any other data structure libraries, like
1651     // TR1, Boost, or llvm/ADT.
1652     if (Options.shouldSuppressFromCXXStandardLibrary()) {
1653       BR.markInvalid(getTag(), nullptr);
1654       return nullptr;
1655
1656     } else {
1657       // If the complete 'std' suppression is not enabled, suppress reports
1658       // from the 'std' namespace that are known to produce false positives.
1659
1660       // The analyzer issues a false use-after-free when std::list::pop_front
1661       // or std::list::pop_back are called multiple times because we cannot
1662       // reason about the internal invariants of the datastructure.
1663       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1664         const CXXRecordDecl *CD = MD->getParent();
1665         if (CD->getName() == "list") {
1666           BR.markInvalid(getTag(), nullptr);
1667           return nullptr;
1668         }
1669       }
1670
1671       // The analyzer issues a false positive when the constructor of
1672       // std::__independent_bits_engine from algorithms is used.
1673       if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) {
1674         const CXXRecordDecl *CD = MD->getParent();
1675         if (CD->getName() == "__independent_bits_engine") {
1676           BR.markInvalid(getTag(), nullptr);
1677           return nullptr;
1678         }
1679       }
1680
1681       for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
1682            LCtx = LCtx->getParent()) {
1683         const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1684         if (!MD)
1685           continue;
1686
1687         const CXXRecordDecl *CD = MD->getParent();
1688         // The analyzer issues a false positive on
1689         //   std::basic_string<uint8_t> v; v.push_back(1);
1690         // and
1691         //   std::u16string s; s += u'a';
1692         // because we cannot reason about the internal invariants of the
1693         // datastructure.
1694         if (CD->getName() == "basic_string") {
1695           BR.markInvalid(getTag(), nullptr);
1696           return nullptr;
1697         }
1698
1699         // The analyzer issues a false positive on
1700         //    std::shared_ptr<int> p(new int(1)); p = nullptr;
1701         // because it does not reason properly about temporary destructors.
1702         if (CD->getName() == "shared_ptr") {
1703           BR.markInvalid(getTag(), nullptr);
1704           return nullptr;
1705         }
1706       }
1707     }
1708   }
1709
1710   // Skip reports within the sys/queue.h macros as we do not have the ability to
1711   // reason about data structure shapes.
1712   SourceManager &SM = BRC.getSourceManager();
1713   FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1714   while (Loc.isMacroID()) {
1715     Loc = Loc.getSpellingLoc();
1716     if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1717       BR.markInvalid(getTag(), nullptr);
1718       return nullptr;
1719     }
1720   }
1721
1722   return nullptr;
1723 }
1724
1725 std::shared_ptr<PathDiagnosticPiece>
1726 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1727                                  const ExplodedNode *PrevN,
1728                                  BugReporterContext &BRC, BugReport &BR) {
1729
1730   ProgramStateRef State = N->getState();
1731   ProgramPoint ProgLoc = N->getLocation();
1732
1733   // We are only interested in visiting CallEnter nodes.
1734   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1735   if (!CEnter)
1736     return nullptr;
1737
1738   // Check if one of the arguments is the region the visitor is tracking.
1739   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1740   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1741   unsigned Idx = 0;
1742   ArrayRef<ParmVarDecl*> parms = Call->parameters();
1743
1744   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1745                               I != E; ++I, ++Idx) {
1746     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1747
1748     // Are we tracking the argument or its subregion?
1749     if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1750       continue;
1751
1752     // Check the function parameter type.
1753     const ParmVarDecl *ParamDecl = *I;
1754     assert(ParamDecl && "Formal parameter has no decl?");
1755     QualType T = ParamDecl->getType();
1756
1757     if (!(T->isAnyPointerType() || T->isReferenceType())) {
1758       // Function can only change the value passed in by address.
1759       continue;
1760     }
1761
1762     // If it is a const pointer value, the function does not intend to
1763     // change the value.
1764     if (T->getPointeeType().isConstQualified())
1765       continue;
1766
1767     // Mark the call site (LocationContext) as interesting if the value of the
1768     // argument is undefined or '0'/'NULL'.
1769     SVal BoundVal = State->getSVal(R);
1770     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1771       BR.markInteresting(CEnter->getCalleeContext());
1772       return nullptr;
1773     }
1774   }
1775   return nullptr;
1776 }
1777
1778 std::shared_ptr<PathDiagnosticPiece>
1779 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
1780                                       const ExplodedNode *Pred,
1781                                       BugReporterContext &BRC, BugReport &BR) {
1782   if (Satisfied)
1783     return nullptr;
1784
1785   auto Edge = Succ->getLocation().getAs<BlockEdge>();
1786   if (!Edge.hasValue())
1787     return nullptr;
1788
1789   auto Tag = Edge->getTag();
1790   if (!Tag)
1791     return nullptr;
1792
1793   if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
1794     return nullptr;
1795
1796   Satisfied = true;
1797
1798   const auto *Met =
1799       dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
1800   assert(Met && "Not a C++ method.");
1801   assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
1802          "Not a copy/move assignment operator.");
1803
1804   const auto *LCtx = Edge->getLocationContext();
1805
1806   const auto &State = Succ->getState();
1807   auto &SVB = State->getStateManager().getSValBuilder();
1808
1809   const auto Param =
1810       State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
1811   const auto This =
1812       State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
1813
1814   auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
1815
1816   if (!L.isValid() || !L.asLocation().isValid())
1817     return nullptr;
1818
1819   SmallString<256> Buf;
1820   llvm::raw_svector_ostream Out(Buf);
1821
1822   Out << "Assuming " << Met->getParamDecl(0)->getName() <<
1823     ((Param == This) ? " == " : " != ") << "*this";
1824
1825   auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1826   Piece->addRange(Met->getSourceRange());
1827
1828   return std::move(Piece);
1829 }