BugReporterVisitors.cpp revision dc9c160dede7e2f5cc11755db6aaa57e7fccbcec
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- C++ -*--//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
10eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch//  This file defines a set of BugReporter "visitors" which can be used to
11eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch//  enhance the diagnostics reported for a bug.
12eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch//
13eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch//===----------------------------------------------------------------------===//
14eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
15eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "clang/AST/Expr.h"
16cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "clang/AST/ExprObjC.h"
17116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/SmallString.h"
245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/StringExtras.h"
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/raw_ostream.h"
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang;
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace ento;
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using llvm::FoldingSetNodeID;
314e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Utility functions.
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
35c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)bool bugreporter::isDeclRefExprToReference(const Expr *E) {
37eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
38eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return DRE->getDecl()->getType()->isReferenceType();
39eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
40eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  return false;
41eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
42eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)const Expr *bugreporter::getDerefExpr(const Stmt *S) {
445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Pattern match for a few useful cases (do something smarter later):
455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //   a[0], p->f, *p
465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const Expr *E = dyn_cast<Expr>(S);
47eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (!E)
48eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return 0;
49eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  E = E->IgnoreParenCasts();
50eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
51eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  while (true) {
52eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
53eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      assert(B->isAssignmentOp());
54eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      E = B->getLHS()->IgnoreParenCasts();
55eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      continue;
56eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
57eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
58eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (U->getOpcode() == UO_Deref)
59eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        return U->getSubExpr()->IgnoreParenCasts();
60eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
61eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
62eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
63eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch        return ME->getBase()->IgnoreParenCasts();
64eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      }
65eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
66eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
67eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      return IvarRef->getBase()->IgnoreParenCasts();
68eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
69eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
70eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      return AE->getBase();
71eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
72eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    break;
73eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
74eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
75eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  return NULL;
76eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
77eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
78eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochconst Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
79eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
80eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
81eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return BE->getRHS();
82eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  return NULL;
835d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
845d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
85eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochconst Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
86eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
87eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
88eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return RS->getRetValue();
894e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  return NULL;
90eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
91eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
92eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch//===----------------------------------------------------------------------===//
93eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch// Definitions for bug reporter visitors.
94eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch//===----------------------------------------------------------------------===//
95eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
96eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen MurdochPathDiagnosticPiece*
97eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen MurdochBugReporterVisitor::getEndPath(BugReporterContext &BRC,
98eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                               const ExplodedNode *EndPathNode,
99eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                               BugReport &BR) {
100eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  return 0;
101eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
102eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
103eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen MurdochPathDiagnosticPiece*
104eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen MurdochBugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
105eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                                      const ExplodedNode *EndPathNode,
106eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                                      BugReport &BR) {
107eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  PathDiagnosticLocation L =
108eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
109eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
110eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  BugReport::ranges_iterator Beg, End;
111eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  llvm::tie(Beg, End) = BR.getRanges();
112eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
113eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // Only add the statement itself as a range if we didn't specify any
114eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // special ranges for this report.
115eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
116eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      BR.getDescription(),
117eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      Beg == End);
118eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  for (; Beg != End; ++Beg)
119eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    P->addRange(*Beg);
120eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
121eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  return P;
122eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch}
123eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
124eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
125eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochnamespace {
126eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch/// Emits an extra note at the return statement of an interesting stack frame.
127eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch///
128eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch/// The returned value is marked as an interesting value, and if it's null,
129eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch/// adds a visitor to track where it became null.
130eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch///
131eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch/// This visitor is intended to be used when another visitor discovers that an
1324e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)/// interesting value comes from an inlined function call.
1334e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
1344e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  const StackFrameContext *StackFrame;
1354e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  enum {
136eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Initial,
137eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    MaybeUnsuppress,
138eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Satisfied
139eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  } Mode;
140eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  bool InitiallySuppressed;
141eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
142eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochpublic:
143eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
1445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    : StackFrame(Frame), Mode(Initial), InitiallySuppressed(Suppressed) {}
1455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  static void *getTag() {
1475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    static int Tag = 0;
1485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return static_cast<void *>(&Tag);
149a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)  }
1505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  virtual void Profile(llvm::FoldingSetNodeID &ID) const {
1525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ID.AddPointer(ReturnVisitor::getTag());
1535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ID.AddPointer(StackFrame);
1545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ID.AddBoolean(InitiallySuppressed);
1555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
1565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1574e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  /// Adds a ReturnVisitor if the given statement represents a call that was
1584e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  /// inlined.
1594e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  ///
1605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// This will search back through the ExplodedGraph, starting from the given
1615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// node, looking for when the given statement was processed. If it turns out
1625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// the statement is a call that was inlined, we add the visitor to the
1635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// bug report, so it can print a note later.
164  static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
165                                    BugReport &BR) {
166    if (!CallEvent::isCallStmt(S))
167      return;
168
169    // First, find when we processed the statement.
170    do {
171      if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
172        if (CEE->getCalleeContext()->getCallSite() == S)
173          break;
174      if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
175        if (SP->getStmt() == S)
176          break;
177
178      Node = Node->getFirstPred();
179    } while (Node);
180
181    // Next, step over any post-statement checks.
182    while (Node && Node->getLocation().getAs<PostStmt>())
183      Node = Node->getFirstPred();
184    if (!Node)
185      return;
186
187    // Finally, see if we inlined the call.
188    Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
189    if (!CEE)
190      return;
191
192    const StackFrameContext *CalleeContext = CEE->getCalleeContext();
193    if (CalleeContext->getCallSite() != S)
194      return;
195
196    // Check the return value.
197    ProgramStateRef State = Node->getState();
198    SVal RetVal = State->getSVal(S, Node->getLocationContext());
199
200    // Handle cases where a reference is returned and then immediately used.
201    if (cast<Expr>(S)->isGLValue())
202      if (Optional<Loc> LValue = RetVal.getAs<Loc>())
203        RetVal = State->getSVal(*LValue);
204
205    // See if the return value is NULL. If so, suppress the report.
206    SubEngine *Eng = State->getStateManager().getOwningEngine();
207    assert(Eng && "Cannot file a bug report without an owning engine");
208    AnalyzerOptions &Options = Eng->getAnalysisManager().options;
209
210    bool InitiallySuppressed = false;
211    if (Options.shouldSuppressNullReturnPaths())
212      if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
213        InitiallySuppressed = !State->assume(*RetLoc, true);
214
215    BR.markInteresting(CalleeContext);
216    BR.addVisitor(new ReturnVisitor(CalleeContext, InitiallySuppressed));
217  }
218
219  /// Returns true if any counter-suppression heuristics are enabled for
220  /// ReturnVisitor.
221  static bool hasCounterSuppression(AnalyzerOptions &Options) {
222    return Options.shouldAvoidSuppressingNullArgumentPaths();
223  }
224
225  PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
226                                        const ExplodedNode *PrevN,
227                                        BugReporterContext &BRC,
228                                        BugReport &BR) {
229    // Only print a message at the interesting return statement.
230    if (N->getLocationContext() != StackFrame)
231      return 0;
232
233    Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
234    if (!SP)
235      return 0;
236
237    const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
238    if (!Ret)
239      return 0;
240
241    // Okay, we're at the right return statement, but do we have the return
242    // value available?
243    ProgramStateRef State = N->getState();
244    SVal V = State->getSVal(Ret, StackFrame);
245    if (V.isUnknownOrUndef())
246      return 0;
247
248    // Don't print any more notes after this one.
249    Mode = Satisfied;
250
251    const Expr *RetE = Ret->getRetValue();
252    assert(RetE && "Tracking a return value for a void function");
253
254    // Handle cases where a reference is returned and then immediately used.
255    Optional<Loc> LValue;
256    if (RetE->isGLValue()) {
257      if ((LValue = V.getAs<Loc>())) {
258        SVal RValue = State->getRawSVal(*LValue, RetE->getType());
259        if (RValue.getAs<DefinedSVal>())
260          V = RValue;
261      }
262    }
263
264    // Ignore aggregate rvalues.
265    if (V.getAs<nonloc::LazyCompoundVal>() ||
266        V.getAs<nonloc::CompoundVal>())
267      return 0;
268
269    RetE = RetE->IgnoreParenCasts();
270
271    // If we can't prove the return value is 0, just mark it interesting, and
272    // make sure to track it into any further inner functions.
273    if (State->assume(V.castAs<DefinedSVal>(), true)) {
274      BR.markInteresting(V);
275      ReturnVisitor::addVisitorIfNecessary(N, RetE, BR);
276      return 0;
277    }
278
279    // If we're returning 0, we should track where that 0 came from.
280    bugreporter::trackNullOrUndefValue(N, RetE, BR);
281
282    // Build an appropriate message based on the return value.
283    SmallString<64> Msg;
284    llvm::raw_svector_ostream Out(Msg);
285
286    if (V.getAs<Loc>()) {
287      // If we have counter-suppression enabled, make sure we keep visiting
288      // future nodes. We want to emit a path note as well, in case
289      // the report is resurrected as valid later on.
290      ExprEngine &Eng = BRC.getBugReporter().getEngine();
291      AnalyzerOptions &Options = Eng.getAnalysisManager().options;
292      if (InitiallySuppressed && hasCounterSuppression(Options))
293        Mode = MaybeUnsuppress;
294
295      if (RetE->getType()->isObjCObjectPointerType())
296        Out << "Returning nil";
297      else
298        Out << "Returning null pointer";
299    } else {
300      Out << "Returning zero";
301    }
302
303    if (LValue) {
304      if (const MemRegion *MR = LValue->getAsRegion()) {
305        if (MR->canPrintPretty()) {
306          Out << " (reference to '";
307          MR->printPretty(Out);
308          Out << "')";
309        }
310      }
311    } else {
312      // FIXME: We should have a more generalized location printing mechanism.
313      if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
314        if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
315          Out << " (loaded from '" << *DD << "')";
316    }
317
318    PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
319    return new PathDiagnosticEventPiece(L, Out.str());
320  }
321
322  PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
323                                                const ExplodedNode *PrevN,
324                                                BugReporterContext &BRC,
325                                                BugReport &BR) {
326#ifndef NDEBUG
327    ExprEngine &Eng = BRC.getBugReporter().getEngine();
328    AnalyzerOptions &Options = Eng.getAnalysisManager().options;
329    assert(hasCounterSuppression(Options));
330#endif
331
332    // Are we at the entry node for this call?
333    Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
334    if (!CE)
335      return 0;
336
337    if (CE->getCalleeContext() != StackFrame)
338      return 0;
339
340    Mode = Satisfied;
341
342    // Don't automatically suppress a report if one of the arguments is
343    // known to be a null pointer. Instead, start tracking /that/ null
344    // value back to its origin.
345    ProgramStateManager &StateMgr = BRC.getStateManager();
346    CallEventManager &CallMgr = StateMgr.getCallEventManager();
347
348    ProgramStateRef State = N->getState();
349    CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
350    for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
351      Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
352      if (!ArgV)
353        continue;
354
355      const Expr *ArgE = Call->getArgExpr(I);
356      if (!ArgE)
357        continue;
358
359      // Is it possible for this argument to be non-null?
360      if (State->assume(*ArgV, true))
361        continue;
362
363      if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true))
364        BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
365
366      // If we /can't/ track the null pointer, we should err on the side of
367      // false negatives, and continue towards marking this report invalid.
368      // (We will still look at the other arguments, though.)
369    }
370
371    return 0;
372  }
373
374  PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
375                                 const ExplodedNode *PrevN,
376                                 BugReporterContext &BRC,
377                                 BugReport &BR) {
378    switch (Mode) {
379    case Initial:
380      return visitNodeInitial(N, PrevN, BRC, BR);
381    case MaybeUnsuppress:
382      return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
383    case Satisfied:
384      return 0;
385    }
386
387    llvm_unreachable("Invalid visit mode!");
388  }
389
390  PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
391                                  const ExplodedNode *N,
392                                  BugReport &BR) {
393    if (InitiallySuppressed)
394      BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
395    return 0;
396  }
397};
398} // end anonymous namespace
399
400
401void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
402  static int tag = 0;
403  ID.AddPointer(&tag);
404  ID.AddPointer(R);
405  ID.Add(V);
406}
407
408PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
409                                                       const ExplodedNode *Pred,
410                                                       BugReporterContext &BRC,
411                                                       BugReport &BR) {
412
413  if (Satisfied)
414    return NULL;
415
416  const ExplodedNode *StoreSite = 0;
417  const Expr *InitE = 0;
418  bool IsParam = false;
419
420  // First see if we reached the declaration of the region.
421  if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
422    if (Optional<PostStmt> P = Pred->getLocationAs<PostStmt>()) {
423      if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
424        if (DS->getSingleDecl() == VR->getDecl()) {
425          StoreSite = Pred;
426          InitE = VR->getDecl()->getInit();
427        }
428      }
429    }
430  }
431
432  // Otherwise, see if this is the store site:
433  // (1) Succ has this binding and Pred does not, i.e. this is
434  //     where the binding first occurred.
435  // (2) Succ has this binding and is a PostStore node for this region, i.e.
436  //     the same binding was re-assigned here.
437  if (!StoreSite) {
438    if (Succ->getState()->getSVal(R) != V)
439      return NULL;
440
441    if (Pred->getState()->getSVal(R) == V) {
442      Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
443      if (!PS || PS->getLocationValue() != R)
444        return NULL;
445    }
446
447    StoreSite = Succ;
448
449    // If this is an assignment expression, we can track the value
450    // being assigned.
451    if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
452      if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
453        if (BO->isAssignmentOp())
454          InitE = BO->getRHS();
455
456    // If this is a call entry, the variable should be a parameter.
457    // FIXME: Handle CXXThisRegion as well. (This is not a priority because
458    // 'this' should never be NULL, but this visitor isn't just for NULL and
459    // UndefinedVal.)
460    if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
461      if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
462        const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
463
464        ProgramStateManager &StateMgr = BRC.getStateManager();
465        CallEventManager &CallMgr = StateMgr.getCallEventManager();
466
467        CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
468                                                Succ->getState());
469        InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
470        IsParam = true;
471      }
472    }
473
474    // If this is a CXXTempObjectRegion, the Expr responsible for its creation
475    // is wrapped inside of it.
476    if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
477      InitE = TmpR->getExpr();
478  }
479
480  if (!StoreSite)
481    return NULL;
482  Satisfied = true;
483
484  // If we have an expression that provided the value, try to track where it
485  // came from.
486  if (InitE) {
487    if (V.isUndef() || V.getAs<loc::ConcreteInt>()) {
488      if (!IsParam)
489        InitE = InitE->IgnoreParenCasts();
490      bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam);
491    } else {
492      ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
493                                           BR);
494    }
495  }
496
497  if (!R->canPrintPretty())
498    return 0;
499
500  // Okay, we've found the binding. Emit an appropriate message.
501  SmallString<256> sbuf;
502  llvm::raw_svector_ostream os(sbuf);
503
504  if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
505    const Stmt *S = PS->getStmt();
506    const char *action = 0;
507    const DeclStmt *DS = dyn_cast<DeclStmt>(S);
508    const VarRegion *VR = dyn_cast<VarRegion>(R);
509
510    if (DS) {
511      action = "initialized to ";
512    } else if (isa<BlockExpr>(S)) {
513      action = "captured by block as ";
514      if (VR) {
515        // See if we can get the BlockVarRegion.
516        ProgramStateRef State = StoreSite->getState();
517        SVal V = State->getSVal(S, PS->getLocationContext());
518        if (const BlockDataRegion *BDR =
519              dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
520          if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
521            if (Optional<KnownSVal> KV =
522                State->getSVal(OriginalR).getAs<KnownSVal>())
523              BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR));
524          }
525        }
526      }
527    }
528
529    if (action) {
530      if (!R)
531        return 0;
532
533      os << '\'';
534      R->printPretty(os);
535      os << "' ";
536
537      if (V.getAs<loc::ConcreteInt>()) {
538        bool b = false;
539        if (R->isBoundable()) {
540          if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
541            if (TR->getValueType()->isObjCObjectPointerType()) {
542              os << action << "nil";
543              b = true;
544            }
545          }
546        }
547
548        if (!b)
549          os << action << "a null pointer value";
550      } else if (Optional<nonloc::ConcreteInt> CVal =
551                     V.getAs<nonloc::ConcreteInt>()) {
552        os << action << CVal->getValue();
553      }
554      else if (DS) {
555        if (V.isUndef()) {
556          if (isa<VarRegion>(R)) {
557            const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
558            if (VD->getInit())
559              os << "initialized to a garbage value";
560            else
561              os << "declared without an initial value";
562          }
563        }
564        else {
565          os << "initialized here";
566        }
567      }
568    }
569  } else if (StoreSite->getLocation().getAs<CallEnter>()) {
570    if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
571      const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
572
573      os << "Passing ";
574
575      if (V.getAs<loc::ConcreteInt>()) {
576        if (Param->getType()->isObjCObjectPointerType())
577          os << "nil object reference";
578        else
579          os << "null pointer value";
580      } else if (V.isUndef()) {
581        os << "uninitialized value";
582      } else if (Optional<nonloc::ConcreteInt> CI =
583                     V.getAs<nonloc::ConcreteInt>()) {
584        os << "the value " << CI->getValue();
585      } else {
586        os << "value";
587      }
588
589      // Printed parameter indexes are 1-based, not 0-based.
590      unsigned Idx = Param->getFunctionScopeIndex() + 1;
591      os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
592
593      R->printPretty(os);
594      os << '\'';
595    }
596  }
597
598  if (os.str().empty()) {
599    if (V.getAs<loc::ConcreteInt>()) {
600      bool b = false;
601      if (R->isBoundable()) {
602        if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
603          if (TR->getValueType()->isObjCObjectPointerType()) {
604            os << "nil object reference stored to ";
605            b = true;
606          }
607        }
608      }
609
610      if (!b)
611        os << "Null pointer value stored to ";
612    }
613    else if (V.isUndef()) {
614      os << "Uninitialized value stored to ";
615    } else if (Optional<nonloc::ConcreteInt> CV =
616                   V.getAs<nonloc::ConcreteInt>()) {
617      os << "The value " << CV->getValue() << " is assigned to ";
618    }
619    else
620      os << "Value assigned to ";
621
622    os << '\'';
623    R->printPretty(os);
624    os << '\'';
625  }
626
627  // Construct a new PathDiagnosticPiece.
628  ProgramPoint P = StoreSite->getLocation();
629  PathDiagnosticLocation L;
630  if (P.getAs<CallEnter>() && InitE)
631    L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
632                               P.getLocationContext());
633  else
634    L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
635  if (!L.isValid())
636    return NULL;
637  return new PathDiagnosticEventPiece(L, os.str());
638}
639
640void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
641  static int tag = 0;
642  ID.AddPointer(&tag);
643  ID.AddBoolean(Assumption);
644  ID.Add(Constraint);
645}
646
647/// Return the tag associated with this visitor.  This tag will be used
648/// to make all PathDiagnosticPieces created by this visitor.
649const char *TrackConstraintBRVisitor::getTag() {
650  return "TrackConstraintBRVisitor";
651}
652
653PathDiagnosticPiece *
654TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
655                                    const ExplodedNode *PrevN,
656                                    BugReporterContext &BRC,
657                                    BugReport &BR) {
658  if (isSatisfied)
659    return NULL;
660
661  // Check if in the previous state it was feasible for this constraint
662  // to *not* be true.
663  if (PrevN->getState()->assume(Constraint, !Assumption)) {
664
665    isSatisfied = true;
666
667    // As a sanity check, make sure that the negation of the constraint
668    // was infeasible in the current state.  If it is feasible, we somehow
669    // missed the transition point.
670    if (N->getState()->assume(Constraint, !Assumption))
671      return NULL;
672
673    // We found the transition point for the constraint.  We now need to
674    // pretty-print the constraint. (work-in-progress)
675    std::string sbuf;
676    llvm::raw_string_ostream os(sbuf);
677
678    if (Constraint.getAs<Loc>()) {
679      os << "Assuming pointer value is ";
680      os << (Assumption ? "non-null" : "null");
681    }
682
683    if (os.str().empty())
684      return NULL;
685
686    // Construct a new PathDiagnosticPiece.
687    ProgramPoint P = N->getLocation();
688    PathDiagnosticLocation L =
689      PathDiagnosticLocation::create(P, BRC.getSourceManager());
690    if (!L.isValid())
691      return NULL;
692
693    PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
694    X->setTag(getTag());
695    return X;
696  }
697
698  return NULL;
699}
700
701SuppressInlineDefensiveChecksVisitor::
702SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
703  : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
704    assert(N->getState()->isNull(V).isConstrainedTrue() &&
705           "The visitor only tracks the cases where V is constrained to 0");
706}
707
708void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
709  static int id = 0;
710  ID.AddPointer(&id);
711  ID.Add(V);
712}
713
714const char *SuppressInlineDefensiveChecksVisitor::getTag() {
715  return "IDCVisitor";
716}
717
718PathDiagnosticPiece *
719SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
720                                                const ExplodedNode *Pred,
721                                                BugReporterContext &BRC,
722                                                BugReport &BR) {
723  if (IsSatisfied)
724    return 0;
725  AnalyzerOptions &Options =
726  BRC.getBugReporter().getEngine().getAnalysisManager().options;
727  if (!Options.shouldSuppressInlinedDefensiveChecks())
728    return 0;
729
730  // Start tracking after we see the first state in which the value is null.
731  if (!IsTrackingTurnedOn)
732    if (Succ->getState()->isNull(V).isConstrainedTrue())
733      IsTrackingTurnedOn = true;
734  if (!IsTrackingTurnedOn)
735    return 0;
736
737
738  // Check if in the previous state it was feasible for this value
739  // to *not* be null.
740  if (Pred->getState()->assume(V, true)) {
741    IsSatisfied = true;
742
743    assert(!Succ->getState()->assume(V, true));
744
745    // Check if this is inlined defensive checks.
746    const LocationContext *CurLC =Succ->getLocationContext();
747    const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
748    if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
749      BR.markInvalid("Suppress IDC", CurLC);
750  }
751  return 0;
752}
753
754static const MemRegion *getLocationRegionIfReference(const Expr *E,
755                                                     const ExplodedNode *N) {
756  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
757    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
758      if (!VD->getType()->isReferenceType())
759        return 0;
760      ProgramStateManager &StateMgr = N->getState()->getStateManager();
761      MemRegionManager &MRMgr = StateMgr.getRegionManager();
762      return MRMgr.getVarRegion(VD, N->getLocationContext());
763    }
764  }
765
766  // FIXME: This does not handle other kinds of null references,
767  // for example, references from FieldRegions:
768  //   struct Wrapper { int &ref; };
769  //   Wrapper w = { *(int *)0 };
770  //   w.ref = 1;
771
772  return 0;
773}
774
775bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
776                                        const Stmt *S,
777                                        BugReport &report, bool IsArg) {
778  if (!S || !N)
779    return false;
780
781  // Peel off OpaqueValueExpr.
782  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S))
783    S = OVE->getSourceExpr();
784
785  // Peel off the ternary operator.
786  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(S)) {
787    ProgramStateRef State = N->getState();
788    SVal CondVal = State->getSVal(CO->getCond(), N->getLocationContext());
789    if (State->isNull(CondVal).isConstrainedTrue()) {
790      S = CO->getTrueExpr();
791    } else {
792      assert(State->isNull(CondVal).isConstrainedFalse());
793      S =  CO->getFalseExpr();
794    }
795  }
796
797  const Expr *Inner = 0;
798  if (const Expr *Ex = dyn_cast<Expr>(S)) {
799    Ex = Ex->IgnoreParenCasts();
800    if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
801      Inner = Ex;
802  }
803
804  if (IsArg) {
805    assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
806  } else {
807    // Walk through nodes until we get one that matches the statement exactly.
808    // Alternately, if we hit a known lvalue for the statement, we know we've
809    // gone too far (though we can likely track the lvalue better anyway).
810    do {
811      const ProgramPoint &pp = N->getLocation();
812      if (Optional<PostStmt> ps = pp.getAs<PostStmt>()) {
813        if (ps->getStmt() == S || ps->getStmt() == Inner)
814          break;
815      } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
816        if (CEE->getCalleeContext()->getCallSite() == S ||
817            CEE->getCalleeContext()->getCallSite() == Inner)
818          break;
819      }
820      N = N->getFirstPred();
821    } while (N);
822
823    if (!N)
824      return false;
825  }
826
827  ProgramStateRef state = N->getState();
828
829  // See if the expression we're interested refers to a variable.
830  // If so, we can track both its contents and constraints on its value.
831  if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
832    const MemRegion *R = 0;
833
834    // Find the ExplodedNode where the lvalue (the value of 'Ex')
835    // was computed.  We need this for getting the location value.
836    const ExplodedNode *LVNode = N;
837    while (LVNode) {
838      if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
839        if (P->getStmt() == Inner)
840          break;
841      }
842      LVNode = LVNode->getFirstPred();
843    }
844    assert(LVNode && "Unable to find the lvalue node.");
845    ProgramStateRef LVState = LVNode->getState();
846    SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
847
848    if (LVState->isNull(LVal).isConstrainedTrue()) {
849      // In case of C++ references, we want to differentiate between a null
850      // reference and reference to null pointer.
851      // If the LVal is null, check if we are dealing with null reference.
852      // For those, we want to track the location of the reference.
853      if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
854        R = RR;
855    } else {
856      R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
857
858      // If this is a C++ reference to a null pointer, we are tracking the
859      // pointer. In additon, we should find the store at which the reference
860      // got initialized.
861      if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
862        if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
863          report.addVisitor(new FindLastStoreBRVisitor(*KV, RR));
864      }
865    }
866
867    if (R) {
868      // Mark both the variable region and its contents as interesting.
869      SVal V = state->getRawSVal(loc::MemRegionVal(R));
870
871      // If the value matches the default for the variable region, that
872      // might mean that it's been cleared out of the state. Fall back to
873      // the full argument expression (with casts and such intact).
874      if (IsArg) {
875        bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant();
876        if (!UseArgValue) {
877          const SymbolRegionValue *SRV =
878            dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol());
879          if (SRV)
880            UseArgValue = (SRV->getRegion() == R);
881        }
882        if (UseArgValue)
883          V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
884      }
885
886      report.markInteresting(R);
887      report.markInteresting(V);
888      report.addVisitor(new UndefOrNullArgVisitor(R));
889
890      if (isa<SymbolicRegion>(R)) {
891        TrackConstraintBRVisitor *VI =
892          new TrackConstraintBRVisitor(loc::MemRegionVal(R), false);
893        report.addVisitor(VI);
894      }
895
896      // If the contents are symbolic, find out when they became null.
897      if (V.getAsLocSymbol()) {
898        BugReporterVisitor *ConstraintTracker =
899          new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
900        report.addVisitor(ConstraintTracker);
901
902        // Add visitor, which will suppress inline defensive checks.
903        if (N->getState()->isNull(V).isConstrainedTrue()) {
904          BugReporterVisitor *IDCSuppressor =
905            new SuppressInlineDefensiveChecksVisitor(V.castAs<DefinedSVal>(),
906                                                     N);
907          report.addVisitor(IDCSuppressor);
908        }
909      }
910
911      if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
912        report.addVisitor(new FindLastStoreBRVisitor(*KV, R));
913      return true;
914    }
915  }
916
917  // If the expression is not an "lvalue expression", we can still
918  // track the constraints on its contents.
919  SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
920
921  // If the value came from an inlined function call, we should at least make
922  // sure that function isn't pruned in our output.
923  if (const Expr *E = dyn_cast<Expr>(S))
924    S = E->IgnoreParenCasts();
925  ReturnVisitor::addVisitorIfNecessary(N, S, report);
926
927  // Uncomment this to find cases where we aren't properly getting the
928  // base value that was dereferenced.
929  // assert(!V.isUnknownOrUndef());
930  // Is it a symbolic value?
931  if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
932    // At this point we are dealing with the region's LValue.
933    // However, if the rvalue is a symbolic region, we should track it as well.
934    SVal RVal = state->getSVal(L->getRegion());
935    const MemRegion *RegionRVal = RVal.getAsRegion();
936    report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
937
938    if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
939      report.markInteresting(RegionRVal);
940      report.addVisitor(new TrackConstraintBRVisitor(
941        loc::MemRegionVal(RegionRVal), false));
942    }
943  }
944
945  return true;
946}
947
948BugReporterVisitor *
949FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
950                                            const MemRegion *R) {
951  assert(R && "The memory region is null.");
952
953  ProgramStateRef state = N->getState();
954  if (Optional<KnownSVal> KV = state->getSVal(R).getAs<KnownSVal>())
955    return new FindLastStoreBRVisitor(*KV, R);
956  return 0;
957}
958
959PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
960                                                     const ExplodedNode *PrevN,
961                                                     BugReporterContext &BRC,
962                                                     BugReport &BR) {
963  Optional<PostStmt> P = N->getLocationAs<PostStmt>();
964  if (!P)
965    return 0;
966  const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
967  if (!ME)
968    return 0;
969  const Expr *Receiver = ME->getInstanceReceiver();
970  if (!Receiver)
971    return 0;
972  ProgramStateRef state = N->getState();
973  const SVal &V = state->getSVal(Receiver, N->getLocationContext());
974  Optional<DefinedOrUnknownSVal> DV = V.getAs<DefinedOrUnknownSVal>();
975  if (!DV)
976    return 0;
977  state = state->assume(*DV, true);
978  if (state)
979    return 0;
980
981  // The receiver was nil, and hence the method was skipped.
982  // Register a BugReporterVisitor to issue a message telling us how
983  // the receiver was null.
984  bugreporter::trackNullOrUndefValue(N, Receiver, BR);
985  // Issue a message saying that the method was skipped.
986  PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
987                                     N->getLocationContext());
988  return new PathDiagnosticEventPiece(L, "No method is called "
989      "because the receiver is nil");
990}
991
992// Registers every VarDecl inside a Stmt with a last store visitor.
993void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
994                                                       const Stmt *S) {
995  const ExplodedNode *N = BR.getErrorNode();
996  std::deque<const Stmt *> WorkList;
997  WorkList.push_back(S);
998
999  while (!WorkList.empty()) {
1000    const Stmt *Head = WorkList.front();
1001    WorkList.pop_front();
1002
1003    ProgramStateRef state = N->getState();
1004    ProgramStateManager &StateMgr = state->getStateManager();
1005
1006    if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1007      if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1008        const VarRegion *R =
1009        StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1010
1011        // What did we load?
1012        SVal V = state->getSVal(S, N->getLocationContext());
1013
1014        if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1015          // Register a new visitor with the BugReport.
1016          BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R));
1017        }
1018      }
1019    }
1020
1021    for (Stmt::const_child_iterator I = Head->child_begin();
1022        I != Head->child_end(); ++I)
1023      WorkList.push_back(*I);
1024  }
1025}
1026
1027//===----------------------------------------------------------------------===//
1028// Visitor that tries to report interesting diagnostics from conditions.
1029//===----------------------------------------------------------------------===//
1030
1031/// Return the tag associated with this visitor.  This tag will be used
1032/// to make all PathDiagnosticPieces created by this visitor.
1033const char *ConditionBRVisitor::getTag() {
1034  return "ConditionBRVisitor";
1035}
1036
1037PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1038                                                   const ExplodedNode *Prev,
1039                                                   BugReporterContext &BRC,
1040                                                   BugReport &BR) {
1041  PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1042  if (piece) {
1043    piece->setTag(getTag());
1044    if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1045      ev->setPrunable(true, /* override */ false);
1046  }
1047  return piece;
1048}
1049
1050PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1051                                                       const ExplodedNode *Prev,
1052                                                       BugReporterContext &BRC,
1053                                                       BugReport &BR) {
1054
1055  ProgramPoint progPoint = N->getLocation();
1056  ProgramStateRef CurrentState = N->getState();
1057  ProgramStateRef PrevState = Prev->getState();
1058
1059  // Compare the GDMs of the state, because that is where constraints
1060  // are managed.  Note that ensure that we only look at nodes that
1061  // were generated by the analyzer engine proper, not checkers.
1062  if (CurrentState->getGDM().getRoot() ==
1063      PrevState->getGDM().getRoot())
1064    return 0;
1065
1066  // If an assumption was made on a branch, it should be caught
1067  // here by looking at the state transition.
1068  if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1069    const CFGBlock *srcBlk = BE->getSrc();
1070    if (const Stmt *term = srcBlk->getTerminator())
1071      return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1072    return 0;
1073  }
1074
1075  if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1076    // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1077    // violation.
1078    const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1079      cast<GRBugReporter>(BRC.getBugReporter()).
1080        getEngine().geteagerlyAssumeBinOpBifurcationTags();
1081
1082    const ProgramPointTag *tag = PS->getTag();
1083    if (tag == tags.first)
1084      return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1085                           BRC, BR, N);
1086    if (tag == tags.second)
1087      return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1088                           BRC, BR, N);
1089
1090    return 0;
1091  }
1092
1093  return 0;
1094}
1095
1096PathDiagnosticPiece *
1097ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1098                                    const ExplodedNode *N,
1099                                    const CFGBlock *srcBlk,
1100                                    const CFGBlock *dstBlk,
1101                                    BugReport &R,
1102                                    BugReporterContext &BRC) {
1103  const Expr *Cond = 0;
1104
1105  switch (Term->getStmtClass()) {
1106  default:
1107    return 0;
1108  case Stmt::IfStmtClass:
1109    Cond = cast<IfStmt>(Term)->getCond();
1110    break;
1111  case Stmt::ConditionalOperatorClass:
1112    Cond = cast<ConditionalOperator>(Term)->getCond();
1113    break;
1114  }
1115
1116  assert(Cond);
1117  assert(srcBlk->succ_size() == 2);
1118  const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1119  return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1120}
1121
1122PathDiagnosticPiece *
1123ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1124                                  bool tookTrue,
1125                                  BugReporterContext &BRC,
1126                                  BugReport &R,
1127                                  const ExplodedNode *N) {
1128
1129  const Expr *Ex = Cond;
1130
1131  while (true) {
1132    Ex = Ex->IgnoreParenCasts();
1133    switch (Ex->getStmtClass()) {
1134      default:
1135        return 0;
1136      case Stmt::BinaryOperatorClass:
1137        return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1138                             R, N);
1139      case Stmt::DeclRefExprClass:
1140        return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1141                             R, N);
1142      case Stmt::UnaryOperatorClass: {
1143        const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1144        if (UO->getOpcode() == UO_LNot) {
1145          tookTrue = !tookTrue;
1146          Ex = UO->getSubExpr();
1147          continue;
1148        }
1149        return 0;
1150      }
1151    }
1152  }
1153}
1154
1155bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1156                                      BugReporterContext &BRC,
1157                                      BugReport &report,
1158                                      const ExplodedNode *N,
1159                                      Optional<bool> &prunable) {
1160  const Expr *OriginalExpr = Ex;
1161  Ex = Ex->IgnoreParenCasts();
1162
1163  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1164    const bool quotes = isa<VarDecl>(DR->getDecl());
1165    if (quotes) {
1166      Out << '\'';
1167      const LocationContext *LCtx = N->getLocationContext();
1168      const ProgramState *state = N->getState().getPtr();
1169      if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1170                                                LCtx).getAsRegion()) {
1171        if (report.isInteresting(R))
1172          prunable = false;
1173        else {
1174          const ProgramState *state = N->getState().getPtr();
1175          SVal V = state->getSVal(R);
1176          if (report.isInteresting(V))
1177            prunable = false;
1178        }
1179      }
1180    }
1181    Out << DR->getDecl()->getDeclName().getAsString();
1182    if (quotes)
1183      Out << '\'';
1184    return quotes;
1185  }
1186
1187  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1188    QualType OriginalTy = OriginalExpr->getType();
1189    if (OriginalTy->isPointerType()) {
1190      if (IL->getValue() == 0) {
1191        Out << "null";
1192        return false;
1193      }
1194    }
1195    else if (OriginalTy->isObjCObjectPointerType()) {
1196      if (IL->getValue() == 0) {
1197        Out << "nil";
1198        return false;
1199      }
1200    }
1201
1202    Out << IL->getValue();
1203    return false;
1204  }
1205
1206  return false;
1207}
1208
1209PathDiagnosticPiece *
1210ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1211                                  const BinaryOperator *BExpr,
1212                                  const bool tookTrue,
1213                                  BugReporterContext &BRC,
1214                                  BugReport &R,
1215                                  const ExplodedNode *N) {
1216
1217  bool shouldInvert = false;
1218  Optional<bool> shouldPrune;
1219
1220  SmallString<128> LhsString, RhsString;
1221  {
1222    llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1223    const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1224                                       shouldPrune);
1225    const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1226                                       shouldPrune);
1227
1228    shouldInvert = !isVarLHS && isVarRHS;
1229  }
1230
1231  BinaryOperator::Opcode Op = BExpr->getOpcode();
1232
1233  if (BinaryOperator::isAssignmentOp(Op)) {
1234    // For assignment operators, all that we care about is that the LHS
1235    // evaluates to "true" or "false".
1236    return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1237                                  BRC, R, N);
1238  }
1239
1240  // For non-assignment operations, we require that we can understand
1241  // both the LHS and RHS.
1242  if (LhsString.empty() || RhsString.empty())
1243    return 0;
1244
1245  // Should we invert the strings if the LHS is not a variable name?
1246  SmallString<256> buf;
1247  llvm::raw_svector_ostream Out(buf);
1248  Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1249
1250  // Do we need to invert the opcode?
1251  if (shouldInvert)
1252    switch (Op) {
1253      default: break;
1254      case BO_LT: Op = BO_GT; break;
1255      case BO_GT: Op = BO_LT; break;
1256      case BO_LE: Op = BO_GE; break;
1257      case BO_GE: Op = BO_LE; break;
1258    }
1259
1260  if (!tookTrue)
1261    switch (Op) {
1262      case BO_EQ: Op = BO_NE; break;
1263      case BO_NE: Op = BO_EQ; break;
1264      case BO_LT: Op = BO_GE; break;
1265      case BO_GT: Op = BO_LE; break;
1266      case BO_LE: Op = BO_GT; break;
1267      case BO_GE: Op = BO_LT; break;
1268      default:
1269        return 0;
1270    }
1271
1272  switch (Op) {
1273    case BO_EQ:
1274      Out << "equal to ";
1275      break;
1276    case BO_NE:
1277      Out << "not equal to ";
1278      break;
1279    default:
1280      Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1281      break;
1282  }
1283
1284  Out << (shouldInvert ? LhsString : RhsString);
1285  const LocationContext *LCtx = N->getLocationContext();
1286  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1287  PathDiagnosticEventPiece *event =
1288    new PathDiagnosticEventPiece(Loc, Out.str());
1289  if (shouldPrune.hasValue())
1290    event->setPrunable(shouldPrune.getValue());
1291  return event;
1292}
1293
1294PathDiagnosticPiece *
1295ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1296                                           const Expr *CondVarExpr,
1297                                           const bool tookTrue,
1298                                           BugReporterContext &BRC,
1299                                           BugReport &report,
1300                                           const ExplodedNode *N) {
1301  // FIXME: If there's already a constraint tracker for this variable,
1302  // we shouldn't emit anything here (c.f. the double note in
1303  // test/Analysis/inlining/path-notes.c)
1304  SmallString<256> buf;
1305  llvm::raw_svector_ostream Out(buf);
1306  Out << "Assuming " << LhsString << " is ";
1307
1308  QualType Ty = CondVarExpr->getType();
1309
1310  if (Ty->isPointerType())
1311    Out << (tookTrue ? "not null" : "null");
1312  else if (Ty->isObjCObjectPointerType())
1313    Out << (tookTrue ? "not nil" : "nil");
1314  else if (Ty->isBooleanType())
1315    Out << (tookTrue ? "true" : "false");
1316  else if (Ty->isIntegerType())
1317    Out << (tookTrue ? "non-zero" : "zero");
1318  else
1319    return 0;
1320
1321  const LocationContext *LCtx = N->getLocationContext();
1322  PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1323  PathDiagnosticEventPiece *event =
1324    new PathDiagnosticEventPiece(Loc, Out.str());
1325
1326  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1327    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1328      const ProgramState *state = N->getState().getPtr();
1329      if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1330        if (report.isInteresting(R))
1331          event->setPrunable(false);
1332      }
1333    }
1334  }
1335
1336  return event;
1337}
1338
1339PathDiagnosticPiece *
1340ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1341                                  const DeclRefExpr *DR,
1342                                  const bool tookTrue,
1343                                  BugReporterContext &BRC,
1344                                  BugReport &report,
1345                                  const ExplodedNode *N) {
1346
1347  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1348  if (!VD)
1349    return 0;
1350
1351  SmallString<256> Buf;
1352  llvm::raw_svector_ostream Out(Buf);
1353
1354  Out << "Assuming '";
1355  VD->getDeclName().printName(Out);
1356  Out << "' is ";
1357
1358  QualType VDTy = VD->getType();
1359
1360  if (VDTy->isPointerType())
1361    Out << (tookTrue ? "non-null" : "null");
1362  else if (VDTy->isObjCObjectPointerType())
1363    Out << (tookTrue ? "non-nil" : "nil");
1364  else if (VDTy->isScalarType())
1365    Out << (tookTrue ? "not equal to 0" : "0");
1366  else
1367    return 0;
1368
1369  const LocationContext *LCtx = N->getLocationContext();
1370  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1371  PathDiagnosticEventPiece *event =
1372    new PathDiagnosticEventPiece(Loc, Out.str());
1373
1374  const ProgramState *state = N->getState().getPtr();
1375  if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1376    if (report.isInteresting(R))
1377      event->setPrunable(false);
1378    else {
1379      SVal V = state->getSVal(R);
1380      if (report.isInteresting(V))
1381        event->setPrunable(false);
1382    }
1383  }
1384  return event;
1385}
1386
1387PathDiagnosticPiece *
1388LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1389                                                    const ExplodedNode *N,
1390                                                    BugReport &BR) {
1391  const Stmt *S = BR.getStmt();
1392  if (!S)
1393    return 0;
1394
1395  // Here we suppress false positives coming from system macros. This list is
1396  // based on known issues.
1397
1398  // Skip reports within the sys/queue.h macros as we do not have the ability to
1399  // reason about data structure shapes.
1400  SourceManager &SM = BRC.getSourceManager();
1401  SourceLocation Loc = S->getLocStart();
1402  while (Loc.isMacroID()) {
1403    if (SM.isInSystemMacro(Loc) &&
1404       (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
1405      BR.markInvalid(getTag(), 0);
1406      return 0;
1407    }
1408    Loc = SM.getSpellingLoc(Loc);
1409  }
1410
1411  return 0;
1412}
1413
1414PathDiagnosticPiece *
1415UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1416                                  const ExplodedNode *PrevN,
1417                                  BugReporterContext &BRC,
1418                                  BugReport &BR) {
1419
1420  ProgramStateRef State = N->getState();
1421  ProgramPoint ProgLoc = N->getLocation();
1422
1423  // We are only interested in visiting CallEnter nodes.
1424  Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1425  if (!CEnter)
1426    return 0;
1427
1428  // Check if one of the arguments is the region the visitor is tracking.
1429  CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1430  CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1431  unsigned Idx = 0;
1432  for (CallEvent::param_iterator I = Call->param_begin(),
1433                                 E = Call->param_end(); I != E; ++I, ++Idx) {
1434    const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1435
1436    // Are we tracking the argument or its subregion?
1437    if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1438      continue;
1439
1440    // Check the function parameter type.
1441    const ParmVarDecl *ParamDecl = *I;
1442    assert(ParamDecl && "Formal parameter has no decl?");
1443    QualType T = ParamDecl->getType();
1444
1445    if (!(T->isAnyPointerType() || T->isReferenceType())) {
1446      // Function can only change the value passed in by address.
1447      continue;
1448    }
1449
1450    // If it is a const pointer value, the function does not intend to
1451    // change the value.
1452    if (T->getPointeeType().isConstQualified())
1453      continue;
1454
1455    // Mark the call site (LocationContext) as interesting if the value of the
1456    // argument is undefined or '0'/'NULL'.
1457    SVal BoundVal = State->getSVal(R);
1458    if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1459      BR.markInteresting(CEnter->getCalleeContext());
1460      return 0;
1461    }
1462  }
1463  return 0;
1464}
1465