BugReporterVisitors.cpp revision 17828ca5857d5d9cadfffd339f888de58182c8f1
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/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/raw_ostream.h"
26
27using namespace clang;
28using namespace ento;
29
30using llvm::FoldingSetNodeID;
31
32//===----------------------------------------------------------------------===//
33// Utility functions.
34//===----------------------------------------------------------------------===//
35
36bool bugreporter::isDeclRefExprToReference(const Expr *E) {
37  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
38    return DRE->getDecl()->getType()->isReferenceType();
39  }
40  return false;
41}
42
43const Expr *bugreporter::getDerefExpr(const Stmt *S) {
44  // Pattern match for a few useful cases:
45  //   a[0], p->f, *p
46  const Expr *E = dyn_cast<Expr>(S);
47  if (!E)
48    return 0;
49  E = E->IgnoreParenCasts();
50
51  while (true) {
52    if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
53      assert(B->isAssignmentOp());
54      E = B->getLHS()->IgnoreParenCasts();
55      continue;
56    }
57    else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
58      if (U->getOpcode() == UO_Deref)
59        return U->getSubExpr()->IgnoreParenCasts();
60    }
61    else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
62      if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
63        return ME->getBase()->IgnoreParenCasts();
64      } else {
65        // If we have a member expr with a dot, the base must have been
66        // dereferenced.
67        return getDerefExpr(ME->getBase());
68      }
69    }
70    else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
71      return IvarRef->getBase()->IgnoreParenCasts();
72    }
73    else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
74      return AE->getBase();
75    }
76    else if (isDeclRefExprToReference(E)) {
77      return E;
78    }
79    break;
80  }
81
82  return NULL;
83}
84
85const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
86  const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
87  if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
88    return BE->getRHS();
89  return NULL;
90}
91
92const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
93  const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
94  if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
95    return RS->getRetValue();
96  return NULL;
97}
98
99//===----------------------------------------------------------------------===//
100// Definitions for bug reporter visitors.
101//===----------------------------------------------------------------------===//
102
103PathDiagnosticPiece*
104BugReporterVisitor::getEndPath(BugReporterContext &BRC,
105                               const ExplodedNode *EndPathNode,
106                               BugReport &BR) {
107  return 0;
108}
109
110PathDiagnosticPiece*
111BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
112                                      const ExplodedNode *EndPathNode,
113                                      BugReport &BR) {
114  PathDiagnosticLocation L =
115    PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
116
117  BugReport::ranges_iterator Beg, End;
118  llvm::tie(Beg, End) = BR.getRanges();
119
120  // Only add the statement itself as a range if we didn't specify any
121  // special ranges for this report.
122  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
123      BR.getDescription(),
124      Beg == End);
125  for (; Beg != End; ++Beg)
126    P->addRange(*Beg);
127
128  return P;
129}
130
131
132namespace {
133/// Emits an extra note at the return statement of an interesting stack frame.
134///
135/// The returned value is marked as an interesting value, and if it's null,
136/// adds a visitor to track where it became null.
137///
138/// This visitor is intended to be used when another visitor discovers that an
139/// interesting value comes from an inlined function call.
140class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
141  const StackFrameContext *StackFrame;
142  enum {
143    Initial,
144    MaybeUnsuppress,
145    Satisfied
146  } Mode;
147
148  bool EnableNullFPSuppression;
149
150public:
151  ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
152    : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
153
154  static void *getTag() {
155    static int Tag = 0;
156    return static_cast<void *>(&Tag);
157  }
158
159  virtual void Profile(llvm::FoldingSetNodeID &ID) const {
160    ID.AddPointer(ReturnVisitor::getTag());
161    ID.AddPointer(StackFrame);
162    ID.AddBoolean(EnableNullFPSuppression);
163  }
164
165  /// Adds a ReturnVisitor if the given statement represents a call that was
166  /// inlined.
167  ///
168  /// This will search back through the ExplodedGraph, starting from the given
169  /// node, looking for when the given statement was processed. If it turns out
170  /// the statement is a call that was inlined, we add the visitor to the
171  /// bug report, so it can print a note later.
172  static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
173                                    BugReport &BR,
174                                    bool InEnableNullFPSuppression) {
175    if (!CallEvent::isCallStmt(S))
176      return;
177
178    // First, find when we processed the statement.
179    do {
180      if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
181        if (CEE->getCalleeContext()->getCallSite() == S)
182          break;
183      if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
184        if (SP->getStmt() == S)
185          break;
186
187      Node = Node->getFirstPred();
188    } while (Node);
189
190    // Next, step over any post-statement checks.
191    while (Node && Node->getLocation().getAs<PostStmt>())
192      Node = Node->getFirstPred();
193    if (!Node)
194      return;
195
196    // Finally, see if we inlined the call.
197    Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
198    if (!CEE)
199      return;
200
201    const StackFrameContext *CalleeContext = CEE->getCalleeContext();
202    if (CalleeContext->getCallSite() != S)
203      return;
204
205    // Check the return value.
206    ProgramStateRef State = Node->getState();
207    SVal RetVal = State->getSVal(S, Node->getLocationContext());
208
209    // Handle cases where a reference is returned and then immediately used.
210    if (cast<Expr>(S)->isGLValue())
211      if (Optional<Loc> LValue = RetVal.getAs<Loc>())
212        RetVal = State->getSVal(*LValue);
213
214    // See if the return value is NULL. If so, suppress the report.
215    SubEngine *Eng = State->getStateManager().getOwningEngine();
216    assert(Eng && "Cannot file a bug report without an owning engine");
217    AnalyzerOptions &Options = Eng->getAnalysisManager().options;
218
219    bool EnableNullFPSuppression = false;
220    if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
221      if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
222        EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
223
224    BR.markInteresting(CalleeContext);
225    BR.addVisitor(new ReturnVisitor(CalleeContext, EnableNullFPSuppression));
226  }
227
228  /// Returns true if any counter-suppression heuristics are enabled for
229  /// ReturnVisitor.
230  static bool hasCounterSuppression(AnalyzerOptions &Options) {
231    return Options.shouldAvoidSuppressingNullArgumentPaths();
232  }
233
234  PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
235                                        const ExplodedNode *PrevN,
236                                        BugReporterContext &BRC,
237                                        BugReport &BR) {
238    // Only print a message at the interesting return statement.
239    if (N->getLocationContext() != StackFrame)
240      return 0;
241
242    Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
243    if (!SP)
244      return 0;
245
246    const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
247    if (!Ret)
248      return 0;
249
250    // Okay, we're at the right return statement, but do we have the return
251    // value available?
252    ProgramStateRef State = N->getState();
253    SVal V = State->getSVal(Ret, StackFrame);
254    if (V.isUnknownOrUndef())
255      return 0;
256
257    // Don't print any more notes after this one.
258    Mode = Satisfied;
259
260    const Expr *RetE = Ret->getRetValue();
261    assert(RetE && "Tracking a return value for a void function");
262
263    // Handle cases where a reference is returned and then immediately used.
264    Optional<Loc> LValue;
265    if (RetE->isGLValue()) {
266      if ((LValue = V.getAs<Loc>())) {
267        SVal RValue = State->getRawSVal(*LValue, RetE->getType());
268        if (RValue.getAs<DefinedSVal>())
269          V = RValue;
270      }
271    }
272
273    // Ignore aggregate rvalues.
274    if (V.getAs<nonloc::LazyCompoundVal>() ||
275        V.getAs<nonloc::CompoundVal>())
276      return 0;
277
278    RetE = RetE->IgnoreParenCasts();
279
280    // If we can't prove the return value is 0, just mark it interesting, and
281    // make sure to track it into any further inner functions.
282    if (!State->isNull(V).isConstrainedTrue()) {
283      BR.markInteresting(V);
284      ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
285                                           EnableNullFPSuppression);
286      return 0;
287    }
288
289    // If we're returning 0, we should track where that 0 came from.
290    bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
291                                       EnableNullFPSuppression);
292
293    // Build an appropriate message based on the return value.
294    SmallString<64> Msg;
295    llvm::raw_svector_ostream Out(Msg);
296
297    if (V.getAs<Loc>()) {
298      // If we have counter-suppression enabled, make sure we keep visiting
299      // future nodes. We want to emit a path note as well, in case
300      // the report is resurrected as valid later on.
301      ExprEngine &Eng = BRC.getBugReporter().getEngine();
302      AnalyzerOptions &Options = Eng.getAnalysisManager().options;
303      if (EnableNullFPSuppression && hasCounterSuppression(Options))
304        Mode = MaybeUnsuppress;
305
306      if (RetE->getType()->isObjCObjectPointerType())
307        Out << "Returning nil";
308      else
309        Out << "Returning null pointer";
310    } else {
311      Out << "Returning zero";
312    }
313
314    if (LValue) {
315      if (const MemRegion *MR = LValue->getAsRegion()) {
316        if (MR->canPrintPretty()) {
317          Out << " (reference to ";
318          MR->printPretty(Out);
319          Out << ")";
320        }
321      }
322    } else {
323      // FIXME: We should have a more generalized location printing mechanism.
324      if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
325        if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
326          Out << " (loaded from '" << *DD << "')";
327    }
328
329    PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
330    return new PathDiagnosticEventPiece(L, Out.str());
331  }
332
333  PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
334                                                const ExplodedNode *PrevN,
335                                                BugReporterContext &BRC,
336                                                BugReport &BR) {
337#ifndef NDEBUG
338    ExprEngine &Eng = BRC.getBugReporter().getEngine();
339    AnalyzerOptions &Options = Eng.getAnalysisManager().options;
340    assert(hasCounterSuppression(Options));
341#endif
342
343    // Are we at the entry node for this call?
344    Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
345    if (!CE)
346      return 0;
347
348    if (CE->getCalleeContext() != StackFrame)
349      return 0;
350
351    Mode = Satisfied;
352
353    // Don't automatically suppress a report if one of the arguments is
354    // known to be a null pointer. Instead, start tracking /that/ null
355    // value back to its origin.
356    ProgramStateManager &StateMgr = BRC.getStateManager();
357    CallEventManager &CallMgr = StateMgr.getCallEventManager();
358
359    ProgramStateRef State = N->getState();
360    CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
361    for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
362      Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
363      if (!ArgV)
364        continue;
365
366      const Expr *ArgE = Call->getArgExpr(I);
367      if (!ArgE)
368        continue;
369
370      // Is it possible for this argument to be non-null?
371      if (!State->isNull(*ArgV).isConstrainedTrue())
372        continue;
373
374      if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
375                                             EnableNullFPSuppression))
376        BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
377
378      // If we /can't/ track the null pointer, we should err on the side of
379      // false negatives, and continue towards marking this report invalid.
380      // (We will still look at the other arguments, though.)
381    }
382
383    return 0;
384  }
385
386  PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
387                                 const ExplodedNode *PrevN,
388                                 BugReporterContext &BRC,
389                                 BugReport &BR) {
390    switch (Mode) {
391    case Initial:
392      return visitNodeInitial(N, PrevN, BRC, BR);
393    case MaybeUnsuppress:
394      return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
395    case Satisfied:
396      return 0;
397    }
398
399    llvm_unreachable("Invalid visit mode!");
400  }
401
402  PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
403                                  const ExplodedNode *N,
404                                  BugReport &BR) {
405    if (EnableNullFPSuppression)
406      BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
407    return 0;
408  }
409};
410} // end anonymous namespace
411
412
413void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
414  static int tag = 0;
415  ID.AddPointer(&tag);
416  ID.AddPointer(R);
417  ID.Add(V);
418  ID.AddBoolean(EnableNullFPSuppression);
419}
420
421/// Returns true if \p N represents the DeclStmt declaring and initializing
422/// \p VR.
423static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
424  Optional<PostStmt> P = N->getLocationAs<PostStmt>();
425  if (!P)
426    return false;
427
428  const DeclStmt *DS = P->getStmtAs<DeclStmt>();
429  if (!DS)
430    return false;
431
432  if (DS->getSingleDecl() != VR->getDecl())
433    return false;
434
435  const MemSpaceRegion *VarSpace = VR->getMemorySpace();
436  const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
437  if (!FrameSpace) {
438    // If we ever directly evaluate global DeclStmts, this assertion will be
439    // invalid, but this still seems preferable to silently accepting an
440    // initialization that may be for a path-sensitive variable.
441    assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
442    return true;
443  }
444
445  assert(VR->getDecl()->hasLocalStorage());
446  const LocationContext *LCtx = N->getLocationContext();
447  return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
448}
449
450PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
451                                                       const ExplodedNode *Pred,
452                                                       BugReporterContext &BRC,
453                                                       BugReport &BR) {
454
455  if (Satisfied)
456    return NULL;
457
458  const ExplodedNode *StoreSite = 0;
459  const Expr *InitE = 0;
460  bool IsParam = false;
461
462  // First see if we reached the declaration of the region.
463  if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
464    if (isInitializationOfVar(Pred, VR)) {
465      StoreSite = Pred;
466      InitE = VR->getDecl()->getInit();
467    }
468  }
469
470  // If this is a post initializer expression, initializing the region, we
471  // should track the initializer expression.
472  if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
473    const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
474    if (FieldReg && FieldReg == R) {
475      StoreSite = Pred;
476      InitE = PIP->getInitializer()->getInit();
477    }
478  }
479
480  // Otherwise, see if this is the store site:
481  // (1) Succ has this binding and Pred does not, i.e. this is
482  //     where the binding first occurred.
483  // (2) Succ has this binding and is a PostStore node for this region, i.e.
484  //     the same binding was re-assigned here.
485  if (!StoreSite) {
486    if (Succ->getState()->getSVal(R) != V)
487      return NULL;
488
489    if (Pred->getState()->getSVal(R) == V) {
490      Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
491      if (!PS || PS->getLocationValue() != R)
492        return NULL;
493    }
494
495    StoreSite = Succ;
496
497    // If this is an assignment expression, we can track the value
498    // being assigned.
499    if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
500      if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
501        if (BO->isAssignmentOp())
502          InitE = BO->getRHS();
503
504    // If this is a call entry, the variable should be a parameter.
505    // FIXME: Handle CXXThisRegion as well. (This is not a priority because
506    // 'this' should never be NULL, but this visitor isn't just for NULL and
507    // UndefinedVal.)
508    if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
509      if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
510        const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
511
512        ProgramStateManager &StateMgr = BRC.getStateManager();
513        CallEventManager &CallMgr = StateMgr.getCallEventManager();
514
515        CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
516                                                Succ->getState());
517        InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
518        IsParam = true;
519      }
520    }
521
522    // If this is a CXXTempObjectRegion, the Expr responsible for its creation
523    // is wrapped inside of it.
524    if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
525      InitE = TmpR->getExpr();
526  }
527
528  if (!StoreSite)
529    return NULL;
530  Satisfied = true;
531
532  // If we have an expression that provided the value, try to track where it
533  // came from.
534  if (InitE) {
535    if (V.isUndef() || V.getAs<loc::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 = 0;
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(new FindLastStoreBRVisitor(*KV, OriginalR,
572                                                      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 NULL;
706
707  return new PathDiagnosticEventPiece(L, os.str());
708}
709
710void 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.
719const char *TrackConstraintBRVisitor::getTag() {
720  return "TrackConstraintBRVisitor";
721}
722
723bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
724  if (IsZeroCheck)
725    return N->getState()->isNull(Constraint).isUnderconstrained();
726  return N->getState()->assume(Constraint, !Assumption);
727}
728
729PathDiagnosticPiece *
730TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
731                                    const ExplodedNode *PrevN,
732                                    BugReporterContext &BRC,
733                                    BugReport &BR) {
734  if (IsSatisfied)
735    return NULL;
736
737  // Start tracking after we see the first state in which the value is
738  // constrained.
739  if (!IsTrackingTurnedOn)
740    if (!isUnderconstrained(N))
741      IsTrackingTurnedOn = true;
742  if (!IsTrackingTurnedOn)
743    return 0;
744
745  // Check if in the previous state it was feasible for this constraint
746  // to *not* be true.
747  if (isUnderconstrained(PrevN)) {
748
749    IsSatisfied = true;
750
751    // As a sanity check, make sure that the negation of the constraint
752    // was infeasible in the current state.  If it is feasible, we somehow
753    // missed the transition point.
754    assert(!isUnderconstrained(N));
755
756    // We found the transition point for the constraint.  We now need to
757    // pretty-print the constraint. (work-in-progress)
758    SmallString<64> sbuf;
759    llvm::raw_svector_ostream os(sbuf);
760
761    if (Constraint.getAs<Loc>()) {
762      os << "Assuming pointer value is ";
763      os << (Assumption ? "non-null" : "null");
764    }
765
766    if (os.str().empty())
767      return NULL;
768
769    // Construct a new PathDiagnosticPiece.
770    ProgramPoint P = N->getLocation();
771    PathDiagnosticLocation L =
772      PathDiagnosticLocation::create(P, BRC.getSourceManager());
773    if (!L.isValid())
774      return NULL;
775
776    PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
777    X->setTag(getTag());
778    return X;
779  }
780
781  return NULL;
782}
783
784SuppressInlineDefensiveChecksVisitor::
785SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
786  : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
787
788    // Check if the visitor is disabled.
789    SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
790    assert(Eng && "Cannot file a bug report without an owning engine");
791    AnalyzerOptions &Options = Eng->getAnalysisManager().options;
792    if (!Options.shouldSuppressInlinedDefensiveChecks())
793      IsSatisfied = true;
794
795    assert(N->getState()->isNull(V).isConstrainedTrue() &&
796           "The visitor only tracks the cases where V is constrained to 0");
797}
798
799void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
800  static int id = 0;
801  ID.AddPointer(&id);
802  ID.Add(V);
803}
804
805const char *SuppressInlineDefensiveChecksVisitor::getTag() {
806  return "IDCVisitor";
807}
808
809PathDiagnosticPiece *
810SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
811                                                const ExplodedNode *Pred,
812                                                BugReporterContext &BRC,
813                                                BugReport &BR) {
814  if (IsSatisfied)
815    return 0;
816
817  // Start tracking after we see the first state in which the value is null.
818  if (!IsTrackingTurnedOn)
819    if (Succ->getState()->isNull(V).isConstrainedTrue())
820      IsTrackingTurnedOn = true;
821  if (!IsTrackingTurnedOn)
822    return 0;
823
824  // Check if in the previous state it was feasible for this value
825  // to *not* be null.
826  if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
827    IsSatisfied = true;
828
829    assert(Succ->getState()->isNull(V).isConstrainedTrue());
830
831    // Check if this is inlined defensive checks.
832    const LocationContext *CurLC =Succ->getLocationContext();
833    const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
834    if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
835      BR.markInvalid("Suppress IDC", CurLC);
836  }
837  return 0;
838}
839
840static const MemRegion *getLocationRegionIfReference(const Expr *E,
841                                                     const ExplodedNode *N) {
842  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
843    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
844      if (!VD->getType()->isReferenceType())
845        return 0;
846      ProgramStateManager &StateMgr = N->getState()->getStateManager();
847      MemRegionManager &MRMgr = StateMgr.getRegionManager();
848      return MRMgr.getVarRegion(VD, N->getLocationContext());
849    }
850  }
851
852  // FIXME: This does not handle other kinds of null references,
853  // for example, references from FieldRegions:
854  //   struct Wrapper { int &ref; };
855  //   Wrapper w = { *(int *)0 };
856  //   w.ref = 1;
857
858  return 0;
859}
860
861static const Expr *peelOffOuterExpr(const Expr *Ex,
862                                    const ExplodedNode *N) {
863  Ex = Ex->IgnoreParenCasts();
864  if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
865    return peelOffOuterExpr(EWC->getSubExpr(), N);
866  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
867    return peelOffOuterExpr(OVE->getSourceExpr(), N);
868
869  // Peel off the ternary operator.
870  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
871    // Find a node where the branching occured and find out which branch
872    // we took (true/false) by looking at the ExplodedGraph.
873    const ExplodedNode *NI = N;
874    do {
875      ProgramPoint ProgPoint = NI->getLocation();
876      if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
877        const CFGBlock *srcBlk = BE->getSrc();
878        if (const Stmt *term = srcBlk->getTerminator()) {
879          if (term == CO) {
880            bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
881            if (TookTrueBranch)
882              return peelOffOuterExpr(CO->getTrueExpr(), N);
883            else
884              return peelOffOuterExpr(CO->getFalseExpr(), N);
885          }
886        }
887      }
888      NI = NI->getFirstPred();
889    } while (NI);
890  }
891  return Ex;
892}
893
894bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
895                                        const Stmt *S,
896                                        BugReport &report, bool IsArg,
897                                        bool EnableNullFPSuppression) {
898  if (!S || !N)
899    return false;
900
901  if (const Expr *Ex = dyn_cast<Expr>(S)) {
902    Ex = Ex->IgnoreParenCasts();
903    const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
904    if (Ex != PeeledEx)
905      S = PeeledEx;
906  }
907
908  const Expr *Inner = 0;
909  if (const Expr *Ex = dyn_cast<Expr>(S)) {
910    Ex = Ex->IgnoreParenCasts();
911    if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
912      Inner = Ex;
913  }
914
915  if (IsArg && !Inner) {
916    assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
917  } else {
918    // Walk through nodes until we get one that matches the statement exactly.
919    // Alternately, if we hit a known lvalue for the statement, we know we've
920    // gone too far (though we can likely track the lvalue better anyway).
921    do {
922      const ProgramPoint &pp = N->getLocation();
923      if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
924        if (ps->getStmt() == S || ps->getStmt() == Inner)
925          break;
926      } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
927        if (CEE->getCalleeContext()->getCallSite() == S ||
928            CEE->getCalleeContext()->getCallSite() == Inner)
929          break;
930      }
931      N = N->getFirstPred();
932    } while (N);
933
934    if (!N)
935      return false;
936  }
937
938  ProgramStateRef state = N->getState();
939
940  // The message send could be nil due to the receiver being nil.
941  // At this point in the path, the receiver should be live since we are at the
942  // message send expr. If it is nil, start tracking it.
943  if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
944    trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
945
946
947  // See if the expression we're interested refers to a variable.
948  // If so, we can track both its contents and constraints on its value.
949  if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
950    const MemRegion *R = 0;
951
952    // Find the ExplodedNode where the lvalue (the value of 'Ex')
953    // was computed.  We need this for getting the location value.
954    const ExplodedNode *LVNode = N;
955    while (LVNode) {
956      if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
957        if (P->getStmt() == Inner)
958          break;
959      }
960      LVNode = LVNode->getFirstPred();
961    }
962    assert(LVNode && "Unable to find the lvalue node.");
963    ProgramStateRef LVState = LVNode->getState();
964    SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
965
966    if (LVState->isNull(LVal).isConstrainedTrue()) {
967      // In case of C++ references, we want to differentiate between a null
968      // reference and reference to null pointer.
969      // If the LVal is null, check if we are dealing with null reference.
970      // For those, we want to track the location of the reference.
971      if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
972        R = RR;
973    } else {
974      R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
975
976      // If this is a C++ reference to a null pointer, we are tracking the
977      // pointer. In additon, we should find the store at which the reference
978      // got initialized.
979      if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
980        if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
981          report.addVisitor(new FindLastStoreBRVisitor(*KV, RR,
982                                                      EnableNullFPSuppression));
983      }
984    }
985
986    if (R) {
987      // Mark both the variable region and its contents as interesting.
988      SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
989
990      report.markInteresting(R);
991      report.markInteresting(V);
992      report.addVisitor(new UndefOrNullArgVisitor(R));
993
994      // If the contents are symbolic, find out when they became null.
995      if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true)) {
996        BugReporterVisitor *ConstraintTracker =
997          new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
998        report.addVisitor(ConstraintTracker);
999
1000        // Add visitor, which will suppress inline defensive checks.
1001        if (LVState->isNull(V).isConstrainedTrue() &&
1002            EnableNullFPSuppression) {
1003          BugReporterVisitor *IDCSuppressor =
1004            new SuppressInlineDefensiveChecksVisitor(V.castAs<DefinedSVal>(),
1005                                                     LVNode);
1006          report.addVisitor(IDCSuppressor);
1007        }
1008      }
1009
1010      if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1011        report.addVisitor(new FindLastStoreBRVisitor(*KV, R,
1012                                                     EnableNullFPSuppression));
1013      return true;
1014    }
1015  }
1016
1017  // If the expression is not an "lvalue expression", we can still
1018  // track the constraints on its contents.
1019  SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1020
1021  // If the value came from an inlined function call, we should at least make
1022  // sure that function isn't pruned in our output.
1023  if (const Expr *E = dyn_cast<Expr>(S))
1024    S = E->IgnoreParenCasts();
1025
1026  ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1027
1028  // Uncomment this to find cases where we aren't properly getting the
1029  // base value that was dereferenced.
1030  // assert(!V.isUnknownOrUndef());
1031  // Is it a symbolic value?
1032  if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1033    // At this point we are dealing with the region's LValue.
1034    // However, if the rvalue is a symbolic region, we should track it as well.
1035    // Try to use the correct type when looking up the value.
1036    SVal RVal;
1037    if (const Expr *E = dyn_cast<Expr>(S))
1038      RVal = state->getRawSVal(L.getValue(), E->getType());
1039    else
1040      RVal = state->getSVal(L->getRegion());
1041
1042    const MemRegion *RegionRVal = RVal.getAsRegion();
1043    report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
1044
1045    if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1046      report.markInteresting(RegionRVal);
1047      report.addVisitor(new TrackConstraintBRVisitor(
1048        loc::MemRegionVal(RegionRVal), false));
1049    }
1050  }
1051
1052  return true;
1053}
1054
1055const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1056                                                 const ExplodedNode *N) {
1057  const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1058  if (!ME)
1059    return 0;
1060  if (const Expr *Receiver = ME->getInstanceReceiver()) {
1061    ProgramStateRef state = N->getState();
1062    SVal V = state->getSVal(Receiver, N->getLocationContext());
1063    if (state->isNull(V).isConstrainedTrue())
1064      return Receiver;
1065  }
1066  return 0;
1067}
1068
1069PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1070                                                     const ExplodedNode *PrevN,
1071                                                     BugReporterContext &BRC,
1072                                                     BugReport &BR) {
1073  Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1074  if (!P)
1075    return 0;
1076
1077  const Stmt *S = P->getStmt();
1078  const Expr *Receiver = getNilReceiver(S, N);
1079  if (!Receiver)
1080    return 0;
1081
1082  llvm::SmallString<256> Buf;
1083  llvm::raw_svector_ostream OS(Buf);
1084
1085  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1086    OS << "'" << ME->getSelector().getAsString() << "' not called";
1087  }
1088  else {
1089    OS << "No method is called";
1090  }
1091  OS << " because the receiver is nil";
1092
1093  // The receiver was nil, and hence the method was skipped.
1094  // Register a BugReporterVisitor to issue a message telling us how
1095  // the receiver was null.
1096  bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1097                                     /*EnableNullFPSuppression*/ false);
1098  // Issue a message saying that the method was skipped.
1099  PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1100                                     N->getLocationContext());
1101  return new PathDiagnosticEventPiece(L, OS.str());
1102}
1103
1104// Registers every VarDecl inside a Stmt with a last store visitor.
1105void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1106                                                const Stmt *S,
1107                                                bool EnableNullFPSuppression) {
1108  const ExplodedNode *N = BR.getErrorNode();
1109  std::deque<const Stmt *> WorkList;
1110  WorkList.push_back(S);
1111
1112  while (!WorkList.empty()) {
1113    const Stmt *Head = WorkList.front();
1114    WorkList.pop_front();
1115
1116    ProgramStateRef state = N->getState();
1117    ProgramStateManager &StateMgr = state->getStateManager();
1118
1119    if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1120      if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1121        const VarRegion *R =
1122        StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1123
1124        // What did we load?
1125        SVal V = state->getSVal(S, N->getLocationContext());
1126
1127        if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1128          // Register a new visitor with the BugReport.
1129          BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R,
1130                                                   EnableNullFPSuppression));
1131        }
1132      }
1133    }
1134
1135    for (Stmt::const_child_iterator I = Head->child_begin();
1136        I != Head->child_end(); ++I)
1137      WorkList.push_back(*I);
1138  }
1139}
1140
1141//===----------------------------------------------------------------------===//
1142// Visitor that tries to report interesting diagnostics from conditions.
1143//===----------------------------------------------------------------------===//
1144
1145/// Return the tag associated with this visitor.  This tag will be used
1146/// to make all PathDiagnosticPieces created by this visitor.
1147const char *ConditionBRVisitor::getTag() {
1148  return "ConditionBRVisitor";
1149}
1150
1151PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1152                                                   const ExplodedNode *Prev,
1153                                                   BugReporterContext &BRC,
1154                                                   BugReport &BR) {
1155  PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1156  if (piece) {
1157    piece->setTag(getTag());
1158    if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1159      ev->setPrunable(true, /* override */ false);
1160  }
1161  return piece;
1162}
1163
1164PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1165                                                       const ExplodedNode *Prev,
1166                                                       BugReporterContext &BRC,
1167                                                       BugReport &BR) {
1168
1169  ProgramPoint progPoint = N->getLocation();
1170  ProgramStateRef CurrentState = N->getState();
1171  ProgramStateRef PrevState = Prev->getState();
1172
1173  // Compare the GDMs of the state, because that is where constraints
1174  // are managed.  Note that ensure that we only look at nodes that
1175  // were generated by the analyzer engine proper, not checkers.
1176  if (CurrentState->getGDM().getRoot() ==
1177      PrevState->getGDM().getRoot())
1178    return 0;
1179
1180  // If an assumption was made on a branch, it should be caught
1181  // here by looking at the state transition.
1182  if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1183    const CFGBlock *srcBlk = BE->getSrc();
1184    if (const Stmt *term = srcBlk->getTerminator())
1185      return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1186    return 0;
1187  }
1188
1189  if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1190    // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1191    // violation.
1192    const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1193      cast<GRBugReporter>(BRC.getBugReporter()).
1194        getEngine().geteagerlyAssumeBinOpBifurcationTags();
1195
1196    const ProgramPointTag *tag = PS->getTag();
1197    if (tag == tags.first)
1198      return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1199                           BRC, BR, N);
1200    if (tag == tags.second)
1201      return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1202                           BRC, BR, N);
1203
1204    return 0;
1205  }
1206
1207  return 0;
1208}
1209
1210PathDiagnosticPiece *
1211ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1212                                    const ExplodedNode *N,
1213                                    const CFGBlock *srcBlk,
1214                                    const CFGBlock *dstBlk,
1215                                    BugReport &R,
1216                                    BugReporterContext &BRC) {
1217  const Expr *Cond = 0;
1218
1219  switch (Term->getStmtClass()) {
1220  default:
1221    return 0;
1222  case Stmt::IfStmtClass:
1223    Cond = cast<IfStmt>(Term)->getCond();
1224    break;
1225  case Stmt::ConditionalOperatorClass:
1226    Cond = cast<ConditionalOperator>(Term)->getCond();
1227    break;
1228  }
1229
1230  assert(Cond);
1231  assert(srcBlk->succ_size() == 2);
1232  const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1233  return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1234}
1235
1236PathDiagnosticPiece *
1237ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1238                                  bool tookTrue,
1239                                  BugReporterContext &BRC,
1240                                  BugReport &R,
1241                                  const ExplodedNode *N) {
1242
1243  const Expr *Ex = Cond;
1244
1245  while (true) {
1246    Ex = Ex->IgnoreParenCasts();
1247    switch (Ex->getStmtClass()) {
1248      default:
1249        return 0;
1250      case Stmt::BinaryOperatorClass:
1251        return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1252                             R, N);
1253      case Stmt::DeclRefExprClass:
1254        return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1255                             R, N);
1256      case Stmt::UnaryOperatorClass: {
1257        const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1258        if (UO->getOpcode() == UO_LNot) {
1259          tookTrue = !tookTrue;
1260          Ex = UO->getSubExpr();
1261          continue;
1262        }
1263        return 0;
1264      }
1265    }
1266  }
1267}
1268
1269bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1270                                      BugReporterContext &BRC,
1271                                      BugReport &report,
1272                                      const ExplodedNode *N,
1273                                      Optional<bool> &prunable) {
1274  const Expr *OriginalExpr = Ex;
1275  Ex = Ex->IgnoreParenCasts();
1276
1277  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1278    const bool quotes = isa<VarDecl>(DR->getDecl());
1279    if (quotes) {
1280      Out << '\'';
1281      const LocationContext *LCtx = N->getLocationContext();
1282      const ProgramState *state = N->getState().getPtr();
1283      if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1284                                                LCtx).getAsRegion()) {
1285        if (report.isInteresting(R))
1286          prunable = false;
1287        else {
1288          const ProgramState *state = N->getState().getPtr();
1289          SVal V = state->getSVal(R);
1290          if (report.isInteresting(V))
1291            prunable = false;
1292        }
1293      }
1294    }
1295    Out << DR->getDecl()->getDeclName().getAsString();
1296    if (quotes)
1297      Out << '\'';
1298    return quotes;
1299  }
1300
1301  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1302    QualType OriginalTy = OriginalExpr->getType();
1303    if (OriginalTy->isPointerType()) {
1304      if (IL->getValue() == 0) {
1305        Out << "null";
1306        return false;
1307      }
1308    }
1309    else if (OriginalTy->isObjCObjectPointerType()) {
1310      if (IL->getValue() == 0) {
1311        Out << "nil";
1312        return false;
1313      }
1314    }
1315
1316    Out << IL->getValue();
1317    return false;
1318  }
1319
1320  return false;
1321}
1322
1323PathDiagnosticPiece *
1324ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1325                                  const BinaryOperator *BExpr,
1326                                  const bool tookTrue,
1327                                  BugReporterContext &BRC,
1328                                  BugReport &R,
1329                                  const ExplodedNode *N) {
1330
1331  bool shouldInvert = false;
1332  Optional<bool> shouldPrune;
1333
1334  SmallString<128> LhsString, RhsString;
1335  {
1336    llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1337    const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1338                                       shouldPrune);
1339    const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1340                                       shouldPrune);
1341
1342    shouldInvert = !isVarLHS && isVarRHS;
1343  }
1344
1345  BinaryOperator::Opcode Op = BExpr->getOpcode();
1346
1347  if (BinaryOperator::isAssignmentOp(Op)) {
1348    // For assignment operators, all that we care about is that the LHS
1349    // evaluates to "true" or "false".
1350    return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1351                                  BRC, R, N);
1352  }
1353
1354  // For non-assignment operations, we require that we can understand
1355  // both the LHS and RHS.
1356  if (LhsString.empty() || RhsString.empty())
1357    return 0;
1358
1359  // Should we invert the strings if the LHS is not a variable name?
1360  SmallString<256> buf;
1361  llvm::raw_svector_ostream Out(buf);
1362  Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1363
1364  // Do we need to invert the opcode?
1365  if (shouldInvert)
1366    switch (Op) {
1367      default: break;
1368      case BO_LT: Op = BO_GT; break;
1369      case BO_GT: Op = BO_LT; break;
1370      case BO_LE: Op = BO_GE; break;
1371      case BO_GE: Op = BO_LE; break;
1372    }
1373
1374  if (!tookTrue)
1375    switch (Op) {
1376      case BO_EQ: Op = BO_NE; break;
1377      case BO_NE: Op = BO_EQ; break;
1378      case BO_LT: Op = BO_GE; break;
1379      case BO_GT: Op = BO_LE; break;
1380      case BO_LE: Op = BO_GT; break;
1381      case BO_GE: Op = BO_LT; break;
1382      default:
1383        return 0;
1384    }
1385
1386  switch (Op) {
1387    case BO_EQ:
1388      Out << "equal to ";
1389      break;
1390    case BO_NE:
1391      Out << "not equal to ";
1392      break;
1393    default:
1394      Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1395      break;
1396  }
1397
1398  Out << (shouldInvert ? LhsString : RhsString);
1399  const LocationContext *LCtx = N->getLocationContext();
1400  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1401  PathDiagnosticEventPiece *event =
1402    new PathDiagnosticEventPiece(Loc, Out.str());
1403  if (shouldPrune.hasValue())
1404    event->setPrunable(shouldPrune.getValue());
1405  return event;
1406}
1407
1408PathDiagnosticPiece *
1409ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1410                                           const Expr *CondVarExpr,
1411                                           const bool tookTrue,
1412                                           BugReporterContext &BRC,
1413                                           BugReport &report,
1414                                           const ExplodedNode *N) {
1415  // FIXME: If there's already a constraint tracker for this variable,
1416  // we shouldn't emit anything here (c.f. the double note in
1417  // test/Analysis/inlining/path-notes.c)
1418  SmallString<256> buf;
1419  llvm::raw_svector_ostream Out(buf);
1420  Out << "Assuming " << LhsString << " is ";
1421
1422  QualType Ty = CondVarExpr->getType();
1423
1424  if (Ty->isPointerType())
1425    Out << (tookTrue ? "not null" : "null");
1426  else if (Ty->isObjCObjectPointerType())
1427    Out << (tookTrue ? "not nil" : "nil");
1428  else if (Ty->isBooleanType())
1429    Out << (tookTrue ? "true" : "false");
1430  else if (Ty->isIntegralOrEnumerationType())
1431    Out << (tookTrue ? "non-zero" : "zero");
1432  else
1433    return 0;
1434
1435  const LocationContext *LCtx = N->getLocationContext();
1436  PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1437  PathDiagnosticEventPiece *event =
1438    new PathDiagnosticEventPiece(Loc, Out.str());
1439
1440  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1441    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1442      const ProgramState *state = N->getState().getPtr();
1443      if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1444        if (report.isInteresting(R))
1445          event->setPrunable(false);
1446      }
1447    }
1448  }
1449
1450  return event;
1451}
1452
1453PathDiagnosticPiece *
1454ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1455                                  const DeclRefExpr *DR,
1456                                  const bool tookTrue,
1457                                  BugReporterContext &BRC,
1458                                  BugReport &report,
1459                                  const ExplodedNode *N) {
1460
1461  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1462  if (!VD)
1463    return 0;
1464
1465  SmallString<256> Buf;
1466  llvm::raw_svector_ostream Out(Buf);
1467
1468  Out << "Assuming '" << VD->getDeclName() << "' is ";
1469
1470  QualType VDTy = VD->getType();
1471
1472  if (VDTy->isPointerType())
1473    Out << (tookTrue ? "non-null" : "null");
1474  else if (VDTy->isObjCObjectPointerType())
1475    Out << (tookTrue ? "non-nil" : "nil");
1476  else if (VDTy->isScalarType())
1477    Out << (tookTrue ? "not equal to 0" : "0");
1478  else
1479    return 0;
1480
1481  const LocationContext *LCtx = N->getLocationContext();
1482  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1483  PathDiagnosticEventPiece *event =
1484    new PathDiagnosticEventPiece(Loc, Out.str());
1485
1486  const ProgramState *state = N->getState().getPtr();
1487  if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1488    if (report.isInteresting(R))
1489      event->setPrunable(false);
1490    else {
1491      SVal V = state->getSVal(R);
1492      if (report.isInteresting(V))
1493        event->setPrunable(false);
1494    }
1495  }
1496  return event;
1497}
1498
1499
1500// FIXME: Copied from ExprEngineCallAndReturn.cpp.
1501static bool isInStdNamespace(const Decl *D) {
1502  const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
1503  const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
1504  if (!ND)
1505    return false;
1506
1507  while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
1508    ND = Parent;
1509
1510  return ND->getName() == "std";
1511}
1512
1513
1514PathDiagnosticPiece *
1515LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1516                                                    const ExplodedNode *N,
1517                                                    BugReport &BR) {
1518  // Here we suppress false positives coming from system headers. This list is
1519  // based on known issues.
1520
1521  // Skip reports within the 'std' namespace. Although these can sometimes be
1522  // the user's fault, we currently don't report them very well, and
1523  // Note that this will not help for any other data structure libraries, like
1524  // TR1, Boost, or llvm/ADT.
1525  ExprEngine &Eng = BRC.getBugReporter().getEngine();
1526  AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1527  if (Options.shouldSuppressFromCXXStandardLibrary()) {
1528    const LocationContext *LCtx = N->getLocationContext();
1529    if (isInStdNamespace(LCtx->getDecl())) {
1530      BR.markInvalid(getTag(), 0);
1531      return 0;
1532    }
1533  }
1534
1535  // Skip reports within the sys/queue.h macros as we do not have the ability to
1536  // reason about data structure shapes.
1537  SourceManager &SM = BRC.getSourceManager();
1538  FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1539  while (Loc.isMacroID()) {
1540    Loc = Loc.getSpellingLoc();
1541    if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1542      BR.markInvalid(getTag(), 0);
1543      return 0;
1544    }
1545  }
1546
1547  return 0;
1548}
1549
1550PathDiagnosticPiece *
1551UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1552                                  const ExplodedNode *PrevN,
1553                                  BugReporterContext &BRC,
1554                                  BugReport &BR) {
1555
1556  ProgramStateRef State = N->getState();
1557  ProgramPoint ProgLoc = N->getLocation();
1558
1559  // We are only interested in visiting CallEnter nodes.
1560  Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1561  if (!CEnter)
1562    return 0;
1563
1564  // Check if one of the arguments is the region the visitor is tracking.
1565  CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1566  CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1567  unsigned Idx = 0;
1568  for (CallEvent::param_iterator I = Call->param_begin(),
1569                                 E = Call->param_end(); I != E; ++I, ++Idx) {
1570    const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1571
1572    // Are we tracking the argument or its subregion?
1573    if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1574      continue;
1575
1576    // Check the function parameter type.
1577    const ParmVarDecl *ParamDecl = *I;
1578    assert(ParamDecl && "Formal parameter has no decl?");
1579    QualType T = ParamDecl->getType();
1580
1581    if (!(T->isAnyPointerType() || T->isReferenceType())) {
1582      // Function can only change the value passed in by address.
1583      continue;
1584    }
1585
1586    // If it is a const pointer value, the function does not intend to
1587    // change the value.
1588    if (T->getPointeeType().isConstQualified())
1589      continue;
1590
1591    // Mark the call site (LocationContext) as interesting if the value of the
1592    // argument is undefined or '0'/'NULL'.
1593    SVal BoundVal = State->getSVal(R);
1594    if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1595      BR.markInteresting(CEnter->getCalleeContext());
1596      return 0;
1597    }
1598  }
1599  return 0;
1600}
1601