1 //===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines BugReporter, a utility class for generating
10 //  PathDiagnostics.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ParentMap.h"
21 #include "clang/AST/Stmt.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/Analysis/AnalysisDeclContext.h"
25 #include "clang/Analysis/CFG.h"
26 #include "clang/Analysis/CFGStmtMap.h"
27 #include "clang/Analysis/PathDiagnostic.h"
28 #include "clang/Analysis/ProgramPoint.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
33 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
34 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
35 #include "clang/StaticAnalyzer/Core/Checker.h"
36 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
37 #include "clang/StaticAnalyzer/Core/CheckerRegistryData.h"
38 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
39 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
40 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/DenseSet.h"
48 #include "llvm/ADT/FoldingSet.h"
49 #include "llvm/ADT/None.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/SmallPtrSet.h"
53 #include "llvm/ADT/SmallString.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/ADT/iterator_range.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/MemoryBuffer.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include <algorithm>
65 #include <cassert>
66 #include <cstddef>
67 #include <iterator>
68 #include <memory>
69 #include <queue>
70 #include <string>
71 #include <tuple>
72 #include <utility>
73 #include <vector>
74 
75 using namespace clang;
76 using namespace ento;
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "BugReporter"
80 
81 STATISTIC(MaxBugClassSize,
82           "The maximum number of bug reports in the same equivalence class");
83 STATISTIC(MaxValidBugClassSize,
84           "The maximum number of bug reports in the same equivalence class "
85           "where at least one report is valid (not suppressed)");
86 
87 BugReporterVisitor::~BugReporterVisitor() = default;
88 
89 void BugReporterContext::anchor() {}
90 
91 //===----------------------------------------------------------------------===//
92 // PathDiagnosticBuilder and its associated routines and helper objects.
93 //===----------------------------------------------------------------------===//
94 
95 namespace {
96 
97 /// A (CallPiece, node assiciated with its CallEnter) pair.
98 using CallWithEntry =
99     std::pair<PathDiagnosticCallPiece *, const ExplodedNode *>;
100 using CallWithEntryStack = SmallVector<CallWithEntry, 6>;
101 
102 /// Map from each node to the diagnostic pieces visitors emit for them.
103 using VisitorsDiagnosticsTy =
104     llvm::DenseMap<const ExplodedNode *, std::vector<PathDiagnosticPieceRef>>;
105 
106 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
107 /// function call it represents.
108 using LocationContextMap =
109     llvm::DenseMap<const PathPieces *, const LocationContext *>;
110 
111 /// A helper class that contains everything needed to construct a
112 /// PathDiagnostic object. It does no much more then providing convenient
113 /// getters and some well placed asserts for extra security.
114 class PathDiagnosticConstruct {
115   /// The consumer we're constructing the bug report for.
116   const PathDiagnosticConsumer *Consumer;
117   /// Our current position in the bug path, which is owned by
118   /// PathDiagnosticBuilder.
119   const ExplodedNode *CurrentNode;
120   /// A mapping from parts of the bug path (for example, a function call, which
121   /// would span backwards from a CallExit to a CallEnter with the nodes in
122   /// between them) with the location contexts it is associated with.
123   LocationContextMap LCM;
124   const SourceManager &SM;
125 
126 public:
127   /// We keep stack of calls to functions as we're ascending the bug path.
128   /// TODO: PathDiagnostic has a stack doing the same thing, shouldn't we use
129   /// that instead?
130   CallWithEntryStack CallStack;
131   /// The bug report we're constructing. For ease of use, this field is kept
132   /// public, though some "shortcut" getters are provided for commonly used
133   /// methods of PathDiagnostic.
134   std::unique_ptr<PathDiagnostic> PD;
135 
136 public:
137   PathDiagnosticConstruct(const PathDiagnosticConsumer *PDC,
138                           const ExplodedNode *ErrorNode,
139                           const PathSensitiveBugReport *R);
140 
141   /// \returns the location context associated with the current position in the
142   /// bug path.
143   const LocationContext *getCurrLocationContext() const {
144     assert(CurrentNode && "Already reached the root!");
145     return CurrentNode->getLocationContext();
146   }
147 
148   /// Same as getCurrLocationContext (they should always return the same
149   /// location context), but works after reaching the root of the bug path as
150   /// well.
151   const LocationContext *getLocationContextForActivePath() const {
152     return LCM.find(&PD->getActivePath())->getSecond();
153   }
154 
155   const ExplodedNode *getCurrentNode() const { return CurrentNode; }
156 
157   /// Steps the current node to its predecessor.
158   /// \returns whether we reached the root of the bug path.
159   bool ascendToPrevNode() {
160     CurrentNode = CurrentNode->getFirstPred();
161     return static_cast<bool>(CurrentNode);
162   }
163 
164   const ParentMap &getParentMap() const {
165     return getCurrLocationContext()->getParentMap();
166   }
167 
168   const SourceManager &getSourceManager() const { return SM; }
169 
170   const Stmt *getParent(const Stmt *S) const {
171     return getParentMap().getParent(S);
172   }
173 
174   void updateLocCtxMap(const PathPieces *Path, const LocationContext *LC) {
175     assert(Path && LC);
176     LCM[Path] = LC;
177   }
178 
179   const LocationContext *getLocationContextFor(const PathPieces *Path) const {
180     assert(LCM.count(Path) &&
181            "Failed to find the context associated with these pieces!");
182     return LCM.find(Path)->getSecond();
183   }
184 
185   bool isInLocCtxMap(const PathPieces *Path) const { return LCM.count(Path); }
186 
187   PathPieces &getActivePath() { return PD->getActivePath(); }
188   PathPieces &getMutablePieces() { return PD->getMutablePieces(); }
189 
190   bool shouldAddPathEdges() const { return Consumer->shouldAddPathEdges(); }
191   bool shouldAddControlNotes() const {
192     return Consumer->shouldAddControlNotes();
193   }
194   bool shouldGenerateDiagnostics() const {
195     return Consumer->shouldGenerateDiagnostics();
196   }
197   bool supportsLogicalOpControlFlow() const {
198     return Consumer->supportsLogicalOpControlFlow();
199   }
200 };
201 
202 /// Contains every contextual information needed for constructing a
203 /// PathDiagnostic object for a given bug report. This class and its fields are
204 /// immutable, and passes a BugReportConstruct object around during the
205 /// construction.
206 class PathDiagnosticBuilder : public BugReporterContext {
207   /// A linear path from the error node to the root.
208   std::unique_ptr<const ExplodedGraph> BugPath;
209   /// The bug report we're describing. Visitors create their diagnostics with
210   /// them being the last entities being able to modify it (for example,
211   /// changing interestingness here would cause inconsistencies as to how this
212   /// file and visitors construct diagnostics), hence its const.
213   const PathSensitiveBugReport *R;
214   /// The leaf of the bug path. This isn't the same as the bug reports error
215   /// node, which refers to the *original* graph, not the bug path.
216   const ExplodedNode *const ErrorNode;
217   /// The diagnostic pieces visitors emitted, which is expected to be collected
218   /// by the time this builder is constructed.
219   std::unique_ptr<const VisitorsDiagnosticsTy> VisitorsDiagnostics;
220 
221 public:
222   /// Find a non-invalidated report for a given equivalence class,  and returns
223   /// a PathDiagnosticBuilder able to construct bug reports for different
224   /// consumers. Returns None if no valid report is found.
225   static Optional<PathDiagnosticBuilder>
226   findValidReport(ArrayRef<PathSensitiveBugReport *> &bugReports,
227                   PathSensitiveBugReporter &Reporter);
228 
229   PathDiagnosticBuilder(
230       BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
231       PathSensitiveBugReport *r, const ExplodedNode *ErrorNode,
232       std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics);
233 
234   /// This function is responsible for generating diagnostic pieces that are
235   /// *not* provided by bug report visitors.
236   /// These diagnostics may differ depending on the consumer's settings,
237   /// and are therefore constructed separately for each consumer.
238   ///
239   /// There are two path diagnostics generation modes: with adding edges (used
240   /// for plists) and without  (used for HTML and text). When edges are added,
241   /// the path is modified to insert artificially generated edges.
242   /// Otherwise, more detailed diagnostics is emitted for block edges,
243   /// explaining the transitions in words.
244   std::unique_ptr<PathDiagnostic>
245   generate(const PathDiagnosticConsumer *PDC) const;
246 
247 private:
248   void updateStackPiecesWithMessage(PathDiagnosticPieceRef P,
249                                     const CallWithEntryStack &CallStack) const;
250   void generatePathDiagnosticsForNode(PathDiagnosticConstruct &C,
251                                       PathDiagnosticLocation &PrevLoc) const;
252 
253   void generateMinimalDiagForBlockEdge(PathDiagnosticConstruct &C,
254                                        BlockEdge BE) const;
255 
256   PathDiagnosticPieceRef
257   generateDiagForGotoOP(const PathDiagnosticConstruct &C, const Stmt *S,
258                         PathDiagnosticLocation &Start) const;
259 
260   PathDiagnosticPieceRef
261   generateDiagForSwitchOP(const PathDiagnosticConstruct &C, const CFGBlock *Dst,
262                           PathDiagnosticLocation &Start) const;
263 
264   PathDiagnosticPieceRef
265   generateDiagForBinaryOP(const PathDiagnosticConstruct &C, const Stmt *T,
266                           const CFGBlock *Src, const CFGBlock *DstC) const;
267 
268   PathDiagnosticLocation
269   ExecutionContinues(const PathDiagnosticConstruct &C) const;
270 
271   PathDiagnosticLocation
272   ExecutionContinues(llvm::raw_string_ostream &os,
273                      const PathDiagnosticConstruct &C) const;
274 
275   const PathSensitiveBugReport *getBugReport() const { return R; }
276 };
277 
278 } // namespace
279 
280 //===----------------------------------------------------------------------===//
281 // Base implementation of stack hint generators.
282 //===----------------------------------------------------------------------===//
283 
284 StackHintGenerator::~StackHintGenerator() = default;
285 
286 std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
287   if (!N)
288     return getMessageForSymbolNotFound();
289 
290   ProgramPoint P = N->getLocation();
291   CallExitEnd CExit = P.castAs<CallExitEnd>();
292 
293   // FIXME: Use CallEvent to abstract this over all calls.
294   const Stmt *CallSite = CExit.getCalleeContext()->getCallSite();
295   const auto *CE = dyn_cast_or_null<CallExpr>(CallSite);
296   if (!CE)
297     return {};
298 
299   // Check if one of the parameters are set to the interesting symbol.
300   unsigned ArgIndex = 0;
301   for (CallExpr::const_arg_iterator I = CE->arg_begin(),
302                                     E = CE->arg_end(); I != E; ++I, ++ArgIndex){
303     SVal SV = N->getSVal(*I);
304 
305     // Check if the variable corresponding to the symbol is passed by value.
306     SymbolRef AS = SV.getAsLocSymbol();
307     if (AS == Sym) {
308       return getMessageForArg(*I, ArgIndex);
309     }
310 
311     // Check if the parameter is a pointer to the symbol.
312     if (Optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
313       // Do not attempt to dereference void*.
314       if ((*I)->getType()->isVoidPointerType())
315         continue;
316       SVal PSV = N->getState()->getSVal(Reg->getRegion());
317       SymbolRef AS = PSV.getAsLocSymbol();
318       if (AS == Sym) {
319         return getMessageForArg(*I, ArgIndex);
320       }
321     }
322   }
323 
324   // Check if we are returning the interesting symbol.
325   SVal SV = N->getSVal(CE);
326   SymbolRef RetSym = SV.getAsLocSymbol();
327   if (RetSym == Sym) {
328     return getMessageForReturn(CE);
329   }
330 
331   return getMessageForSymbolNotFound();
332 }
333 
334 std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
335                                                           unsigned ArgIndex) {
336   // Printed parameters start at 1, not 0.
337   ++ArgIndex;
338 
339   return (llvm::Twine(Msg) + " via " + std::to_string(ArgIndex) +
340           llvm::getOrdinalSuffix(ArgIndex) + " parameter").str();
341 }
342 
343 //===----------------------------------------------------------------------===//
344 // Diagnostic cleanup.
345 //===----------------------------------------------------------------------===//
346 
347 static PathDiagnosticEventPiece *
348 eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
349                             PathDiagnosticEventPiece *Y) {
350   // Prefer diagnostics that come from ConditionBRVisitor over
351   // those that came from TrackConstraintBRVisitor,
352   // unless the one from ConditionBRVisitor is
353   // its generic fallback diagnostic.
354   const void *tagPreferred = ConditionBRVisitor::getTag();
355   const void *tagLesser = TrackConstraintBRVisitor::getTag();
356 
357   if (X->getLocation() != Y->getLocation())
358     return nullptr;
359 
360   if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
361     return ConditionBRVisitor::isPieceMessageGeneric(X) ? Y : X;
362 
363   if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
364     return ConditionBRVisitor::isPieceMessageGeneric(Y) ? X : Y;
365 
366   return nullptr;
367 }
368 
369 /// An optimization pass over PathPieces that removes redundant diagnostics
370 /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor.  Both
371 /// BugReporterVisitors use different methods to generate diagnostics, with
372 /// one capable of emitting diagnostics in some cases but not in others.  This
373 /// can lead to redundant diagnostic pieces at the same point in a path.
374 static void removeRedundantMsgs(PathPieces &path) {
375   unsigned N = path.size();
376   if (N < 2)
377     return;
378   // NOTE: this loop intentionally is not using an iterator.  Instead, we
379   // are streaming the path and modifying it in place.  This is done by
380   // grabbing the front, processing it, and if we decide to keep it append
381   // it to the end of the path.  The entire path is processed in this way.
382   for (unsigned i = 0; i < N; ++i) {
383     auto piece = std::move(path.front());
384     path.pop_front();
385 
386     switch (piece->getKind()) {
387       case PathDiagnosticPiece::Call:
388         removeRedundantMsgs(cast<PathDiagnosticCallPiece>(*piece).path);
389         break;
390       case PathDiagnosticPiece::Macro:
391         removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(*piece).subPieces);
392         break;
393       case PathDiagnosticPiece::Event: {
394         if (i == N-1)
395           break;
396 
397         if (auto *nextEvent =
398             dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
399           auto *event = cast<PathDiagnosticEventPiece>(piece.get());
400           // Check to see if we should keep one of the two pieces.  If we
401           // come up with a preference, record which piece to keep, and consume
402           // another piece from the path.
403           if (auto *pieceToKeep =
404                   eventsDescribeSameCondition(event, nextEvent)) {
405             piece = std::move(pieceToKeep == event ? piece : path.front());
406             path.pop_front();
407             ++i;
408           }
409         }
410         break;
411       }
412       case PathDiagnosticPiece::ControlFlow:
413       case PathDiagnosticPiece::Note:
414       case PathDiagnosticPiece::PopUp:
415         break;
416     }
417     path.push_back(std::move(piece));
418   }
419 }
420 
421 /// Recursively scan through a path and prune out calls and macros pieces
422 /// that aren't needed.  Return true if afterwards the path contains
423 /// "interesting stuff" which means it shouldn't be pruned from the parent path.
424 static bool removeUnneededCalls(const PathDiagnosticConstruct &C,
425                                 PathPieces &pieces,
426                                 const PathSensitiveBugReport *R,
427                                 bool IsInteresting = false) {
428   bool containsSomethingInteresting = IsInteresting;
429   const unsigned N = pieces.size();
430 
431   for (unsigned i = 0 ; i < N ; ++i) {
432     // Remove the front piece from the path.  If it is still something we
433     // want to keep once we are done, we will push it back on the end.
434     auto piece = std::move(pieces.front());
435     pieces.pop_front();
436 
437     switch (piece->getKind()) {
438       case PathDiagnosticPiece::Call: {
439         auto &call = cast<PathDiagnosticCallPiece>(*piece);
440         // Check if the location context is interesting.
441         if (!removeUnneededCalls(
442                 C, call.path, R,
443                 R->isInteresting(C.getLocationContextFor(&call.path))))
444           continue;
445 
446         containsSomethingInteresting = true;
447         break;
448       }
449       case PathDiagnosticPiece::Macro: {
450         auto &macro = cast<PathDiagnosticMacroPiece>(*piece);
451         if (!removeUnneededCalls(C, macro.subPieces, R, IsInteresting))
452           continue;
453         containsSomethingInteresting = true;
454         break;
455       }
456       case PathDiagnosticPiece::Event: {
457         auto &event = cast<PathDiagnosticEventPiece>(*piece);
458 
459         // We never throw away an event, but we do throw it away wholesale
460         // as part of a path if we throw the entire path away.
461         containsSomethingInteresting |= !event.isPrunable();
462         break;
463       }
464       case PathDiagnosticPiece::ControlFlow:
465       case PathDiagnosticPiece::Note:
466       case PathDiagnosticPiece::PopUp:
467         break;
468     }
469 
470     pieces.push_back(std::move(piece));
471   }
472 
473   return containsSomethingInteresting;
474 }
475 
476 /// Same logic as above to remove extra pieces.
477 static void removePopUpNotes(PathPieces &Path) {
478   for (unsigned int i = 0; i < Path.size(); ++i) {
479     auto Piece = std::move(Path.front());
480     Path.pop_front();
481     if (!isa<PathDiagnosticPopUpPiece>(*Piece))
482       Path.push_back(std::move(Piece));
483   }
484 }
485 
486 /// Returns true if the given decl has been implicitly given a body, either by
487 /// the analyzer or by the compiler proper.
488 static bool hasImplicitBody(const Decl *D) {
489   assert(D);
490   return D->isImplicit() || !D->hasBody();
491 }
492 
493 /// Recursively scan through a path and make sure that all call pieces have
494 /// valid locations.
495 static void
496 adjustCallLocations(PathPieces &Pieces,
497                     PathDiagnosticLocation *LastCallLocation = nullptr) {
498   for (const auto &I : Pieces) {
499     auto *Call = dyn_cast<PathDiagnosticCallPiece>(I.get());
500 
501     if (!Call)
502       continue;
503 
504     if (LastCallLocation) {
505       bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
506       if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
507         Call->callEnter = *LastCallLocation;
508       if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
509         Call->callReturn = *LastCallLocation;
510     }
511 
512     // Recursively clean out the subclass.  Keep this call around if
513     // it contains any informative diagnostics.
514     PathDiagnosticLocation *ThisCallLocation;
515     if (Call->callEnterWithin.asLocation().isValid() &&
516         !hasImplicitBody(Call->getCallee()))
517       ThisCallLocation = &Call->callEnterWithin;
518     else
519       ThisCallLocation = &Call->callEnter;
520 
521     assert(ThisCallLocation && "Outermost call has an invalid location");
522     adjustCallLocations(Call->path, ThisCallLocation);
523   }
524 }
525 
526 /// Remove edges in and out of C++ default initializer expressions. These are
527 /// for fields that have in-class initializers, as opposed to being initialized
528 /// explicitly in a constructor or braced list.
529 static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
530   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
531     if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
532       removeEdgesToDefaultInitializers(C->path);
533 
534     if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
535       removeEdgesToDefaultInitializers(M->subPieces);
536 
537     if (auto *CF = dyn_cast<PathDiagnosticControlFlowPiece>(I->get())) {
538       const Stmt *Start = CF->getStartLocation().asStmt();
539       const Stmt *End = CF->getEndLocation().asStmt();
540       if (Start && isa<CXXDefaultInitExpr>(Start)) {
541         I = Pieces.erase(I);
542         continue;
543       } else if (End && isa<CXXDefaultInitExpr>(End)) {
544         PathPieces::iterator Next = std::next(I);
545         if (Next != E) {
546           if (auto *NextCF =
547                   dyn_cast<PathDiagnosticControlFlowPiece>(Next->get())) {
548             NextCF->setStartLocation(CF->getStartLocation());
549           }
550         }
551         I = Pieces.erase(I);
552         continue;
553       }
554     }
555 
556     I++;
557   }
558 }
559 
560 /// Remove all pieces with invalid locations as these cannot be serialized.
561 /// We might have pieces with invalid locations as a result of inlining Body
562 /// Farm generated functions.
563 static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
564   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
565     if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
566       removePiecesWithInvalidLocations(C->path);
567 
568     if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
569       removePiecesWithInvalidLocations(M->subPieces);
570 
571     if (!(*I)->getLocation().isValid() ||
572         !(*I)->getLocation().asLocation().isValid()) {
573       I = Pieces.erase(I);
574       continue;
575     }
576     I++;
577   }
578 }
579 
580 PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
581     const PathDiagnosticConstruct &C) const {
582   if (const Stmt *S = C.getCurrentNode()->getNextStmtForDiagnostics())
583     return PathDiagnosticLocation(S, getSourceManager(),
584                                   C.getCurrLocationContext());
585 
586   return PathDiagnosticLocation::createDeclEnd(C.getCurrLocationContext(),
587                                                getSourceManager());
588 }
589 
590 PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
591     llvm::raw_string_ostream &os, const PathDiagnosticConstruct &C) const {
592   // Slow, but probably doesn't matter.
593   if (os.str().empty())
594     os << ' ';
595 
596   const PathDiagnosticLocation &Loc = ExecutionContinues(C);
597 
598   if (Loc.asStmt())
599     os << "Execution continues on line "
600        << getSourceManager().getExpansionLineNumber(Loc.asLocation())
601        << '.';
602   else {
603     os << "Execution jumps to the end of the ";
604     const Decl *D = C.getCurrLocationContext()->getDecl();
605     if (isa<ObjCMethodDecl>(D))
606       os << "method";
607     else if (isa<FunctionDecl>(D))
608       os << "function";
609     else {
610       assert(isa<BlockDecl>(D));
611       os << "anonymous block";
612     }
613     os << '.';
614   }
615 
616   return Loc;
617 }
618 
619 static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
620   if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
621     return PM.getParentIgnoreParens(S);
622 
623   const Stmt *Parent = PM.getParentIgnoreParens(S);
624   if (!Parent)
625     return nullptr;
626 
627   switch (Parent->getStmtClass()) {
628   case Stmt::ForStmtClass:
629   case Stmt::DoStmtClass:
630   case Stmt::WhileStmtClass:
631   case Stmt::ObjCForCollectionStmtClass:
632   case Stmt::CXXForRangeStmtClass:
633     return Parent;
634   default:
635     break;
636   }
637 
638   return nullptr;
639 }
640 
641 static PathDiagnosticLocation
642 getEnclosingStmtLocation(const Stmt *S, const LocationContext *LC,
643                          bool allowNestedContexts = false) {
644   if (!S)
645     return {};
646 
647   const SourceManager &SMgr = LC->getDecl()->getASTContext().getSourceManager();
648 
649   while (const Stmt *Parent = getEnclosingParent(S, LC->getParentMap())) {
650     switch (Parent->getStmtClass()) {
651       case Stmt::BinaryOperatorClass: {
652         const auto *B = cast<BinaryOperator>(Parent);
653         if (B->isLogicalOp())
654           return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
655         break;
656       }
657       case Stmt::CompoundStmtClass:
658       case Stmt::StmtExprClass:
659         return PathDiagnosticLocation(S, SMgr, LC);
660       case Stmt::ChooseExprClass:
661         // Similar to '?' if we are referring to condition, just have the edge
662         // point to the entire choose expression.
663         if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
664           return PathDiagnosticLocation(Parent, SMgr, LC);
665         else
666           return PathDiagnosticLocation(S, SMgr, LC);
667       case Stmt::BinaryConditionalOperatorClass:
668       case Stmt::ConditionalOperatorClass:
669         // For '?', if we are referring to condition, just have the edge point
670         // to the entire '?' expression.
671         if (allowNestedContexts ||
672             cast<AbstractConditionalOperator>(Parent)->getCond() == S)
673           return PathDiagnosticLocation(Parent, SMgr, LC);
674         else
675           return PathDiagnosticLocation(S, SMgr, LC);
676       case Stmt::CXXForRangeStmtClass:
677         if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
678           return PathDiagnosticLocation(S, SMgr, LC);
679         break;
680       case Stmt::DoStmtClass:
681           return PathDiagnosticLocation(S, SMgr, LC);
682       case Stmt::ForStmtClass:
683         if (cast<ForStmt>(Parent)->getBody() == S)
684           return PathDiagnosticLocation(S, SMgr, LC);
685         break;
686       case Stmt::IfStmtClass:
687         if (cast<IfStmt>(Parent)->getCond() != S)
688           return PathDiagnosticLocation(S, SMgr, LC);
689         break;
690       case Stmt::ObjCForCollectionStmtClass:
691         if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
692           return PathDiagnosticLocation(S, SMgr, LC);
693         break;
694       case Stmt::WhileStmtClass:
695         if (cast<WhileStmt>(Parent)->getCond() != S)
696           return PathDiagnosticLocation(S, SMgr, LC);
697         break;
698       default:
699         break;
700     }
701 
702     S = Parent;
703   }
704 
705   assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
706 
707   return PathDiagnosticLocation(S, SMgr, LC);
708 }
709 
710 //===----------------------------------------------------------------------===//
711 // "Minimal" path diagnostic generation algorithm.
712 //===----------------------------------------------------------------------===//
713 
714 /// If the piece contains a special message, add it to all the call pieces on
715 /// the active stack. For example, my_malloc allocated memory, so MallocChecker
716 /// will construct an event at the call to malloc(), and add a stack hint that
717 /// an allocated memory was returned. We'll use this hint to construct a message
718 /// when returning from the call to my_malloc
719 ///
720 ///   void *my_malloc() { return malloc(sizeof(int)); }
721 ///   void fishy() {
722 ///     void *ptr = my_malloc(); // returned allocated memory
723 ///   } // leak
724 void PathDiagnosticBuilder::updateStackPiecesWithMessage(
725     PathDiagnosticPieceRef P, const CallWithEntryStack &CallStack) const {
726   if (R->hasCallStackHint(P))
727     for (const auto &I : CallStack) {
728       PathDiagnosticCallPiece *CP = I.first;
729       const ExplodedNode *N = I.second;
730       std::string stackMsg = R->getCallStackMessage(P, N);
731 
732       // The last message on the path to final bug is the most important
733       // one. Since we traverse the path backwards, do not add the message
734       // if one has been previously added.
735       if (!CP->hasCallStackMessage())
736         CP->setCallStackMessage(stackMsg);
737     }
738 }
739 
740 static void CompactMacroExpandedPieces(PathPieces &path,
741                                        const SourceManager& SM);
742 
743 PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForSwitchOP(
744     const PathDiagnosticConstruct &C, const CFGBlock *Dst,
745     PathDiagnosticLocation &Start) const {
746 
747   const SourceManager &SM = getSourceManager();
748   // Figure out what case arm we took.
749   std::string sbuf;
750   llvm::raw_string_ostream os(sbuf);
751   PathDiagnosticLocation End;
752 
753   if (const Stmt *S = Dst->getLabel()) {
754     End = PathDiagnosticLocation(S, SM, C.getCurrLocationContext());
755 
756     switch (S->getStmtClass()) {
757     default:
758       os << "No cases match in the switch statement. "
759         "Control jumps to line "
760         << End.asLocation().getExpansionLineNumber();
761       break;
762     case Stmt::DefaultStmtClass:
763       os << "Control jumps to the 'default' case at line "
764         << End.asLocation().getExpansionLineNumber();
765       break;
766 
767     case Stmt::CaseStmtClass: {
768       os << "Control jumps to 'case ";
769       const auto *Case = cast<CaseStmt>(S);
770       const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
771 
772       // Determine if it is an enum.
773       bool GetRawInt = true;
774 
775       if (const auto *DR = dyn_cast<DeclRefExpr>(LHS)) {
776         // FIXME: Maybe this should be an assertion.  Are there cases
777         // were it is not an EnumConstantDecl?
778         const auto *D = dyn_cast<EnumConstantDecl>(DR->getDecl());
779 
780         if (D) {
781           GetRawInt = false;
782           os << *D;
783         }
784       }
785 
786       if (GetRawInt)
787         os << LHS->EvaluateKnownConstInt(getASTContext());
788 
789       os << ":'  at line " << End.asLocation().getExpansionLineNumber();
790       break;
791     }
792     }
793   } else {
794     os << "'Default' branch taken. ";
795     End = ExecutionContinues(os, C);
796   }
797   return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
798                                                        os.str());
799 }
800 
801 PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForGotoOP(
802     const PathDiagnosticConstruct &C, const Stmt *S,
803     PathDiagnosticLocation &Start) const {
804   std::string sbuf;
805   llvm::raw_string_ostream os(sbuf);
806   const PathDiagnosticLocation &End =
807       getEnclosingStmtLocation(S, C.getCurrLocationContext());
808   os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
809   return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str());
810 }
811 
812 PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForBinaryOP(
813     const PathDiagnosticConstruct &C, const Stmt *T, const CFGBlock *Src,
814     const CFGBlock *Dst) const {
815 
816   const SourceManager &SM = getSourceManager();
817 
818   const auto *B = cast<BinaryOperator>(T);
819   std::string sbuf;
820   llvm::raw_string_ostream os(sbuf);
821   os << "Left side of '";
822   PathDiagnosticLocation Start, End;
823 
824   if (B->getOpcode() == BO_LAnd) {
825     os << "&&"
826       << "' is ";
827 
828     if (*(Src->succ_begin() + 1) == Dst) {
829       os << "false";
830       End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
831       Start =
832         PathDiagnosticLocation::createOperatorLoc(B, SM);
833     } else {
834       os << "true";
835       Start =
836           PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
837       End = ExecutionContinues(C);
838     }
839   } else {
840     assert(B->getOpcode() == BO_LOr);
841     os << "||"
842       << "' is ";
843 
844     if (*(Src->succ_begin() + 1) == Dst) {
845       os << "false";
846       Start =
847           PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
848       End = ExecutionContinues(C);
849     } else {
850       os << "true";
851       End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
852       Start =
853         PathDiagnosticLocation::createOperatorLoc(B, SM);
854     }
855   }
856   return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
857                                                          os.str());
858 }
859 
860 void PathDiagnosticBuilder::generateMinimalDiagForBlockEdge(
861     PathDiagnosticConstruct &C, BlockEdge BE) const {
862   const SourceManager &SM = getSourceManager();
863   const LocationContext *LC = C.getCurrLocationContext();
864   const CFGBlock *Src = BE.getSrc();
865   const CFGBlock *Dst = BE.getDst();
866   const Stmt *T = Src->getTerminatorStmt();
867   if (!T)
868     return;
869 
870   auto Start = PathDiagnosticLocation::createBegin(T, SM, LC);
871   switch (T->getStmtClass()) {
872   default:
873     break;
874 
875   case Stmt::GotoStmtClass:
876   case Stmt::IndirectGotoStmtClass: {
877     if (const Stmt *S = C.getCurrentNode()->getNextStmtForDiagnostics())
878       C.getActivePath().push_front(generateDiagForGotoOP(C, S, Start));
879     break;
880   }
881 
882   case Stmt::SwitchStmtClass: {
883     C.getActivePath().push_front(generateDiagForSwitchOP(C, Dst, Start));
884     break;
885   }
886 
887   case Stmt::BreakStmtClass:
888   case Stmt::ContinueStmtClass: {
889     std::string sbuf;
890     llvm::raw_string_ostream os(sbuf);
891     PathDiagnosticLocation End = ExecutionContinues(os, C);
892     C.getActivePath().push_front(
893         std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
894     break;
895   }
896 
897   // Determine control-flow for ternary '?'.
898   case Stmt::BinaryConditionalOperatorClass:
899   case Stmt::ConditionalOperatorClass: {
900     std::string sbuf;
901     llvm::raw_string_ostream os(sbuf);
902     os << "'?' condition is ";
903 
904     if (*(Src->succ_begin() + 1) == Dst)
905       os << "false";
906     else
907       os << "true";
908 
909     PathDiagnosticLocation End = ExecutionContinues(C);
910 
911     if (const Stmt *S = End.asStmt())
912       End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
913 
914     C.getActivePath().push_front(
915         std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
916     break;
917   }
918 
919   // Determine control-flow for short-circuited '&&' and '||'.
920   case Stmt::BinaryOperatorClass: {
921     if (!C.supportsLogicalOpControlFlow())
922       break;
923 
924     C.getActivePath().push_front(generateDiagForBinaryOP(C, T, Src, Dst));
925     break;
926   }
927 
928   case Stmt::DoStmtClass:
929     if (*(Src->succ_begin()) == Dst) {
930       std::string sbuf;
931       llvm::raw_string_ostream os(sbuf);
932 
933       os << "Loop condition is true. ";
934       PathDiagnosticLocation End = ExecutionContinues(os, C);
935 
936       if (const Stmt *S = End.asStmt())
937         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
938 
939       C.getActivePath().push_front(
940           std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
941                                                            os.str()));
942     } else {
943       PathDiagnosticLocation End = ExecutionContinues(C);
944 
945       if (const Stmt *S = End.asStmt())
946         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
947 
948       C.getActivePath().push_front(
949           std::make_shared<PathDiagnosticControlFlowPiece>(
950               Start, End, "Loop condition is false.  Exiting loop"));
951     }
952     break;
953 
954   case Stmt::WhileStmtClass:
955   case Stmt::ForStmtClass:
956     if (*(Src->succ_begin() + 1) == Dst) {
957       std::string sbuf;
958       llvm::raw_string_ostream os(sbuf);
959 
960       os << "Loop condition is false. ";
961       PathDiagnosticLocation End = ExecutionContinues(os, C);
962       if (const Stmt *S = End.asStmt())
963         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
964 
965       C.getActivePath().push_front(
966           std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
967                                                            os.str()));
968     } else {
969       PathDiagnosticLocation End = ExecutionContinues(C);
970       if (const Stmt *S = End.asStmt())
971         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
972 
973       C.getActivePath().push_front(
974           std::make_shared<PathDiagnosticControlFlowPiece>(
975               Start, End, "Loop condition is true.  Entering loop body"));
976     }
977 
978     break;
979 
980   case Stmt::IfStmtClass: {
981     PathDiagnosticLocation End = ExecutionContinues(C);
982 
983     if (const Stmt *S = End.asStmt())
984       End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
985 
986     if (*(Src->succ_begin() + 1) == Dst)
987       C.getActivePath().push_front(
988           std::make_shared<PathDiagnosticControlFlowPiece>(
989               Start, End, "Taking false branch"));
990     else
991       C.getActivePath().push_front(
992           std::make_shared<PathDiagnosticControlFlowPiece>(
993               Start, End, "Taking true branch"));
994 
995     break;
996   }
997   }
998 }
999 
1000 //===----------------------------------------------------------------------===//
1001 // Functions for determining if a loop was executed 0 times.
1002 //===----------------------------------------------------------------------===//
1003 
1004 static bool isLoop(const Stmt *Term) {
1005   switch (Term->getStmtClass()) {
1006     case Stmt::ForStmtClass:
1007     case Stmt::WhileStmtClass:
1008     case Stmt::ObjCForCollectionStmtClass:
1009     case Stmt::CXXForRangeStmtClass:
1010       return true;
1011     default:
1012       // Note that we intentionally do not include do..while here.
1013       return false;
1014   }
1015 }
1016 
1017 static bool isJumpToFalseBranch(const BlockEdge *BE) {
1018   const CFGBlock *Src = BE->getSrc();
1019   assert(Src->succ_size() == 2);
1020   return (*(Src->succ_begin()+1) == BE->getDst());
1021 }
1022 
1023 static bool isContainedByStmt(const ParentMap &PM, const Stmt *S,
1024                               const Stmt *SubS) {
1025   while (SubS) {
1026     if (SubS == S)
1027       return true;
1028     SubS = PM.getParent(SubS);
1029   }
1030   return false;
1031 }
1032 
1033 static const Stmt *getStmtBeforeCond(const ParentMap &PM, const Stmt *Term,
1034                                      const ExplodedNode *N) {
1035   while (N) {
1036     Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1037     if (SP) {
1038       const Stmt *S = SP->getStmt();
1039       if (!isContainedByStmt(PM, Term, S))
1040         return S;
1041     }
1042     N = N->getFirstPred();
1043   }
1044   return nullptr;
1045 }
1046 
1047 static bool isInLoopBody(const ParentMap &PM, const Stmt *S, const Stmt *Term) {
1048   const Stmt *LoopBody = nullptr;
1049   switch (Term->getStmtClass()) {
1050     case Stmt::CXXForRangeStmtClass: {
1051       const auto *FR = cast<CXXForRangeStmt>(Term);
1052       if (isContainedByStmt(PM, FR->getInc(), S))
1053         return true;
1054       if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
1055         return true;
1056       LoopBody = FR->getBody();
1057       break;
1058     }
1059     case Stmt::ForStmtClass: {
1060       const auto *FS = cast<ForStmt>(Term);
1061       if (isContainedByStmt(PM, FS->getInc(), S))
1062         return true;
1063       LoopBody = FS->getBody();
1064       break;
1065     }
1066     case Stmt::ObjCForCollectionStmtClass: {
1067       const auto *FC = cast<ObjCForCollectionStmt>(Term);
1068       LoopBody = FC->getBody();
1069       break;
1070     }
1071     case Stmt::WhileStmtClass:
1072       LoopBody = cast<WhileStmt>(Term)->getBody();
1073       break;
1074     default:
1075       return false;
1076   }
1077   return isContainedByStmt(PM, LoopBody, S);
1078 }
1079 
1080 /// Adds a sanitized control-flow diagnostic edge to a path.
1081 static void addEdgeToPath(PathPieces &path,
1082                           PathDiagnosticLocation &PrevLoc,
1083                           PathDiagnosticLocation NewLoc) {
1084   if (!NewLoc.isValid())
1085     return;
1086 
1087   SourceLocation NewLocL = NewLoc.asLocation();
1088   if (NewLocL.isInvalid())
1089     return;
1090 
1091   if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
1092     PrevLoc = NewLoc;
1093     return;
1094   }
1095 
1096   // Ignore self-edges, which occur when there are multiple nodes at the same
1097   // statement.
1098   if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
1099     return;
1100 
1101   path.push_front(
1102       std::make_shared<PathDiagnosticControlFlowPiece>(NewLoc, PrevLoc));
1103   PrevLoc = NewLoc;
1104 }
1105 
1106 /// A customized wrapper for CFGBlock::getTerminatorCondition()
1107 /// which returns the element for ObjCForCollectionStmts.
1108 static const Stmt *getTerminatorCondition(const CFGBlock *B) {
1109   const Stmt *S = B->getTerminatorCondition();
1110   if (const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(S))
1111     return FS->getElement();
1112   return S;
1113 }
1114 
1115 constexpr llvm::StringLiteral StrEnteringLoop = "Entering loop body";
1116 constexpr llvm::StringLiteral StrLoopBodyZero = "Loop body executed 0 times";
1117 constexpr llvm::StringLiteral StrLoopRangeEmpty =
1118     "Loop body skipped when range is empty";
1119 constexpr llvm::StringLiteral StrLoopCollectionEmpty =
1120     "Loop body skipped when collection is empty";
1121 
1122 static std::unique_ptr<FilesToLineNumsMap>
1123 findExecutedLines(const SourceManager &SM, const ExplodedNode *N);
1124 
1125 void PathDiagnosticBuilder::generatePathDiagnosticsForNode(
1126     PathDiagnosticConstruct &C, PathDiagnosticLocation &PrevLoc) const {
1127   ProgramPoint P = C.getCurrentNode()->getLocation();
1128   const SourceManager &SM = getSourceManager();
1129 
1130   // Have we encountered an entrance to a call?  It may be
1131   // the case that we have not encountered a matching
1132   // call exit before this point.  This means that the path
1133   // terminated within the call itself.
1134   if (auto CE = P.getAs<CallEnter>()) {
1135 
1136     if (C.shouldAddPathEdges()) {
1137       // Add an edge to the start of the function.
1138       const StackFrameContext *CalleeLC = CE->getCalleeContext();
1139       const Decl *D = CalleeLC->getDecl();
1140       // Add the edge only when the callee has body. We jump to the beginning
1141       // of the *declaration*, however we expect it to be followed by the
1142       // body. This isn't the case for autosynthesized property accessors in
1143       // Objective-C. No need for a similar extra check for CallExit points
1144       // because the exit edge comes from a statement (i.e. return),
1145       // not from declaration.
1146       if (D->hasBody())
1147         addEdgeToPath(C.getActivePath(), PrevLoc,
1148                       PathDiagnosticLocation::createBegin(D, SM));
1149     }
1150 
1151     // Did we visit an entire call?
1152     bool VisitedEntireCall = C.PD->isWithinCall();
1153     C.PD->popActivePath();
1154 
1155     PathDiagnosticCallPiece *Call;
1156     if (VisitedEntireCall) {
1157       Call = cast<PathDiagnosticCallPiece>(C.getActivePath().front().get());
1158     } else {
1159       // The path terminated within a nested location context, create a new
1160       // call piece to encapsulate the rest of the path pieces.
1161       const Decl *Caller = CE->getLocationContext()->getDecl();
1162       Call = PathDiagnosticCallPiece::construct(C.getActivePath(), Caller);
1163       assert(C.getActivePath().size() == 1 &&
1164              C.getActivePath().front().get() == Call);
1165 
1166       // Since we just transferred the path over to the call piece, reset the
1167       // mapping of the active path to the current location context.
1168       assert(C.isInLocCtxMap(&C.getActivePath()) &&
1169              "When we ascend to a previously unvisited call, the active path's "
1170              "address shouldn't change, but rather should be compacted into "
1171              "a single CallEvent!");
1172       C.updateLocCtxMap(&C.getActivePath(), C.getCurrLocationContext());
1173 
1174       // Record the location context mapping for the path within the call.
1175       assert(!C.isInLocCtxMap(&Call->path) &&
1176              "When we ascend to a previously unvisited call, this must be the "
1177              "first time we encounter the caller context!");
1178       C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1179     }
1180     Call->setCallee(*CE, SM);
1181 
1182     // Update the previous location in the active path.
1183     PrevLoc = Call->getLocation();
1184 
1185     if (!C.CallStack.empty()) {
1186       assert(C.CallStack.back().first == Call);
1187       C.CallStack.pop_back();
1188     }
1189     return;
1190   }
1191 
1192   assert(C.getCurrLocationContext() == C.getLocationContextForActivePath() &&
1193          "The current position in the bug path is out of sync with the "
1194          "location context associated with the active path!");
1195 
1196   // Have we encountered an exit from a function call?
1197   if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1198 
1199     // We are descending into a call (backwards).  Construct
1200     // a new call piece to contain the path pieces for that call.
1201     auto Call = PathDiagnosticCallPiece::construct(*CE, SM);
1202     // Record the mapping from call piece to LocationContext.
1203     assert(!C.isInLocCtxMap(&Call->path) &&
1204            "We just entered a call, this must've been the first time we "
1205            "encounter its context!");
1206     C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1207 
1208     if (C.shouldAddPathEdges()) {
1209       // Add the edge to the return site.
1210       addEdgeToPath(C.getActivePath(), PrevLoc, Call->callReturn);
1211       PrevLoc.invalidate();
1212     }
1213 
1214     auto *P = Call.get();
1215     C.getActivePath().push_front(std::move(Call));
1216 
1217     // Make the contents of the call the active path for now.
1218     C.PD->pushActivePath(&P->path);
1219     C.CallStack.push_back(CallWithEntry(P, C.getCurrentNode()));
1220     return;
1221   }
1222 
1223   if (auto PS = P.getAs<PostStmt>()) {
1224     if (!C.shouldAddPathEdges())
1225       return;
1226 
1227     // Add an edge.  If this is an ObjCForCollectionStmt do
1228     // not add an edge here as it appears in the CFG both
1229     // as a terminator and as a terminator condition.
1230     if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
1231       PathDiagnosticLocation L =
1232           PathDiagnosticLocation(PS->getStmt(), SM, C.getCurrLocationContext());
1233       addEdgeToPath(C.getActivePath(), PrevLoc, L);
1234     }
1235 
1236   } else if (auto BE = P.getAs<BlockEdge>()) {
1237 
1238     if (C.shouldAddControlNotes()) {
1239       generateMinimalDiagForBlockEdge(C, *BE);
1240     }
1241 
1242     if (!C.shouldAddPathEdges()) {
1243       return;
1244     }
1245 
1246     // Are we jumping to the head of a loop?  Add a special diagnostic.
1247     if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1248       PathDiagnosticLocation L(Loop, SM, C.getCurrLocationContext());
1249       const Stmt *Body = nullptr;
1250 
1251       if (const auto *FS = dyn_cast<ForStmt>(Loop))
1252         Body = FS->getBody();
1253       else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
1254         Body = WS->getBody();
1255       else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
1256         Body = OFS->getBody();
1257       } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
1258         Body = FRS->getBody();
1259       }
1260       // do-while statements are explicitly excluded here
1261 
1262       auto p = std::make_shared<PathDiagnosticEventPiece>(
1263           L, "Looping back to the head of the loop");
1264       p->setPrunable(true);
1265 
1266       addEdgeToPath(C.getActivePath(), PrevLoc, p->getLocation());
1267       // We might've added a very similar control node already
1268       if (!C.shouldAddControlNotes()) {
1269         C.getActivePath().push_front(std::move(p));
1270       }
1271 
1272       if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
1273         addEdgeToPath(C.getActivePath(), PrevLoc,
1274                       PathDiagnosticLocation::createEndBrace(CS, SM));
1275       }
1276     }
1277 
1278     const CFGBlock *BSrc = BE->getSrc();
1279     const ParentMap &PM = C.getParentMap();
1280 
1281     if (const Stmt *Term = BSrc->getTerminatorStmt()) {
1282       // Are we jumping past the loop body without ever executing the
1283       // loop (because the condition was false)?
1284       if (isLoop(Term)) {
1285         const Stmt *TermCond = getTerminatorCondition(BSrc);
1286         bool IsInLoopBody = isInLoopBody(
1287             PM, getStmtBeforeCond(PM, TermCond, C.getCurrentNode()), Term);
1288 
1289         StringRef str;
1290 
1291         if (isJumpToFalseBranch(&*BE)) {
1292           if (!IsInLoopBody) {
1293             if (isa<ObjCForCollectionStmt>(Term)) {
1294               str = StrLoopCollectionEmpty;
1295             } else if (isa<CXXForRangeStmt>(Term)) {
1296               str = StrLoopRangeEmpty;
1297             } else {
1298               str = StrLoopBodyZero;
1299             }
1300           }
1301         } else {
1302           str = StrEnteringLoop;
1303         }
1304 
1305         if (!str.empty()) {
1306           PathDiagnosticLocation L(TermCond ? TermCond : Term, SM,
1307                                    C.getCurrLocationContext());
1308           auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
1309           PE->setPrunable(true);
1310           addEdgeToPath(C.getActivePath(), PrevLoc, PE->getLocation());
1311 
1312           // We might've added a very similar control node already
1313           if (!C.shouldAddControlNotes()) {
1314             C.getActivePath().push_front(std::move(PE));
1315           }
1316         }
1317       } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
1318                  isa<GotoStmt>(Term)) {
1319         PathDiagnosticLocation L(Term, SM, C.getCurrLocationContext());
1320         addEdgeToPath(C.getActivePath(), PrevLoc, L);
1321       }
1322     }
1323   }
1324 }
1325 
1326 static std::unique_ptr<PathDiagnostic>
1327 generateDiagnosticForBasicReport(const BasicBugReport *R) {
1328   const BugType &BT = R->getBugType();
1329   return std::make_unique<PathDiagnostic>(
1330       BT.getCheckerName(), R->getDeclWithIssue(), BT.getDescription(),
1331       R->getDescription(), R->getShortDescription(/*UseFallback=*/false),
1332       BT.getCategory(), R->getUniqueingLocation(), R->getUniqueingDecl(),
1333       std::make_unique<FilesToLineNumsMap>());
1334 }
1335 
1336 static std::unique_ptr<PathDiagnostic>
1337 generateEmptyDiagnosticForReport(const PathSensitiveBugReport *R,
1338                                  const SourceManager &SM) {
1339   const BugType &BT = R->getBugType();
1340   return std::make_unique<PathDiagnostic>(
1341       BT.getCheckerName(), R->getDeclWithIssue(), BT.getDescription(),
1342       R->getDescription(), R->getShortDescription(/*UseFallback=*/false),
1343       BT.getCategory(), R->getUniqueingLocation(), R->getUniqueingDecl(),
1344       findExecutedLines(SM, R->getErrorNode()));
1345 }
1346 
1347 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
1348   if (!S)
1349     return nullptr;
1350 
1351   while (true) {
1352     S = PM.getParentIgnoreParens(S);
1353 
1354     if (!S)
1355       break;
1356 
1357     if (isa<FullExpr>(S) ||
1358         isa<CXXBindTemporaryExpr>(S) ||
1359         isa<SubstNonTypeTemplateParmExpr>(S))
1360       continue;
1361 
1362     break;
1363   }
1364 
1365   return S;
1366 }
1367 
1368 static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
1369   switch (S->getStmtClass()) {
1370     case Stmt::BinaryOperatorClass: {
1371       const auto *BO = cast<BinaryOperator>(S);
1372       if (!BO->isLogicalOp())
1373         return false;
1374       return BO->getLHS() == Cond || BO->getRHS() == Cond;
1375     }
1376     case Stmt::IfStmtClass:
1377       return cast<IfStmt>(S)->getCond() == Cond;
1378     case Stmt::ForStmtClass:
1379       return cast<ForStmt>(S)->getCond() == Cond;
1380     case Stmt::WhileStmtClass:
1381       return cast<WhileStmt>(S)->getCond() == Cond;
1382     case Stmt::DoStmtClass:
1383       return cast<DoStmt>(S)->getCond() == Cond;
1384     case Stmt::ChooseExprClass:
1385       return cast<ChooseExpr>(S)->getCond() == Cond;
1386     case Stmt::IndirectGotoStmtClass:
1387       return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
1388     case Stmt::SwitchStmtClass:
1389       return cast<SwitchStmt>(S)->getCond() == Cond;
1390     case Stmt::BinaryConditionalOperatorClass:
1391       return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
1392     case Stmt::ConditionalOperatorClass: {
1393       const auto *CO = cast<ConditionalOperator>(S);
1394       return CO->getCond() == Cond ||
1395              CO->getLHS() == Cond ||
1396              CO->getRHS() == Cond;
1397     }
1398     case Stmt::ObjCForCollectionStmtClass:
1399       return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
1400     case Stmt::CXXForRangeStmtClass: {
1401       const auto *FRS = cast<CXXForRangeStmt>(S);
1402       return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
1403     }
1404     default:
1405       return false;
1406   }
1407 }
1408 
1409 static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
1410   if (const auto *FS = dyn_cast<ForStmt>(FL))
1411     return FS->getInc() == S || FS->getInit() == S;
1412   if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
1413     return FRS->getInc() == S || FRS->getRangeStmt() == S ||
1414            FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
1415   return false;
1416 }
1417 
1418 using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
1419 
1420 /// Adds synthetic edges from top-level statements to their subexpressions.
1421 ///
1422 /// This avoids a "swoosh" effect, where an edge from a top-level statement A
1423 /// points to a sub-expression B.1 that's not at the start of B. In these cases,
1424 /// we'd like to see an edge from A to B, then another one from B to B.1.
1425 static void addContextEdges(PathPieces &pieces, const LocationContext *LC) {
1426   const ParentMap &PM = LC->getParentMap();
1427   PathPieces::iterator Prev = pieces.end();
1428   for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
1429        Prev = I, ++I) {
1430     auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1431 
1432     if (!Piece)
1433       continue;
1434 
1435     PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
1436     SmallVector<PathDiagnosticLocation, 4> SrcContexts;
1437 
1438     PathDiagnosticLocation NextSrcContext = SrcLoc;
1439     const Stmt *InnerStmt = nullptr;
1440     while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
1441       SrcContexts.push_back(NextSrcContext);
1442       InnerStmt = NextSrcContext.asStmt();
1443       NextSrcContext = getEnclosingStmtLocation(InnerStmt, LC,
1444                                                 /*allowNested=*/true);
1445     }
1446 
1447     // Repeatedly split the edge as necessary.
1448     // This is important for nested logical expressions (||, &&, ?:) where we
1449     // want to show all the levels of context.
1450     while (true) {
1451       const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
1452 
1453       // We are looking at an edge. Is the destination within a larger
1454       // expression?
1455       PathDiagnosticLocation DstContext =
1456           getEnclosingStmtLocation(Dst, LC, /*allowNested=*/true);
1457       if (!DstContext.isValid() || DstContext.asStmt() == Dst)
1458         break;
1459 
1460       // If the source is in the same context, we're already good.
1461       if (llvm::find(SrcContexts, DstContext) != SrcContexts.end())
1462         break;
1463 
1464       // Update the subexpression node to point to the context edge.
1465       Piece->setStartLocation(DstContext);
1466 
1467       // Try to extend the previous edge if it's at the same level as the source
1468       // context.
1469       if (Prev != E) {
1470         auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
1471 
1472         if (PrevPiece) {
1473           if (const Stmt *PrevSrc =
1474                   PrevPiece->getStartLocation().getStmtOrNull()) {
1475             const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
1476             if (PrevSrcParent ==
1477                 getStmtParent(DstContext.getStmtOrNull(), PM)) {
1478               PrevPiece->setEndLocation(DstContext);
1479               break;
1480             }
1481           }
1482         }
1483       }
1484 
1485       // Otherwise, split the current edge into a context edge and a
1486       // subexpression edge. Note that the context statement may itself have
1487       // context.
1488       auto P =
1489           std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
1490       Piece = P.get();
1491       I = pieces.insert(I, std::move(P));
1492     }
1493   }
1494 }
1495 
1496 /// Move edges from a branch condition to a branch target
1497 ///        when the condition is simple.
1498 ///
1499 /// This restructures some of the work of addContextEdges.  That function
1500 /// creates edges this may destroy, but they work together to create a more
1501 /// aesthetically set of edges around branches.  After the call to
1502 /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
1503 /// the branch to the branch condition, and (3) an edge from the branch
1504 /// condition to the branch target.  We keep (1), but may wish to remove (2)
1505 /// and move the source of (3) to the branch if the branch condition is simple.
1506 static void simplifySimpleBranches(PathPieces &pieces) {
1507   for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
1508     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1509 
1510     if (!PieceI)
1511       continue;
1512 
1513     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1514     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1515 
1516     if (!s1Start || !s1End)
1517       continue;
1518 
1519     PathPieces::iterator NextI = I; ++NextI;
1520     if (NextI == E)
1521       break;
1522 
1523     PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
1524 
1525     while (true) {
1526       if (NextI == E)
1527         break;
1528 
1529       const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1530       if (EV) {
1531         StringRef S = EV->getString();
1532         if (S == StrEnteringLoop || S == StrLoopBodyZero ||
1533             S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
1534           ++NextI;
1535           continue;
1536         }
1537         break;
1538       }
1539 
1540       PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1541       break;
1542     }
1543 
1544     if (!PieceNextI)
1545       continue;
1546 
1547     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1548     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1549 
1550     if (!s2Start || !s2End || s1End != s2Start)
1551       continue;
1552 
1553     // We only perform this transformation for specific branch kinds.
1554     // We don't want to do this for do..while, for example.
1555     if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
1556           isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
1557           isa<CXXForRangeStmt>(s1Start)))
1558       continue;
1559 
1560     // Is s1End the branch condition?
1561     if (!isConditionForTerminator(s1Start, s1End))
1562       continue;
1563 
1564     // Perform the hoisting by eliminating (2) and changing the start
1565     // location of (3).
1566     PieceNextI->setStartLocation(PieceI->getStartLocation());
1567     I = pieces.erase(I);
1568   }
1569 }
1570 
1571 /// Returns the number of bytes in the given (character-based) SourceRange.
1572 ///
1573 /// If the locations in the range are not on the same line, returns None.
1574 ///
1575 /// Note that this does not do a precise user-visible character or column count.
1576 static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1577                                               SourceRange Range) {
1578   SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
1579                              SM.getExpansionRange(Range.getEnd()).getEnd());
1580 
1581   FileID FID = SM.getFileID(ExpansionRange.getBegin());
1582   if (FID != SM.getFileID(ExpansionRange.getEnd()))
1583     return None;
1584 
1585   Optional<MemoryBufferRef> Buffer = SM.getBufferOrNone(FID);
1586   if (!Buffer)
1587     return None;
1588 
1589   unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
1590   unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
1591   StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
1592 
1593   // We're searching the raw bytes of the buffer here, which might include
1594   // escaped newlines and such. That's okay; we're trying to decide whether the
1595   // SourceRange is covering a large or small amount of space in the user's
1596   // editor.
1597   if (Snippet.find_first_of("\r\n") != StringRef::npos)
1598     return None;
1599 
1600   // This isn't Unicode-aware, but it doesn't need to be.
1601   return Snippet.size();
1602 }
1603 
1604 /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
1605 static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1606                                               const Stmt *S) {
1607   return getLengthOnSingleLine(SM, S->getSourceRange());
1608 }
1609 
1610 /// Eliminate two-edge cycles created by addContextEdges().
1611 ///
1612 /// Once all the context edges are in place, there are plenty of cases where
1613 /// there's a single edge from a top-level statement to a subexpression,
1614 /// followed by a single path note, and then a reverse edge to get back out to
1615 /// the top level. If the statement is simple enough, the subexpression edges
1616 /// just add noise and make it harder to understand what's going on.
1617 ///
1618 /// This function only removes edges in pairs, because removing only one edge
1619 /// might leave other edges dangling.
1620 ///
1621 /// This will not remove edges in more complicated situations:
1622 /// - if there is more than one "hop" leading to or from a subexpression.
1623 /// - if there is an inlined call between the edges instead of a single event.
1624 /// - if the whole statement is large enough that having subexpression arrows
1625 ///   might be helpful.
1626 static void removeContextCycles(PathPieces &Path, const SourceManager &SM) {
1627   for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
1628     // Pattern match the current piece and its successor.
1629     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1630 
1631     if (!PieceI) {
1632       ++I;
1633       continue;
1634     }
1635 
1636     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1637     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1638 
1639     PathPieces::iterator NextI = I; ++NextI;
1640     if (NextI == E)
1641       break;
1642 
1643     const auto *PieceNextI =
1644         dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1645 
1646     if (!PieceNextI) {
1647       if (isa<PathDiagnosticEventPiece>(NextI->get())) {
1648         ++NextI;
1649         if (NextI == E)
1650           break;
1651         PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1652       }
1653 
1654       if (!PieceNextI) {
1655         ++I;
1656         continue;
1657       }
1658     }
1659 
1660     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1661     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1662 
1663     if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
1664       const size_t MAX_SHORT_LINE_LENGTH = 80;
1665       Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
1666       if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
1667         Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
1668         if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
1669           Path.erase(I);
1670           I = Path.erase(NextI);
1671           continue;
1672         }
1673       }
1674     }
1675 
1676     ++I;
1677   }
1678 }
1679 
1680 /// Return true if X is contained by Y.
1681 static bool lexicalContains(const ParentMap &PM, const Stmt *X, const Stmt *Y) {
1682   while (X) {
1683     if (X == Y)
1684       return true;
1685     X = PM.getParent(X);
1686   }
1687   return false;
1688 }
1689 
1690 // Remove short edges on the same line less than 3 columns in difference.
1691 static void removePunyEdges(PathPieces &path, const SourceManager &SM,
1692                             const ParentMap &PM) {
1693   bool erased = false;
1694 
1695   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
1696        erased ? I : ++I) {
1697     erased = false;
1698 
1699     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1700 
1701     if (!PieceI)
1702       continue;
1703 
1704     const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
1705     const Stmt *end   = PieceI->getEndLocation().getStmtOrNull();
1706 
1707     if (!start || !end)
1708       continue;
1709 
1710     const Stmt *endParent = PM.getParent(end);
1711     if (!endParent)
1712       continue;
1713 
1714     if (isConditionForTerminator(end, endParent))
1715       continue;
1716 
1717     SourceLocation FirstLoc = start->getBeginLoc();
1718     SourceLocation SecondLoc = end->getBeginLoc();
1719 
1720     if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
1721       continue;
1722     if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
1723       std::swap(SecondLoc, FirstLoc);
1724 
1725     SourceRange EdgeRange(FirstLoc, SecondLoc);
1726     Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
1727 
1728     // If the statements are on different lines, continue.
1729     if (!ByteWidth)
1730       continue;
1731 
1732     const size_t MAX_PUNY_EDGE_LENGTH = 2;
1733     if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
1734       // FIXME: There are enough /bytes/ between the endpoints of the edge, but
1735       // there might not be enough /columns/. A proper user-visible column count
1736       // is probably too expensive, though.
1737       I = path.erase(I);
1738       erased = true;
1739       continue;
1740     }
1741   }
1742 }
1743 
1744 static void removeIdenticalEvents(PathPieces &path) {
1745   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
1746     const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
1747 
1748     if (!PieceI)
1749       continue;
1750 
1751     PathPieces::iterator NextI = I; ++NextI;
1752     if (NextI == E)
1753       return;
1754 
1755     const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1756 
1757     if (!PieceNextI)
1758       continue;
1759 
1760     // Erase the second piece if it has the same exact message text.
1761     if (PieceI->getString() == PieceNextI->getString()) {
1762       path.erase(NextI);
1763     }
1764   }
1765 }
1766 
1767 static bool optimizeEdges(const PathDiagnosticConstruct &C, PathPieces &path,
1768                           OptimizedCallsSet &OCS) {
1769   bool hasChanges = false;
1770   const LocationContext *LC = C.getLocationContextFor(&path);
1771   assert(LC);
1772   const ParentMap &PM = LC->getParentMap();
1773   const SourceManager &SM = C.getSourceManager();
1774 
1775   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
1776     // Optimize subpaths.
1777     if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
1778       // Record the fact that a call has been optimized so we only do the
1779       // effort once.
1780       if (!OCS.count(CallI)) {
1781         while (optimizeEdges(C, CallI->path, OCS)) {
1782         }
1783         OCS.insert(CallI);
1784       }
1785       ++I;
1786       continue;
1787     }
1788 
1789     // Pattern match the current piece and its successor.
1790     auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1791 
1792     if (!PieceI) {
1793       ++I;
1794       continue;
1795     }
1796 
1797     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1798     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1799     const Stmt *level1 = getStmtParent(s1Start, PM);
1800     const Stmt *level2 = getStmtParent(s1End, PM);
1801 
1802     PathPieces::iterator NextI = I; ++NextI;
1803     if (NextI == E)
1804       break;
1805 
1806     const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1807 
1808     if (!PieceNextI) {
1809       ++I;
1810       continue;
1811     }
1812 
1813     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1814     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1815     const Stmt *level3 = getStmtParent(s2Start, PM);
1816     const Stmt *level4 = getStmtParent(s2End, PM);
1817 
1818     // Rule I.
1819     //
1820     // If we have two consecutive control edges whose end/begin locations
1821     // are at the same level (e.g. statements or top-level expressions within
1822     // a compound statement, or siblings share a single ancestor expression),
1823     // then merge them if they have no interesting intermediate event.
1824     //
1825     // For example:
1826     //
1827     // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
1828     // parent is '1'.  Here 'x.y.z' represents the hierarchy of statements.
1829     //
1830     // NOTE: this will be limited later in cases where we add barriers
1831     // to prevent this optimization.
1832     if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
1833       PieceI->setEndLocation(PieceNextI->getEndLocation());
1834       path.erase(NextI);
1835       hasChanges = true;
1836       continue;
1837     }
1838 
1839     // Rule II.
1840     //
1841     // Eliminate edges between subexpressions and parent expressions
1842     // when the subexpression is consumed.
1843     //
1844     // NOTE: this will be limited later in cases where we add barriers
1845     // to prevent this optimization.
1846     if (s1End && s1End == s2Start && level2) {
1847       bool removeEdge = false;
1848       // Remove edges into the increment or initialization of a
1849       // loop that have no interleaving event.  This means that
1850       // they aren't interesting.
1851       if (isIncrementOrInitInForLoop(s1End, level2))
1852         removeEdge = true;
1853       // Next only consider edges that are not anchored on
1854       // the condition of a terminator.  This are intermediate edges
1855       // that we might want to trim.
1856       else if (!isConditionForTerminator(level2, s1End)) {
1857         // Trim edges on expressions that are consumed by
1858         // the parent expression.
1859         if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
1860           removeEdge = true;
1861         }
1862         // Trim edges where a lexical containment doesn't exist.
1863         // For example:
1864         //
1865         //  X -> Y -> Z
1866         //
1867         // If 'Z' lexically contains Y (it is an ancestor) and
1868         // 'X' does not lexically contain Y (it is a descendant OR
1869         // it has no lexical relationship at all) then trim.
1870         //
1871         // This can eliminate edges where we dive into a subexpression
1872         // and then pop back out, etc.
1873         else if (s1Start && s2End &&
1874                  lexicalContains(PM, s2Start, s2End) &&
1875                  !lexicalContains(PM, s1End, s1Start)) {
1876           removeEdge = true;
1877         }
1878         // Trim edges from a subexpression back to the top level if the
1879         // subexpression is on a different line.
1880         //
1881         // A.1 -> A -> B
1882         // becomes
1883         // A.1 -> B
1884         //
1885         // These edges just look ugly and don't usually add anything.
1886         else if (s1Start && s2End &&
1887                  lexicalContains(PM, s1Start, s1End)) {
1888           SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
1889                                 PieceI->getStartLocation().asLocation());
1890           if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
1891             removeEdge = true;
1892         }
1893       }
1894 
1895       if (removeEdge) {
1896         PieceI->setEndLocation(PieceNextI->getEndLocation());
1897         path.erase(NextI);
1898         hasChanges = true;
1899         continue;
1900       }
1901     }
1902 
1903     // Optimize edges for ObjC fast-enumeration loops.
1904     //
1905     // (X -> collection) -> (collection -> element)
1906     //
1907     // becomes:
1908     //
1909     // (X -> element)
1910     if (s1End == s2Start) {
1911       const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
1912       if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
1913           s2End == FS->getElement()) {
1914         PieceI->setEndLocation(PieceNextI->getEndLocation());
1915         path.erase(NextI);
1916         hasChanges = true;
1917         continue;
1918       }
1919     }
1920 
1921     // No changes at this index?  Move to the next one.
1922     ++I;
1923   }
1924 
1925   if (!hasChanges) {
1926     // Adjust edges into subexpressions to make them more uniform
1927     // and aesthetically pleasing.
1928     addContextEdges(path, LC);
1929     // Remove "cyclical" edges that include one or more context edges.
1930     removeContextCycles(path, SM);
1931     // Hoist edges originating from branch conditions to branches
1932     // for simple branches.
1933     simplifySimpleBranches(path);
1934     // Remove any puny edges left over after primary optimization pass.
1935     removePunyEdges(path, SM, PM);
1936     // Remove identical events.
1937     removeIdenticalEvents(path);
1938   }
1939 
1940   return hasChanges;
1941 }
1942 
1943 /// Drop the very first edge in a path, which should be a function entry edge.
1944 ///
1945 /// If the first edge is not a function entry edge (say, because the first
1946 /// statement had an invalid source location), this function does nothing.
1947 // FIXME: We should just generate invalid edges anyway and have the optimizer
1948 // deal with them.
1949 static void dropFunctionEntryEdge(const PathDiagnosticConstruct &C,
1950                                   PathPieces &Path) {
1951   const auto *FirstEdge =
1952       dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
1953   if (!FirstEdge)
1954     return;
1955 
1956   const Decl *D = C.getLocationContextFor(&Path)->getDecl();
1957   PathDiagnosticLocation EntryLoc =
1958       PathDiagnosticLocation::createBegin(D, C.getSourceManager());
1959   if (FirstEdge->getStartLocation() != EntryLoc)
1960     return;
1961 
1962   Path.pop_front();
1963 }
1964 
1965 /// Populate executes lines with lines containing at least one diagnostics.
1966 static void updateExecutedLinesWithDiagnosticPieces(PathDiagnostic &PD) {
1967 
1968   PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
1969   FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
1970 
1971   for (const auto &P : path) {
1972     FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
1973     FileID FID = Loc.getFileID();
1974     unsigned LineNo = Loc.getLineNumber();
1975     assert(FID.isValid());
1976     ExecutedLines[FID].insert(LineNo);
1977   }
1978 }
1979 
1980 PathDiagnosticConstruct::PathDiagnosticConstruct(
1981     const PathDiagnosticConsumer *PDC, const ExplodedNode *ErrorNode,
1982     const PathSensitiveBugReport *R)
1983     : Consumer(PDC), CurrentNode(ErrorNode),
1984       SM(CurrentNode->getCodeDecl().getASTContext().getSourceManager()),
1985       PD(generateEmptyDiagnosticForReport(R, getSourceManager())) {
1986   LCM[&PD->getActivePath()] = ErrorNode->getLocationContext();
1987 }
1988 
1989 PathDiagnosticBuilder::PathDiagnosticBuilder(
1990     BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
1991     PathSensitiveBugReport *r, const ExplodedNode *ErrorNode,
1992     std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics)
1993     : BugReporterContext(BRC), BugPath(std::move(BugPath)), R(r),
1994       ErrorNode(ErrorNode),
1995       VisitorsDiagnostics(std::move(VisitorsDiagnostics)) {}
1996 
1997 std::unique_ptr<PathDiagnostic>
1998 PathDiagnosticBuilder::generate(const PathDiagnosticConsumer *PDC) const {
1999   PathDiagnosticConstruct Construct(PDC, ErrorNode, R);
2000 
2001   const SourceManager &SM = getSourceManager();
2002   const AnalyzerOptions &Opts = getAnalyzerOptions();
2003 
2004   if (!PDC->shouldGenerateDiagnostics())
2005     return generateEmptyDiagnosticForReport(R, getSourceManager());
2006 
2007   // Construct the final (warning) event for the bug report.
2008   auto EndNotes = VisitorsDiagnostics->find(ErrorNode);
2009   PathDiagnosticPieceRef LastPiece;
2010   if (EndNotes != VisitorsDiagnostics->end()) {
2011     assert(!EndNotes->second.empty());
2012     LastPiece = EndNotes->second[0];
2013   } else {
2014     LastPiece = BugReporterVisitor::getDefaultEndPath(*this, ErrorNode,
2015                                                       *getBugReport());
2016   }
2017   Construct.PD->setEndOfPath(LastPiece);
2018 
2019   PathDiagnosticLocation PrevLoc = Construct.PD->getLocation();
2020   // From the error node to the root, ascend the bug path and construct the bug
2021   // report.
2022   while (Construct.ascendToPrevNode()) {
2023     generatePathDiagnosticsForNode(Construct, PrevLoc);
2024 
2025     auto VisitorNotes = VisitorsDiagnostics->find(Construct.getCurrentNode());
2026     if (VisitorNotes == VisitorsDiagnostics->end())
2027       continue;
2028 
2029     // This is a workaround due to inability to put shared PathDiagnosticPiece
2030     // into a FoldingSet.
2031     std::set<llvm::FoldingSetNodeID> DeduplicationSet;
2032 
2033     // Add pieces from custom visitors.
2034     for (const PathDiagnosticPieceRef &Note : VisitorNotes->second) {
2035       llvm::FoldingSetNodeID ID;
2036       Note->Profile(ID);
2037       if (!DeduplicationSet.insert(ID).second)
2038         continue;
2039 
2040       if (PDC->shouldAddPathEdges())
2041         addEdgeToPath(Construct.getActivePath(), PrevLoc, Note->getLocation());
2042       updateStackPiecesWithMessage(Note, Construct.CallStack);
2043       Construct.getActivePath().push_front(Note);
2044     }
2045   }
2046 
2047   if (PDC->shouldAddPathEdges()) {
2048     // Add an edge to the start of the function.
2049     // We'll prune it out later, but it helps make diagnostics more uniform.
2050     const StackFrameContext *CalleeLC =
2051         Construct.getLocationContextForActivePath()->getStackFrame();
2052     const Decl *D = CalleeLC->getDecl();
2053     addEdgeToPath(Construct.getActivePath(), PrevLoc,
2054                   PathDiagnosticLocation::createBegin(D, SM));
2055   }
2056 
2057 
2058   // Finally, prune the diagnostic path of uninteresting stuff.
2059   if (!Construct.PD->path.empty()) {
2060     if (R->shouldPrunePath() && Opts.ShouldPrunePaths) {
2061       bool stillHasNotes =
2062           removeUnneededCalls(Construct, Construct.getMutablePieces(), R);
2063       assert(stillHasNotes);
2064       (void)stillHasNotes;
2065     }
2066 
2067     // Remove pop-up notes if needed.
2068     if (!Opts.ShouldAddPopUpNotes)
2069       removePopUpNotes(Construct.getMutablePieces());
2070 
2071     // Redirect all call pieces to have valid locations.
2072     adjustCallLocations(Construct.getMutablePieces());
2073     removePiecesWithInvalidLocations(Construct.getMutablePieces());
2074 
2075     if (PDC->shouldAddPathEdges()) {
2076 
2077       // Reduce the number of edges from a very conservative set
2078       // to an aesthetically pleasing subset that conveys the
2079       // necessary information.
2080       OptimizedCallsSet OCS;
2081       while (optimizeEdges(Construct, Construct.getMutablePieces(), OCS)) {
2082       }
2083 
2084       // Drop the very first function-entry edge. It's not really necessary
2085       // for top-level functions.
2086       dropFunctionEntryEdge(Construct, Construct.getMutablePieces());
2087     }
2088 
2089     // Remove messages that are basically the same, and edges that may not
2090     // make sense.
2091     // We have to do this after edge optimization in the Extensive mode.
2092     removeRedundantMsgs(Construct.getMutablePieces());
2093     removeEdgesToDefaultInitializers(Construct.getMutablePieces());
2094   }
2095 
2096   if (Opts.ShouldDisplayMacroExpansions)
2097     CompactMacroExpandedPieces(Construct.getMutablePieces(), SM);
2098 
2099   return std::move(Construct.PD);
2100 }
2101 
2102 //===----------------------------------------------------------------------===//
2103 // Methods for BugType and subclasses.
2104 //===----------------------------------------------------------------------===//
2105 
2106 void BugType::anchor() {}
2107 
2108 void BuiltinBug::anchor() {}
2109 
2110 //===----------------------------------------------------------------------===//
2111 // Methods for BugReport and subclasses.
2112 //===----------------------------------------------------------------------===//
2113 
2114 LLVM_ATTRIBUTE_USED static bool
2115 isDependency(const CheckerRegistryData &Registry, StringRef CheckerName) {
2116   for (const std::pair<StringRef, StringRef> &Pair : Registry.Dependencies) {
2117     if (Pair.second == CheckerName)
2118       return true;
2119   }
2120   return false;
2121 }
2122 
2123 LLVM_ATTRIBUTE_USED static bool isHidden(const CheckerRegistryData &Registry,
2124                                          StringRef CheckerName) {
2125   for (const CheckerInfo &Checker : Registry.Checkers) {
2126     if (Checker.FullName == CheckerName)
2127       return Checker.IsHidden;
2128   }
2129   llvm_unreachable(
2130       "Checker name not found in CheckerRegistry -- did you retrieve it "
2131       "correctly from CheckerManager::getCurrentCheckerName?");
2132 }
2133 
2134 PathSensitiveBugReport::PathSensitiveBugReport(
2135     const BugType &bt, StringRef shortDesc, StringRef desc,
2136     const ExplodedNode *errorNode, PathDiagnosticLocation LocationToUnique,
2137     const Decl *DeclToUnique)
2138     : BugReport(Kind::PathSensitive, bt, shortDesc, desc), ErrorNode(errorNode),
2139       ErrorNodeRange(getStmt() ? getStmt()->getSourceRange() : SourceRange()),
2140       UniqueingLocation(LocationToUnique), UniqueingDecl(DeclToUnique) {
2141   assert(!isDependency(ErrorNode->getState()
2142                            ->getAnalysisManager()
2143                            .getCheckerManager()
2144                            ->getCheckerRegistryData(),
2145                        bt.getCheckerName()) &&
2146          "Some checkers depend on this one! We don't allow dependency "
2147          "checkers to emit warnings, because checkers should depend on "
2148          "*modeling*, not *diagnostics*.");
2149 
2150   assert(
2151       (bt.getCheckerName().startswith("debug") ||
2152        !isHidden(ErrorNode->getState()
2153                      ->getAnalysisManager()
2154                      .getCheckerManager()
2155                      ->getCheckerRegistryData(),
2156                  bt.getCheckerName())) &&
2157           "Hidden checkers musn't emit diagnostics as they are by definition "
2158           "non-user facing!");
2159 }
2160 
2161 void PathSensitiveBugReport::addVisitor(
2162     std::unique_ptr<BugReporterVisitor> visitor) {
2163   if (!visitor)
2164     return;
2165 
2166   llvm::FoldingSetNodeID ID;
2167   visitor->Profile(ID);
2168 
2169   void *InsertPos = nullptr;
2170   if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
2171     return;
2172   }
2173 
2174   Callbacks.push_back(std::move(visitor));
2175 }
2176 
2177 void PathSensitiveBugReport::clearVisitors() {
2178   Callbacks.clear();
2179 }
2180 
2181 const Decl *PathSensitiveBugReport::getDeclWithIssue() const {
2182   const ExplodedNode *N = getErrorNode();
2183   if (!N)
2184     return nullptr;
2185 
2186   const LocationContext *LC = N->getLocationContext();
2187   return LC->getStackFrame()->getDecl();
2188 }
2189 
2190 void BasicBugReport::Profile(llvm::FoldingSetNodeID& hash) const {
2191   hash.AddInteger(static_cast<int>(getKind()));
2192   hash.AddPointer(&BT);
2193   hash.AddString(Description);
2194   assert(Location.isValid());
2195   Location.Profile(hash);
2196 
2197   for (SourceRange range : Ranges) {
2198     if (!range.isValid())
2199       continue;
2200     hash.Add(range.getBegin());
2201     hash.Add(range.getEnd());
2202   }
2203 }
2204 
2205 void PathSensitiveBugReport::Profile(llvm::FoldingSetNodeID &hash) const {
2206   hash.AddInteger(static_cast<int>(getKind()));
2207   hash.AddPointer(&BT);
2208   hash.AddString(Description);
2209   PathDiagnosticLocation UL = getUniqueingLocation();
2210   if (UL.isValid()) {
2211     UL.Profile(hash);
2212   } else {
2213     // TODO: The statement may be null if the report was emitted before any
2214     // statements were executed. In particular, some checkers by design
2215     // occasionally emit their reports in empty functions (that have no
2216     // statements in their body). Do we profile correctly in this case?
2217     hash.AddPointer(ErrorNode->getCurrentOrPreviousStmtForDiagnostics());
2218   }
2219 
2220   for (SourceRange range : Ranges) {
2221     if (!range.isValid())
2222       continue;
2223     hash.Add(range.getBegin());
2224     hash.Add(range.getEnd());
2225   }
2226 }
2227 
2228 template <class T>
2229 static void insertToInterestingnessMap(
2230     llvm::DenseMap<T, bugreporter::TrackingKind> &InterestingnessMap, T Val,
2231     bugreporter::TrackingKind TKind) {
2232   auto Result = InterestingnessMap.insert({Val, TKind});
2233 
2234   if (Result.second)
2235     return;
2236 
2237   // Even if this symbol/region was already marked as interesting as a
2238   // condition, if we later mark it as interesting again but with
2239   // thorough tracking, overwrite it. Entities marked with thorough
2240   // interestiness are the most important (or most interesting, if you will),
2241   // and we wouldn't like to downplay their importance.
2242 
2243   switch (TKind) {
2244     case bugreporter::TrackingKind::Thorough:
2245       Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
2246       return;
2247     case bugreporter::TrackingKind::Condition:
2248       return;
2249     }
2250 
2251     llvm_unreachable(
2252         "BugReport::markInteresting currently can only handle 2 different "
2253         "tracking kinds! Please define what tracking kind should this entitiy"
2254         "have, if it was already marked as interesting with a different kind!");
2255 }
2256 
2257 void PathSensitiveBugReport::markInteresting(SymbolRef sym,
2258                                              bugreporter::TrackingKind TKind) {
2259   if (!sym)
2260     return;
2261 
2262   insertToInterestingnessMap(InterestingSymbols, sym, TKind);
2263 
2264   // FIXME: No tests exist for this code and it is questionable:
2265   // How to handle multiple metadata for the same region?
2266   if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2267     markInteresting(meta->getRegion(), TKind);
2268 }
2269 
2270 void PathSensitiveBugReport::markNotInteresting(SymbolRef sym) {
2271   if (!sym)
2272     return;
2273   InterestingSymbols.erase(sym);
2274 
2275   // The metadata part of markInteresting is not reversed here.
2276   // Just making the same region not interesting is incorrect
2277   // in specific cases.
2278   if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2279     markNotInteresting(meta->getRegion());
2280 }
2281 
2282 void PathSensitiveBugReport::markInteresting(const MemRegion *R,
2283                                              bugreporter::TrackingKind TKind) {
2284   if (!R)
2285     return;
2286 
2287   R = R->getBaseRegion();
2288   insertToInterestingnessMap(InterestingRegions, R, TKind);
2289 
2290   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2291     markInteresting(SR->getSymbol(), TKind);
2292 }
2293 
2294 void PathSensitiveBugReport::markNotInteresting(const MemRegion *R) {
2295   if (!R)
2296     return;
2297 
2298   R = R->getBaseRegion();
2299   InterestingRegions.erase(R);
2300 
2301   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2302     markNotInteresting(SR->getSymbol());
2303 }
2304 
2305 void PathSensitiveBugReport::markInteresting(SVal V,
2306                                              bugreporter::TrackingKind TKind) {
2307   markInteresting(V.getAsRegion(), TKind);
2308   markInteresting(V.getAsSymbol(), TKind);
2309 }
2310 
2311 void PathSensitiveBugReport::markInteresting(const LocationContext *LC) {
2312   if (!LC)
2313     return;
2314   InterestingLocationContexts.insert(LC);
2315 }
2316 
2317 Optional<bugreporter::TrackingKind>
2318 PathSensitiveBugReport::getInterestingnessKind(SVal V) const {
2319   auto RKind = getInterestingnessKind(V.getAsRegion());
2320   auto SKind = getInterestingnessKind(V.getAsSymbol());
2321   if (!RKind)
2322     return SKind;
2323   if (!SKind)
2324     return RKind;
2325 
2326   // If either is marked with throrough tracking, return that, we wouldn't like
2327   // to downplay a note's importance by 'only' mentioning it as a condition.
2328   switch(*RKind) {
2329     case bugreporter::TrackingKind::Thorough:
2330       return RKind;
2331     case bugreporter::TrackingKind::Condition:
2332       return SKind;
2333   }
2334 
2335   llvm_unreachable(
2336       "BugReport::getInterestingnessKind currently can only handle 2 different "
2337       "tracking kinds! Please define what tracking kind should we return here "
2338       "when the kind of getAsRegion() and getAsSymbol() is different!");
2339   return None;
2340 }
2341 
2342 Optional<bugreporter::TrackingKind>
2343 PathSensitiveBugReport::getInterestingnessKind(SymbolRef sym) const {
2344   if (!sym)
2345     return None;
2346   // We don't currently consider metadata symbols to be interesting
2347   // even if we know their region is interesting. Is that correct behavior?
2348   auto It = InterestingSymbols.find(sym);
2349   if (It == InterestingSymbols.end())
2350     return None;
2351   return It->getSecond();
2352 }
2353 
2354 Optional<bugreporter::TrackingKind>
2355 PathSensitiveBugReport::getInterestingnessKind(const MemRegion *R) const {
2356   if (!R)
2357     return None;
2358 
2359   R = R->getBaseRegion();
2360   auto It = InterestingRegions.find(R);
2361   if (It != InterestingRegions.end())
2362     return It->getSecond();
2363 
2364   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2365     return getInterestingnessKind(SR->getSymbol());
2366   return None;
2367 }
2368 
2369 bool PathSensitiveBugReport::isInteresting(SVal V) const {
2370   return getInterestingnessKind(V).hasValue();
2371 }
2372 
2373 bool PathSensitiveBugReport::isInteresting(SymbolRef sym) const {
2374   return getInterestingnessKind(sym).hasValue();
2375 }
2376 
2377 bool PathSensitiveBugReport::isInteresting(const MemRegion *R) const {
2378   return getInterestingnessKind(R).hasValue();
2379 }
2380 
2381 bool PathSensitiveBugReport::isInteresting(const LocationContext *LC)  const {
2382   if (!LC)
2383     return false;
2384   return InterestingLocationContexts.count(LC);
2385 }
2386 
2387 const Stmt *PathSensitiveBugReport::getStmt() const {
2388   if (!ErrorNode)
2389     return nullptr;
2390 
2391   ProgramPoint ProgP = ErrorNode->getLocation();
2392   const Stmt *S = nullptr;
2393 
2394   if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2395     CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2396     if (BE->getBlock() == &Exit)
2397       S = ErrorNode->getPreviousStmtForDiagnostics();
2398   }
2399   if (!S)
2400     S = ErrorNode->getStmtForDiagnostics();
2401 
2402   return S;
2403 }
2404 
2405 ArrayRef<SourceRange>
2406 PathSensitiveBugReport::getRanges() const {
2407   // If no custom ranges, add the range of the statement corresponding to
2408   // the error node.
2409   if (Ranges.empty() && isa_and_nonnull<Expr>(getStmt()))
2410       return ErrorNodeRange;
2411 
2412   return Ranges;
2413 }
2414 
2415 PathDiagnosticLocation
2416 PathSensitiveBugReport::getLocation() const {
2417   assert(ErrorNode && "Cannot create a location with a null node.");
2418   const Stmt *S = ErrorNode->getStmtForDiagnostics();
2419     ProgramPoint P = ErrorNode->getLocation();
2420   const LocationContext *LC = P.getLocationContext();
2421   SourceManager &SM =
2422       ErrorNode->getState()->getStateManager().getContext().getSourceManager();
2423 
2424   if (!S) {
2425     // If this is an implicit call, return the implicit call point location.
2426     if (Optional<PreImplicitCall> PIE = P.getAs<PreImplicitCall>())
2427       return PathDiagnosticLocation(PIE->getLocation(), SM);
2428     if (auto FE = P.getAs<FunctionExitPoint>()) {
2429       if (const ReturnStmt *RS = FE->getStmt())
2430         return PathDiagnosticLocation::createBegin(RS, SM, LC);
2431     }
2432     S = ErrorNode->getNextStmtForDiagnostics();
2433   }
2434 
2435   if (S) {
2436     // For member expressions, return the location of the '.' or '->'.
2437     if (const auto *ME = dyn_cast<MemberExpr>(S))
2438       return PathDiagnosticLocation::createMemberLoc(ME, SM);
2439 
2440     // For binary operators, return the location of the operator.
2441     if (const auto *B = dyn_cast<BinaryOperator>(S))
2442       return PathDiagnosticLocation::createOperatorLoc(B, SM);
2443 
2444     if (P.getAs<PostStmtPurgeDeadSymbols>())
2445       return PathDiagnosticLocation::createEnd(S, SM, LC);
2446 
2447     if (S->getBeginLoc().isValid())
2448       return PathDiagnosticLocation(S, SM, LC);
2449 
2450     return PathDiagnosticLocation(
2451         PathDiagnosticLocation::getValidSourceLocation(S, LC), SM);
2452   }
2453 
2454   return PathDiagnosticLocation::createDeclEnd(ErrorNode->getLocationContext(),
2455                                                SM);
2456 }
2457 
2458 //===----------------------------------------------------------------------===//
2459 // Methods for BugReporter and subclasses.
2460 //===----------------------------------------------------------------------===//
2461 
2462 const ExplodedGraph &PathSensitiveBugReporter::getGraph() const {
2463   return Eng.getGraph();
2464 }
2465 
2466 ProgramStateManager &PathSensitiveBugReporter::getStateManager() const {
2467   return Eng.getStateManager();
2468 }
2469 
2470 BugReporter::BugReporter(BugReporterData &d) : D(d) {}
2471 BugReporter::~BugReporter() {
2472   // Make sure reports are flushed.
2473   assert(StrBugTypes.empty() &&
2474          "Destroying BugReporter before diagnostics are emitted!");
2475 
2476   // Free the bug reports we are tracking.
2477   for (const auto I : EQClassesVector)
2478     delete I;
2479 }
2480 
2481 void BugReporter::FlushReports() {
2482   // We need to flush reports in deterministic order to ensure the order
2483   // of the reports is consistent between runs.
2484   for (const auto EQ : EQClassesVector)
2485     FlushReport(*EQ);
2486 
2487   // BugReporter owns and deletes only BugTypes created implicitly through
2488   // EmitBasicReport.
2489   // FIXME: There are leaks from checkers that assume that the BugTypes they
2490   // create will be destroyed by the BugReporter.
2491   StrBugTypes.clear();
2492 }
2493 
2494 //===----------------------------------------------------------------------===//
2495 // PathDiagnostics generation.
2496 //===----------------------------------------------------------------------===//
2497 
2498 namespace {
2499 
2500 /// A wrapper around an ExplodedGraph that contains a single path from the root
2501 /// to the error node.
2502 class BugPathInfo {
2503 public:
2504   std::unique_ptr<ExplodedGraph> BugPath;
2505   PathSensitiveBugReport *Report;
2506   const ExplodedNode *ErrorNode;
2507 };
2508 
2509 /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
2510 /// conveniently retrieve bug paths from a single error node to the root.
2511 class BugPathGetter {
2512   std::unique_ptr<ExplodedGraph> TrimmedGraph;
2513 
2514   using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
2515 
2516   /// Assign each node with its distance from the root.
2517   PriorityMapTy PriorityMap;
2518 
2519   /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
2520   /// we need to pair it to the error node of the constructed trimmed graph.
2521   using ReportNewNodePair =
2522       std::pair<PathSensitiveBugReport *, const ExplodedNode *>;
2523   SmallVector<ReportNewNodePair, 32> ReportNodes;
2524 
2525   BugPathInfo CurrentBugPath;
2526 
2527   /// A helper class for sorting ExplodedNodes by priority.
2528   template <bool Descending>
2529   class PriorityCompare {
2530     const PriorityMapTy &PriorityMap;
2531 
2532   public:
2533     PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2534 
2535     bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2536       PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2537       PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2538       PriorityMapTy::const_iterator E = PriorityMap.end();
2539 
2540       if (LI == E)
2541         return Descending;
2542       if (RI == E)
2543         return !Descending;
2544 
2545       return Descending ? LI->second > RI->second
2546                         : LI->second < RI->second;
2547     }
2548 
2549     bool operator()(const ReportNewNodePair &LHS,
2550                     const ReportNewNodePair &RHS) const {
2551       return (*this)(LHS.second, RHS.second);
2552     }
2553   };
2554 
2555 public:
2556   BugPathGetter(const ExplodedGraph *OriginalGraph,
2557                 ArrayRef<PathSensitiveBugReport *> &bugReports);
2558 
2559   BugPathInfo *getNextBugPath();
2560 };
2561 
2562 } // namespace
2563 
2564 BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
2565                              ArrayRef<PathSensitiveBugReport *> &bugReports) {
2566   SmallVector<const ExplodedNode *, 32> Nodes;
2567   for (const auto I : bugReports) {
2568     assert(I->isValid() &&
2569            "We only allow BugReporterVisitors and BugReporter itself to "
2570            "invalidate reports!");
2571     Nodes.emplace_back(I->getErrorNode());
2572   }
2573 
2574   // The trimmed graph is created in the body of the constructor to ensure
2575   // that the DenseMaps have been initialized already.
2576   InterExplodedGraphMap ForwardMap;
2577   TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap);
2578 
2579   // Find the (first) error node in the trimmed graph.  We just need to consult
2580   // the node map which maps from nodes in the original graph to nodes
2581   // in the new graph.
2582   llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
2583 
2584   for (PathSensitiveBugReport *Report : bugReports) {
2585     const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
2586     assert(NewNode &&
2587            "Failed to construct a trimmed graph that contains this error "
2588            "node!");
2589     ReportNodes.emplace_back(Report, NewNode);
2590     RemainingNodes.insert(NewNode);
2591   }
2592 
2593   assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
2594 
2595   // Perform a forward BFS to find all the shortest paths.
2596   std::queue<const ExplodedNode *> WS;
2597 
2598   assert(TrimmedGraph->num_roots() == 1);
2599   WS.push(*TrimmedGraph->roots_begin());
2600   unsigned Priority = 0;
2601 
2602   while (!WS.empty()) {
2603     const ExplodedNode *Node = WS.front();
2604     WS.pop();
2605 
2606     PriorityMapTy::iterator PriorityEntry;
2607     bool IsNew;
2608     std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
2609     ++Priority;
2610 
2611     if (!IsNew) {
2612       assert(PriorityEntry->second <= Priority);
2613       continue;
2614     }
2615 
2616     if (RemainingNodes.erase(Node))
2617       if (RemainingNodes.empty())
2618         break;
2619 
2620     for (const ExplodedNode *Succ : Node->succs())
2621       WS.push(Succ);
2622   }
2623 
2624   // Sort the error paths from longest to shortest.
2625   llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
2626 }
2627 
2628 BugPathInfo *BugPathGetter::getNextBugPath() {
2629   if (ReportNodes.empty())
2630     return nullptr;
2631 
2632   const ExplodedNode *OrigN;
2633   std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
2634   assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2635          "error node not accessible from root");
2636 
2637   // Create a new graph with a single path. This is the graph that will be
2638   // returned to the caller.
2639   auto GNew = std::make_unique<ExplodedGraph>();
2640 
2641   // Now walk from the error node up the BFS path, always taking the
2642   // predeccessor with the lowest number.
2643   ExplodedNode *Succ = nullptr;
2644   while (true) {
2645     // Create the equivalent node in the new graph with the same state
2646     // and location.
2647     ExplodedNode *NewN = GNew->createUncachedNode(
2648         OrigN->getLocation(), OrigN->getState(),
2649         OrigN->getID(), OrigN->isSink());
2650 
2651     // Link up the new node with the previous node.
2652     if (Succ)
2653       Succ->addPredecessor(NewN, *GNew);
2654     else
2655       CurrentBugPath.ErrorNode = NewN;
2656 
2657     Succ = NewN;
2658 
2659     // Are we at the final node?
2660     if (OrigN->pred_empty()) {
2661       GNew->addRoot(NewN);
2662       break;
2663     }
2664 
2665     // Find the next predeccessor node.  We choose the node that is marked
2666     // with the lowest BFS number.
2667     OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2668                               PriorityCompare<false>(PriorityMap));
2669   }
2670 
2671   CurrentBugPath.BugPath = std::move(GNew);
2672 
2673   return &CurrentBugPath;
2674 }
2675 
2676 /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
2677 /// object and collapses PathDiagosticPieces that are expanded by macros.
2678 static void CompactMacroExpandedPieces(PathPieces &path,
2679                                        const SourceManager& SM) {
2680   using MacroStackTy = std::vector<
2681       std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
2682 
2683   using PiecesTy = std::vector<PathDiagnosticPieceRef>;
2684 
2685   MacroStackTy MacroStack;
2686   PiecesTy Pieces;
2687 
2688   for (PathPieces::const_iterator I = path.begin(), E = path.end();
2689        I != E; ++I) {
2690     const auto &piece = *I;
2691 
2692     // Recursively compact calls.
2693     if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
2694       CompactMacroExpandedPieces(call->path, SM);
2695     }
2696 
2697     // Get the location of the PathDiagnosticPiece.
2698     const FullSourceLoc Loc = piece->getLocation().asLocation();
2699 
2700     // Determine the instantiation location, which is the location we group
2701     // related PathDiagnosticPieces.
2702     SourceLocation InstantiationLoc = Loc.isMacroID() ?
2703                                       SM.getExpansionLoc(Loc) :
2704                                       SourceLocation();
2705 
2706     if (Loc.isFileID()) {
2707       MacroStack.clear();
2708       Pieces.push_back(piece);
2709       continue;
2710     }
2711 
2712     assert(Loc.isMacroID());
2713 
2714     // Is the PathDiagnosticPiece within the same macro group?
2715     if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2716       MacroStack.back().first->subPieces.push_back(piece);
2717       continue;
2718     }
2719 
2720     // We aren't in the same group.  Are we descending into a new macro
2721     // or are part of an old one?
2722     std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
2723 
2724     SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2725                                           SM.getExpansionLoc(Loc) :
2726                                           SourceLocation();
2727 
2728     // Walk the entire macro stack.
2729     while (!MacroStack.empty()) {
2730       if (InstantiationLoc == MacroStack.back().second) {
2731         MacroGroup = MacroStack.back().first;
2732         break;
2733       }
2734 
2735       if (ParentInstantiationLoc == MacroStack.back().second) {
2736         MacroGroup = MacroStack.back().first;
2737         break;
2738       }
2739 
2740       MacroStack.pop_back();
2741     }
2742 
2743     if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2744       // Create a new macro group and add it to the stack.
2745       auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
2746           PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2747 
2748       if (MacroGroup)
2749         MacroGroup->subPieces.push_back(NewGroup);
2750       else {
2751         assert(InstantiationLoc.isFileID());
2752         Pieces.push_back(NewGroup);
2753       }
2754 
2755       MacroGroup = NewGroup;
2756       MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2757     }
2758 
2759     // Finally, add the PathDiagnosticPiece to the group.
2760     MacroGroup->subPieces.push_back(piece);
2761   }
2762 
2763   // Now take the pieces and construct a new PathDiagnostic.
2764   path.clear();
2765 
2766   path.insert(path.end(), Pieces.begin(), Pieces.end());
2767 }
2768 
2769 /// Generate notes from all visitors.
2770 /// Notes associated with @c ErrorNode are generated using
2771 /// @c getEndPath, and the rest are generated with @c VisitNode.
2772 static std::unique_ptr<VisitorsDiagnosticsTy>
2773 generateVisitorsDiagnostics(PathSensitiveBugReport *R,
2774                             const ExplodedNode *ErrorNode,
2775                             BugReporterContext &BRC) {
2776   std::unique_ptr<VisitorsDiagnosticsTy> Notes =
2777       std::make_unique<VisitorsDiagnosticsTy>();
2778   PathSensitiveBugReport::VisitorList visitors;
2779 
2780   // Run visitors on all nodes starting from the node *before* the last one.
2781   // The last node is reserved for notes generated with @c getEndPath.
2782   const ExplodedNode *NextNode = ErrorNode->getFirstPred();
2783   while (NextNode) {
2784 
2785     // At each iteration, move all visitors from report to visitor list. This is
2786     // important, because the Profile() functions of the visitors make sure that
2787     // a visitor isn't added multiple times for the same node, but it's fine
2788     // to add the a visitor with Profile() for different nodes (e.g. tracking
2789     // a region at different points of the symbolic execution).
2790     for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
2791       visitors.push_back(std::move(Visitor));
2792 
2793     R->clearVisitors();
2794 
2795     const ExplodedNode *Pred = NextNode->getFirstPred();
2796     if (!Pred) {
2797       PathDiagnosticPieceRef LastPiece;
2798       for (auto &V : visitors) {
2799         V->finalizeVisitor(BRC, ErrorNode, *R);
2800 
2801         if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
2802           assert(!LastPiece &&
2803                  "There can only be one final piece in a diagnostic.");
2804           assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
2805                  "The final piece must contain a message!");
2806           LastPiece = std::move(Piece);
2807           (*Notes)[ErrorNode].push_back(LastPiece);
2808         }
2809       }
2810       break;
2811     }
2812 
2813     for (auto &V : visitors) {
2814       auto P = V->VisitNode(NextNode, BRC, *R);
2815       if (P)
2816         (*Notes)[NextNode].push_back(std::move(P));
2817     }
2818 
2819     if (!R->isValid())
2820       break;
2821 
2822     NextNode = Pred;
2823   }
2824 
2825   return Notes;
2826 }
2827 
2828 Optional<PathDiagnosticBuilder> PathDiagnosticBuilder::findValidReport(
2829     ArrayRef<PathSensitiveBugReport *> &bugReports,
2830     PathSensitiveBugReporter &Reporter) {
2831 
2832   BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
2833 
2834   while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
2835     // Find the BugReport with the original location.
2836     PathSensitiveBugReport *R = BugPath->Report;
2837     assert(R && "No original report found for sliced graph.");
2838     assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2839     const ExplodedNode *ErrorNode = BugPath->ErrorNode;
2840 
2841     // Register refutation visitors first, if they mark the bug invalid no
2842     // further analysis is required
2843     R->addVisitor<LikelyFalsePositiveSuppressionBRVisitor>();
2844 
2845     // Register additional node visitors.
2846     R->addVisitor<NilReceiverBRVisitor>();
2847     R->addVisitor<ConditionBRVisitor>();
2848     R->addVisitor<TagVisitor>();
2849 
2850     BugReporterContext BRC(Reporter);
2851 
2852     // Run all visitors on a given graph, once.
2853     std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
2854         generateVisitorsDiagnostics(R, ErrorNode, BRC);
2855 
2856     if (R->isValid()) {
2857       if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
2858         // If crosscheck is enabled, remove all visitors, add the refutation
2859         // visitor and check again
2860         R->clearVisitors();
2861         R->addVisitor<FalsePositiveRefutationBRVisitor>();
2862 
2863         // We don't overwrite the notes inserted by other visitors because the
2864         // refutation manager does not add any new note to the path
2865         generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
2866       }
2867 
2868       // Check if the bug is still valid
2869       if (R->isValid())
2870         return PathDiagnosticBuilder(
2871             std::move(BRC), std::move(BugPath->BugPath), BugPath->Report,
2872             BugPath->ErrorNode, std::move(visitorNotes));
2873     }
2874   }
2875 
2876   return {};
2877 }
2878 
2879 std::unique_ptr<DiagnosticForConsumerMapTy>
2880 PathSensitiveBugReporter::generatePathDiagnostics(
2881     ArrayRef<PathDiagnosticConsumer *> consumers,
2882     ArrayRef<PathSensitiveBugReport *> &bugReports) {
2883   assert(!bugReports.empty());
2884 
2885   auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
2886 
2887   Optional<PathDiagnosticBuilder> PDB =
2888       PathDiagnosticBuilder::findValidReport(bugReports, *this);
2889 
2890   if (PDB) {
2891     for (PathDiagnosticConsumer *PC : consumers) {
2892       if (std::unique_ptr<PathDiagnostic> PD = PDB->generate(PC)) {
2893         (*Out)[PC] = std::move(PD);
2894       }
2895     }
2896   }
2897 
2898   return Out;
2899 }
2900 
2901 void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
2902   bool ValidSourceLoc = R->getLocation().isValid();
2903   assert(ValidSourceLoc);
2904   // If we mess up in a release build, we'd still prefer to just drop the bug
2905   // instead of trying to go on.
2906   if (!ValidSourceLoc)
2907     return;
2908 
2909   // Compute the bug report's hash to determine its equivalence class.
2910   llvm::FoldingSetNodeID ID;
2911   R->Profile(ID);
2912 
2913   // Lookup the equivance class.  If there isn't one, create it.
2914   void *InsertPos;
2915   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2916 
2917   if (!EQ) {
2918     EQ = new BugReportEquivClass(std::move(R));
2919     EQClasses.InsertNode(EQ, InsertPos);
2920     EQClassesVector.push_back(EQ);
2921   } else
2922     EQ->AddReport(std::move(R));
2923 }
2924 
2925 void PathSensitiveBugReporter::emitReport(std::unique_ptr<BugReport> R) {
2926   if (auto PR = dyn_cast<PathSensitiveBugReport>(R.get()))
2927     if (const ExplodedNode *E = PR->getErrorNode()) {
2928       // An error node must either be a sink or have a tag, otherwise
2929       // it could get reclaimed before the path diagnostic is created.
2930       assert((E->isSink() || E->getLocation().getTag()) &&
2931              "Error node must either be a sink or have a tag");
2932 
2933       const AnalysisDeclContext *DeclCtx =
2934           E->getLocationContext()->getAnalysisDeclContext();
2935       // The source of autosynthesized body can be handcrafted AST or a model
2936       // file. The locations from handcrafted ASTs have no valid source
2937       // locations and have to be discarded. Locations from model files should
2938       // be preserved for processing and reporting.
2939       if (DeclCtx->isBodyAutosynthesized() &&
2940           !DeclCtx->isBodyAutosynthesizedFromModelFile())
2941         return;
2942     }
2943 
2944   BugReporter::emitReport(std::move(R));
2945 }
2946 
2947 //===----------------------------------------------------------------------===//
2948 // Emitting reports in equivalence classes.
2949 //===----------------------------------------------------------------------===//
2950 
2951 namespace {
2952 
2953 struct FRIEC_WLItem {
2954   const ExplodedNode *N;
2955   ExplodedNode::const_succ_iterator I, E;
2956 
2957   FRIEC_WLItem(const ExplodedNode *n)
2958       : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2959 };
2960 
2961 } // namespace
2962 
2963 BugReport *PathSensitiveBugReporter::findReportInEquivalenceClass(
2964     BugReportEquivClass &EQ, SmallVectorImpl<BugReport *> &bugReports) {
2965   // If we don't need to suppress any of the nodes because they are
2966   // post-dominated by a sink, simply add all the nodes in the equivalence class
2967   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2968   assert(EQ.getReports().size() > 0);
2969   const BugType& BT = EQ.getReports()[0]->getBugType();
2970   if (!BT.isSuppressOnSink()) {
2971     BugReport *R = EQ.getReports()[0].get();
2972     for (auto &J : EQ.getReports()) {
2973       if (auto *PR = dyn_cast<PathSensitiveBugReport>(J.get())) {
2974         R = PR;
2975         bugReports.push_back(PR);
2976       }
2977     }
2978     return R;
2979   }
2980 
2981   // For bug reports that should be suppressed when all paths are post-dominated
2982   // by a sink node, iterate through the reports in the equivalence class
2983   // until we find one that isn't post-dominated (if one exists).  We use a
2984   // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2985   // this as a recursive function, but we don't want to risk blowing out the
2986   // stack for very long paths.
2987   BugReport *exampleReport = nullptr;
2988 
2989   for (const auto &I: EQ.getReports()) {
2990     auto *R = dyn_cast<PathSensitiveBugReport>(I.get());
2991     if (!R)
2992       continue;
2993 
2994     const ExplodedNode *errorNode = R->getErrorNode();
2995     if (errorNode->isSink()) {
2996       llvm_unreachable(
2997            "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2998     }
2999     // No successors?  By definition this nodes isn't post-dominated by a sink.
3000     if (errorNode->succ_empty()) {
3001       bugReports.push_back(R);
3002       if (!exampleReport)
3003         exampleReport = R;
3004       continue;
3005     }
3006 
3007     // See if we are in a no-return CFG block. If so, treat this similarly
3008     // to being post-dominated by a sink. This works better when the analysis
3009     // is incomplete and we have never reached the no-return function call(s)
3010     // that we'd inevitably bump into on this path.
3011     if (const CFGBlock *ErrorB = errorNode->getCFGBlock())
3012       if (ErrorB->isInevitablySinking())
3013         continue;
3014 
3015     // At this point we know that 'N' is not a sink and it has at least one
3016     // successor.  Use a DFS worklist to find a non-sink end-of-path node.
3017     using WLItem = FRIEC_WLItem;
3018     using DFSWorkList = SmallVector<WLItem, 10>;
3019 
3020     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
3021 
3022     DFSWorkList WL;
3023     WL.push_back(errorNode);
3024     Visited[errorNode] = 1;
3025 
3026     while (!WL.empty()) {
3027       WLItem &WI = WL.back();
3028       assert(!WI.N->succ_empty());
3029 
3030       for (; WI.I != WI.E; ++WI.I) {
3031         const ExplodedNode *Succ = *WI.I;
3032         // End-of-path node?
3033         if (Succ->succ_empty()) {
3034           // If we found an end-of-path node that is not a sink.
3035           if (!Succ->isSink()) {
3036             bugReports.push_back(R);
3037             if (!exampleReport)
3038               exampleReport = R;
3039             WL.clear();
3040             break;
3041           }
3042           // Found a sink?  Continue on to the next successor.
3043           continue;
3044         }
3045         // Mark the successor as visited.  If it hasn't been explored,
3046         // enqueue it to the DFS worklist.
3047         unsigned &mark = Visited[Succ];
3048         if (!mark) {
3049           mark = 1;
3050           WL.push_back(Succ);
3051           break;
3052         }
3053       }
3054 
3055       // The worklist may have been cleared at this point.  First
3056       // check if it is empty before checking the last item.
3057       if (!WL.empty() && &WL.back() == &WI)
3058         WL.pop_back();
3059     }
3060   }
3061 
3062   // ExampleReport will be NULL if all the nodes in the equivalence class
3063   // were post-dominated by sinks.
3064   return exampleReport;
3065 }
3066 
3067 void BugReporter::FlushReport(BugReportEquivClass& EQ) {
3068   SmallVector<BugReport*, 10> bugReports;
3069   BugReport *report = findReportInEquivalenceClass(EQ, bugReports);
3070   if (!report)
3071     return;
3072 
3073   // See whether we need to silence the checker/package.
3074   for (const std::string &CheckerOrPackage :
3075        getAnalyzerOptions().SilencedCheckersAndPackages) {
3076     if (report->getBugType().getCheckerName().startswith(
3077             CheckerOrPackage))
3078       return;
3079   }
3080 
3081   ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
3082   std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
3083       generateDiagnosticForConsumerMap(report, Consumers, bugReports);
3084 
3085   for (auto &P : *Diagnostics) {
3086     PathDiagnosticConsumer *Consumer = P.first;
3087     std::unique_ptr<PathDiagnostic> &PD = P.second;
3088 
3089     // If the path is empty, generate a single step path with the location
3090     // of the issue.
3091     if (PD->path.empty()) {
3092       PathDiagnosticLocation L = report->getLocation();
3093       auto piece = std::make_unique<PathDiagnosticEventPiece>(
3094         L, report->getDescription());
3095       for (SourceRange Range : report->getRanges())
3096         piece->addRange(Range);
3097       PD->setEndOfPath(std::move(piece));
3098     }
3099 
3100     PathPieces &Pieces = PD->getMutablePieces();
3101     if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
3102       // For path diagnostic consumers that don't support extra notes,
3103       // we may optionally convert those to path notes.
3104       for (auto I = report->getNotes().rbegin(),
3105            E = report->getNotes().rend(); I != E; ++I) {
3106         PathDiagnosticNotePiece *Piece = I->get();
3107         auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
3108           Piece->getLocation(), Piece->getString());
3109         for (const auto &R: Piece->getRanges())
3110           ConvertedPiece->addRange(R);
3111 
3112         Pieces.push_front(std::move(ConvertedPiece));
3113       }
3114     } else {
3115       for (auto I = report->getNotes().rbegin(),
3116            E = report->getNotes().rend(); I != E; ++I)
3117         Pieces.push_front(*I);
3118     }
3119 
3120     for (const auto &I : report->getFixits())
3121       Pieces.back()->addFixit(I);
3122 
3123     updateExecutedLinesWithDiagnosticPieces(*PD);
3124     Consumer->HandlePathDiagnostic(std::move(PD));
3125   }
3126 }
3127 
3128 /// Insert all lines participating in the function signature \p Signature
3129 /// into \p ExecutedLines.
3130 static void populateExecutedLinesWithFunctionSignature(
3131     const Decl *Signature, const SourceManager &SM,
3132     FilesToLineNumsMap &ExecutedLines) {
3133   SourceRange SignatureSourceRange;
3134   const Stmt* Body = Signature->getBody();
3135   if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
3136     SignatureSourceRange = FD->getSourceRange();
3137   } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
3138     SignatureSourceRange = OD->getSourceRange();
3139   } else {
3140     return;
3141   }
3142   SourceLocation Start = SignatureSourceRange.getBegin();
3143   SourceLocation End = Body ? Body->getSourceRange().getBegin()
3144     : SignatureSourceRange.getEnd();
3145   if (!Start.isValid() || !End.isValid())
3146     return;
3147   unsigned StartLine = SM.getExpansionLineNumber(Start);
3148   unsigned EndLine = SM.getExpansionLineNumber(End);
3149 
3150   FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
3151   for (unsigned Line = StartLine; Line <= EndLine; Line++)
3152     ExecutedLines[FID].insert(Line);
3153 }
3154 
3155 static void populateExecutedLinesWithStmt(
3156     const Stmt *S, const SourceManager &SM,
3157     FilesToLineNumsMap &ExecutedLines) {
3158   SourceLocation Loc = S->getSourceRange().getBegin();
3159   if (!Loc.isValid())
3160     return;
3161   SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
3162   FileID FID = SM.getFileID(ExpansionLoc);
3163   unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
3164   ExecutedLines[FID].insert(LineNo);
3165 }
3166 
3167 /// \return all executed lines including function signatures on the path
3168 /// starting from \p N.
3169 static std::unique_ptr<FilesToLineNumsMap>
3170 findExecutedLines(const SourceManager &SM, const ExplodedNode *N) {
3171   auto ExecutedLines = std::make_unique<FilesToLineNumsMap>();
3172 
3173   while (N) {
3174     if (N->getFirstPred() == nullptr) {
3175       // First node: show signature of the entrance point.
3176       const Decl *D = N->getLocationContext()->getDecl();
3177       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
3178     } else if (auto CE = N->getLocationAs<CallEnter>()) {
3179       // Inlined function: show signature.
3180       const Decl* D = CE->getCalleeContext()->getDecl();
3181       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
3182     } else if (const Stmt *S = N->getStmtForDiagnostics()) {
3183       populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
3184 
3185       // Show extra context for some parent kinds.
3186       const Stmt *P = N->getParentMap().getParent(S);
3187 
3188       // The path exploration can die before the node with the associated
3189       // return statement is generated, but we do want to show the whole
3190       // return.
3191       if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
3192         populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
3193         P = N->getParentMap().getParent(RS);
3194       }
3195 
3196       if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
3197         populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
3198     }
3199 
3200     N = N->getFirstPred();
3201   }
3202   return ExecutedLines;
3203 }
3204 
3205 std::unique_ptr<DiagnosticForConsumerMapTy>
3206 BugReporter::generateDiagnosticForConsumerMap(
3207     BugReport *exampleReport, ArrayRef<PathDiagnosticConsumer *> consumers,
3208     ArrayRef<BugReport *> bugReports) {
3209   auto *basicReport = cast<BasicBugReport>(exampleReport);
3210   auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
3211   for (auto *Consumer : consumers)
3212     (*Out)[Consumer] = generateDiagnosticForBasicReport(basicReport);
3213   return Out;
3214 }
3215 
3216 static PathDiagnosticCallPiece *
3217 getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
3218                                 const SourceManager &SMgr) {
3219   SourceLocation CallLoc = CP->callEnter.asLocation();
3220 
3221   // If the call is within a macro, don't do anything (for now).
3222   if (CallLoc.isMacroID())
3223     return nullptr;
3224 
3225   assert(AnalysisManager::isInCodeFile(CallLoc, SMgr) &&
3226          "The call piece should not be in a header file.");
3227 
3228   // Check if CP represents a path through a function outside of the main file.
3229   if (!AnalysisManager::isInCodeFile(CP->callEnterWithin.asLocation(), SMgr))
3230     return CP;
3231 
3232   const PathPieces &Path = CP->path;
3233   if (Path.empty())
3234     return nullptr;
3235 
3236   // Check if the last piece in the callee path is a call to a function outside
3237   // of the main file.
3238   if (auto *CPInner = dyn_cast<PathDiagnosticCallPiece>(Path.back().get()))
3239     return getFirstStackedCallToHeaderFile(CPInner, SMgr);
3240 
3241   // Otherwise, the last piece is in the main file.
3242   return nullptr;
3243 }
3244 
3245 static void resetDiagnosticLocationToMainFile(PathDiagnostic &PD) {
3246   if (PD.path.empty())
3247     return;
3248 
3249   PathDiagnosticPiece *LastP = PD.path.back().get();
3250   assert(LastP);
3251   const SourceManager &SMgr = LastP->getLocation().getManager();
3252 
3253   // We only need to check if the report ends inside headers, if the last piece
3254   // is a call piece.
3255   if (auto *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
3256     CP = getFirstStackedCallToHeaderFile(CP, SMgr);
3257     if (CP) {
3258       // Mark the piece.
3259        CP->setAsLastInMainSourceFile();
3260 
3261       // Update the path diagnostic message.
3262       const auto *ND = dyn_cast<NamedDecl>(CP->getCallee());
3263       if (ND) {
3264         SmallString<200> buf;
3265         llvm::raw_svector_ostream os(buf);
3266         os << " (within a call to '" << ND->getDeclName() << "')";
3267         PD.appendToDesc(os.str());
3268       }
3269 
3270       // Reset the report containing declaration and location.
3271       PD.setDeclWithIssue(CP->getCaller());
3272       PD.setLocation(CP->getLocation());
3273 
3274       return;
3275     }
3276   }
3277 }
3278 
3279 
3280 
3281 std::unique_ptr<DiagnosticForConsumerMapTy>
3282 PathSensitiveBugReporter::generateDiagnosticForConsumerMap(
3283     BugReport *exampleReport, ArrayRef<PathDiagnosticConsumer *> consumers,
3284     ArrayRef<BugReport *> bugReports) {
3285   std::vector<BasicBugReport *> BasicBugReports;
3286   std::vector<PathSensitiveBugReport *> PathSensitiveBugReports;
3287   if (isa<BasicBugReport>(exampleReport))
3288     return BugReporter::generateDiagnosticForConsumerMap(exampleReport,
3289                                                          consumers, bugReports);
3290 
3291   // Generate the full path sensitive diagnostic, using the generation scheme
3292   // specified by the PathDiagnosticConsumer. Note that we have to generate
3293   // path diagnostics even for consumers which do not support paths, because
3294   // the BugReporterVisitors may mark this bug as a false positive.
3295   assert(!bugReports.empty());
3296   MaxBugClassSize.updateMax(bugReports.size());
3297 
3298   // Avoid copying the whole array because there may be a lot of reports.
3299   ArrayRef<PathSensitiveBugReport *> convertedArrayOfReports(
3300       reinterpret_cast<PathSensitiveBugReport *const *>(&*bugReports.begin()),
3301       reinterpret_cast<PathSensitiveBugReport *const *>(&*bugReports.end()));
3302   std::unique_ptr<DiagnosticForConsumerMapTy> Out = generatePathDiagnostics(
3303       consumers, convertedArrayOfReports);
3304 
3305   if (Out->empty())
3306     return Out;
3307 
3308   MaxValidBugClassSize.updateMax(bugReports.size());
3309 
3310   // Examine the report and see if the last piece is in a header. Reset the
3311   // report location to the last piece in the main source file.
3312   const AnalyzerOptions &Opts = getAnalyzerOptions();
3313   for (auto const &P : *Out)
3314     if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
3315       resetDiagnosticLocationToMainFile(*P.second);
3316 
3317   return Out;
3318 }
3319 
3320 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3321                                   const CheckerBase *Checker, StringRef Name,
3322                                   StringRef Category, StringRef Str,
3323                                   PathDiagnosticLocation Loc,
3324                                   ArrayRef<SourceRange> Ranges,
3325                                   ArrayRef<FixItHint> Fixits) {
3326   EmitBasicReport(DeclWithIssue, Checker->getCheckerName(), Name, Category, Str,
3327                   Loc, Ranges, Fixits);
3328 }
3329 
3330 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3331                                   CheckerNameRef CheckName,
3332                                   StringRef name, StringRef category,
3333                                   StringRef str, PathDiagnosticLocation Loc,
3334                                   ArrayRef<SourceRange> Ranges,
3335                                   ArrayRef<FixItHint> Fixits) {
3336   // 'BT' is owned by BugReporter.
3337   BugType *BT = getBugTypeForName(CheckName, name, category);
3338   auto R = std::make_unique<BasicBugReport>(*BT, str, Loc);
3339   R->setDeclWithIssue(DeclWithIssue);
3340   for (const auto &SR : Ranges)
3341     R->addRange(SR);
3342   for (const auto &FH : Fixits)
3343     R->addFixItHint(FH);
3344   emitReport(std::move(R));
3345 }
3346 
3347 BugType *BugReporter::getBugTypeForName(CheckerNameRef CheckName,
3348                                         StringRef name, StringRef category) {
3349   SmallString<136> fullDesc;
3350   llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
3351                                       << ":" << category;
3352   std::unique_ptr<BugType> &BT = StrBugTypes[fullDesc];
3353   if (!BT)
3354     BT = std::make_unique<BugType>(CheckName, name, category);
3355   return BT.get();
3356 }
3357