16a58efdfSEugene Zelenko //===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
2fa0734ecSArgyrios Kyrtzidis //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fa0734ecSArgyrios Kyrtzidis //
7fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
8fa0734ecSArgyrios Kyrtzidis //
9fa0734ecSArgyrios Kyrtzidis // This file defines BugReporter, a utility class for generating
10fa0734ecSArgyrios Kyrtzidis // PathDiagnostics.
11fa0734ecSArgyrios Kyrtzidis //
12fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
13fa0734ecSArgyrios Kyrtzidis
14f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
156a58efdfSEugene Zelenko #include "clang/AST/Decl.h"
166a58efdfSEugene Zelenko #include "clang/AST/DeclBase.h"
1711764ab4SBenjamin Kramer #include "clang/AST/DeclObjC.h"
18fa0734ecSArgyrios Kyrtzidis #include "clang/AST/Expr.h"
192ab0ac53SReid Kleckner #include "clang/AST/ExprCXX.h"
20fa0734ecSArgyrios Kyrtzidis #include "clang/AST/ParentMap.h"
216a58efdfSEugene Zelenko #include "clang/AST/Stmt.h"
222ab0ac53SReid Kleckner #include "clang/AST/StmtCXX.h"
235553d0d4SChandler Carruth #include "clang/AST/StmtObjC.h"
246a58efdfSEugene Zelenko #include "clang/Analysis/AnalysisDeclContext.h"
253a02247dSChandler Carruth #include "clang/Analysis/CFG.h"
260e0a8b4dSArtem Dergachev #include "clang/Analysis/CFGStmtMap.h"
27f0bb45faSArtem Dergachev #include "clang/Analysis/PathDiagnostic.h"
28fa0734ecSArgyrios Kyrtzidis #include "clang/Analysis/ProgramPoint.h"
296a58efdfSEugene Zelenko #include "clang/Basic/LLVM.h"
306a58efdfSEugene Zelenko #include "clang/Basic/SourceLocation.h"
313a02247dSChandler Carruth #include "clang/Basic/SourceManager.h"
326a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
336a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
343a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
356a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/Checker.h"
366a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/CheckerManager.h"
37b2956076SKirstóf Umann #include "clang/StaticAnalyzer/Core/CheckerRegistryData.h"
386a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
393a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
406a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
416a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
42de361df3SBalazs Benics #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
436a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
446a58efdfSEugene Zelenko #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
456a58efdfSEugene Zelenko #include "llvm/ADT/ArrayRef.h"
46fa0734ecSArgyrios Kyrtzidis #include "llvm/ADT/DenseMap.h"
476a58efdfSEugene Zelenko #include "llvm/ADT/DenseSet.h"
486a58efdfSEugene Zelenko #include "llvm/ADT/FoldingSet.h"
496a58efdfSEugene Zelenko #include "llvm/ADT/None.h"
506a58efdfSEugene Zelenko #include "llvm/ADT/Optional.h"
513a02247dSChandler Carruth #include "llvm/ADT/STLExtras.h"
526a58efdfSEugene Zelenko #include "llvm/ADT/SmallPtrSet.h"
533a02247dSChandler Carruth #include "llvm/ADT/SmallString.h"
546a58efdfSEugene Zelenko #include "llvm/ADT/SmallVector.h"
55a45fc811SJordan Rose #include "llvm/ADT/Statistic.h"
5676221c73SReid Kleckner #include "llvm/ADT/StringExtras.h"
576a58efdfSEugene Zelenko #include "llvm/ADT/StringRef.h"
586a58efdfSEugene Zelenko #include "llvm/ADT/iterator_range.h"
596a58efdfSEugene Zelenko #include "llvm/Support/Casting.h"
606a58efdfSEugene Zelenko #include "llvm/Support/Compiler.h"
616a58efdfSEugene Zelenko #include "llvm/Support/ErrorHandling.h"
626a58efdfSEugene Zelenko #include "llvm/Support/MemoryBuffer.h"
633a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h"
646a58efdfSEugene Zelenko #include <algorithm>
656a58efdfSEugene Zelenko #include <cassert>
666a58efdfSEugene Zelenko #include <cstddef>
676a58efdfSEugene Zelenko #include <iterator>
68dfca6f97SAhmed Charles #include <memory>
69fa0734ecSArgyrios Kyrtzidis #include <queue>
706a58efdfSEugene Zelenko #include <string>
716a58efdfSEugene Zelenko #include <tuple>
726a58efdfSEugene Zelenko #include <utility>
736a58efdfSEugene Zelenko #include <vector>
74fa0734ecSArgyrios Kyrtzidis
75fa0734ecSArgyrios Kyrtzidis using namespace clang;
76fa0734ecSArgyrios Kyrtzidis using namespace ento;
772f169e7cSArtem Dergachev using namespace llvm;
78fa0734ecSArgyrios Kyrtzidis
7910346667SChandler Carruth #define DEBUG_TYPE "BugReporter"
8010346667SChandler Carruth
81a45fc811SJordan Rose STATISTIC(MaxBugClassSize,
82a45fc811SJordan Rose "The maximum number of bug reports in the same equivalence class");
83a45fc811SJordan Rose STATISTIC(MaxValidBugClassSize,
84a45fc811SJordan Rose "The maximum number of bug reports in the same equivalence class "
85a45fc811SJordan Rose "where at least one report is valid (not suppressed)");
86a45fc811SJordan Rose
876a58efdfSEugene Zelenko BugReporterVisitor::~BugReporterVisitor() = default;
88fa0734ecSArgyrios Kyrtzidis
anchor()8968e081d6SDavid Blaikie void BugReporterContext::anchor() {}
9068e081d6SDavid Blaikie
91fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
92f9d75bedSKristof Umann // PathDiagnosticBuilder and its associated routines and helper objects.
93f9d75bedSKristof Umann //===----------------------------------------------------------------------===//
94f9d75bedSKristof Umann
95f9d75bedSKristof Umann namespace {
96f9d75bedSKristof Umann
97edb78859SKristof Umann /// A (CallPiece, node assiciated with its CallEnter) pair.
98edb78859SKristof Umann using CallWithEntry =
99f9d75bedSKristof Umann std::pair<PathDiagnosticCallPiece *, const ExplodedNode *>;
100edb78859SKristof Umann using CallWithEntryStack = SmallVector<CallWithEntry, 6>;
101f9d75bedSKristof Umann
102f9d75bedSKristof Umann /// Map from each node to the diagnostic pieces visitors emit for them.
103f9d75bedSKristof Umann using VisitorsDiagnosticsTy =
104f9d75bedSKristof Umann llvm::DenseMap<const ExplodedNode *, std::vector<PathDiagnosticPieceRef>>;
105f9d75bedSKristof Umann
106f9d75bedSKristof Umann /// A map from PathDiagnosticPiece to the LocationContext of the inlined
107f9d75bedSKristof Umann /// function call it represents.
108f9d75bedSKristof Umann using LocationContextMap =
109f9d75bedSKristof Umann llvm::DenseMap<const PathPieces *, const LocationContext *>;
110f9d75bedSKristof Umann
111f9d75bedSKristof Umann /// A helper class that contains everything needed to construct a
112f9d75bedSKristof Umann /// PathDiagnostic object. It does no much more then providing convenient
113f9d75bedSKristof Umann /// getters and some well placed asserts for extra security.
114edb78859SKristof Umann class PathDiagnosticConstruct {
115f9d75bedSKristof Umann /// The consumer we're constructing the bug report for.
116f9d75bedSKristof Umann const PathDiagnosticConsumer *Consumer;
117f9d75bedSKristof Umann /// Our current position in the bug path, which is owned by
118f9d75bedSKristof Umann /// PathDiagnosticBuilder.
119f9d75bedSKristof Umann const ExplodedNode *CurrentNode;
120f9d75bedSKristof Umann /// A mapping from parts of the bug path (for example, a function call, which
121f9d75bedSKristof Umann /// would span backwards from a CallExit to a CallEnter with the nodes in
122f9d75bedSKristof Umann /// between them) with the location contexts it is associated with.
123f9d75bedSKristof Umann LocationContextMap LCM;
124f9d75bedSKristof Umann const SourceManager &SM;
125f9d75bedSKristof Umann
126f9d75bedSKristof Umann public:
127f9d75bedSKristof Umann /// We keep stack of calls to functions as we're ascending the bug path.
128f9d75bedSKristof Umann /// TODO: PathDiagnostic has a stack doing the same thing, shouldn't we use
129f9d75bedSKristof Umann /// that instead?
130edb78859SKristof Umann CallWithEntryStack CallStack;
131f9d75bedSKristof Umann /// The bug report we're constructing. For ease of use, this field is kept
132f9d75bedSKristof Umann /// public, though some "shortcut" getters are provided for commonly used
133f9d75bedSKristof Umann /// methods of PathDiagnostic.
134f9d75bedSKristof Umann std::unique_ptr<PathDiagnostic> PD;
135f9d75bedSKristof Umann
136f9d75bedSKristof Umann public:
137edb78859SKristof Umann PathDiagnosticConstruct(const PathDiagnosticConsumer *PDC,
1382f169e7cSArtem Dergachev const ExplodedNode *ErrorNode,
1392f169e7cSArtem Dergachev const PathSensitiveBugReport *R);
140f9d75bedSKristof Umann
141f9d75bedSKristof Umann /// \returns the location context associated with the current position in the
142f9d75bedSKristof Umann /// bug path.
getCurrLocationContext() const143f9d75bedSKristof Umann const LocationContext *getCurrLocationContext() const {
144f9d75bedSKristof Umann assert(CurrentNode && "Already reached the root!");
145f9d75bedSKristof Umann return CurrentNode->getLocationContext();
146f9d75bedSKristof Umann }
147f9d75bedSKristof Umann
148f9d75bedSKristof Umann /// Same as getCurrLocationContext (they should always return the same
149f9d75bedSKristof Umann /// location context), but works after reaching the root of the bug path as
150f9d75bedSKristof Umann /// well.
getLocationContextForActivePath() const151f9d75bedSKristof Umann const LocationContext *getLocationContextForActivePath() const {
152f9d75bedSKristof Umann return LCM.find(&PD->getActivePath())->getSecond();
153f9d75bedSKristof Umann }
154f9d75bedSKristof Umann
getCurrentNode() const155f9d75bedSKristof Umann const ExplodedNode *getCurrentNode() const { return CurrentNode; }
156f9d75bedSKristof Umann
157f9d75bedSKristof Umann /// Steps the current node to its predecessor.
158f9d75bedSKristof Umann /// \returns whether we reached the root of the bug path.
ascendToPrevNode()159f9d75bedSKristof Umann bool ascendToPrevNode() {
160f9d75bedSKristof Umann CurrentNode = CurrentNode->getFirstPred();
161f9d75bedSKristof Umann return static_cast<bool>(CurrentNode);
162f9d75bedSKristof Umann }
163f9d75bedSKristof Umann
getParentMap() const164f9d75bedSKristof Umann const ParentMap &getParentMap() const {
165f9d75bedSKristof Umann return getCurrLocationContext()->getParentMap();
166f9d75bedSKristof Umann }
167f9d75bedSKristof Umann
getSourceManager() const168f9d75bedSKristof Umann const SourceManager &getSourceManager() const { return SM; }
169f9d75bedSKristof Umann
getParent(const Stmt * S) const170f9d75bedSKristof Umann const Stmt *getParent(const Stmt *S) const {
171f9d75bedSKristof Umann return getParentMap().getParent(S);
172f9d75bedSKristof Umann }
173f9d75bedSKristof Umann
updateLocCtxMap(const PathPieces * Path,const LocationContext * LC)174f9d75bedSKristof Umann void updateLocCtxMap(const PathPieces *Path, const LocationContext *LC) {
175f9d75bedSKristof Umann assert(Path && LC);
176f9d75bedSKristof Umann LCM[Path] = LC;
177f9d75bedSKristof Umann }
178f9d75bedSKristof Umann
getLocationContextFor(const PathPieces * Path) const179f9d75bedSKristof Umann const LocationContext *getLocationContextFor(const PathPieces *Path) const {
180f9d75bedSKristof Umann assert(LCM.count(Path) &&
181f9d75bedSKristof Umann "Failed to find the context associated with these pieces!");
182f9d75bedSKristof Umann return LCM.find(Path)->getSecond();
183f9d75bedSKristof Umann }
184f9d75bedSKristof Umann
isInLocCtxMap(const PathPieces * Path) const185f9d75bedSKristof Umann bool isInLocCtxMap(const PathPieces *Path) const { return LCM.count(Path); }
186f9d75bedSKristof Umann
getActivePath()187f9d75bedSKristof Umann PathPieces &getActivePath() { return PD->getActivePath(); }
getMutablePieces()188f9d75bedSKristof Umann PathPieces &getMutablePieces() { return PD->getMutablePieces(); }
189f9d75bedSKristof Umann
shouldAddPathEdges() const190f9d75bedSKristof Umann bool shouldAddPathEdges() const { return Consumer->shouldAddPathEdges(); }
shouldAddControlNotes() const19197bcafa2SValeriy Savchenko bool shouldAddControlNotes() const {
19297bcafa2SValeriy Savchenko return Consumer->shouldAddControlNotes();
19397bcafa2SValeriy Savchenko }
shouldGenerateDiagnostics() const194f9d75bedSKristof Umann bool shouldGenerateDiagnostics() const {
195f9d75bedSKristof Umann return Consumer->shouldGenerateDiagnostics();
196f9d75bedSKristof Umann }
supportsLogicalOpControlFlow() const197f9d75bedSKristof Umann bool supportsLogicalOpControlFlow() const {
198f9d75bedSKristof Umann return Consumer->supportsLogicalOpControlFlow();
199f9d75bedSKristof Umann }
200f9d75bedSKristof Umann };
201f9d75bedSKristof Umann
202f9d75bedSKristof Umann /// Contains every contextual information needed for constructing a
203e1117addSKristof Umann /// PathDiagnostic object for a given bug report. This class and its fields are
204e1117addSKristof Umann /// immutable, and passes a BugReportConstruct object around during the
205e1117addSKristof Umann /// construction.
206f9d75bedSKristof Umann class PathDiagnosticBuilder : public BugReporterContext {
207f9d75bedSKristof Umann /// A linear path from the error node to the root.
208f9d75bedSKristof Umann std::unique_ptr<const ExplodedGraph> BugPath;
209e1117addSKristof Umann /// The bug report we're describing. Visitors create their diagnostics with
210e1117addSKristof Umann /// them being the last entities being able to modify it (for example,
211e1117addSKristof Umann /// changing interestingness here would cause inconsistencies as to how this
212e1117addSKristof Umann /// file and visitors construct diagnostics), hence its const.
2132f169e7cSArtem Dergachev const PathSensitiveBugReport *R;
214f9d75bedSKristof Umann /// The leaf of the bug path. This isn't the same as the bug reports error
215f9d75bedSKristof Umann /// node, which refers to the *original* graph, not the bug path.
216f9d75bedSKristof Umann const ExplodedNode *const ErrorNode;
217f9d75bedSKristof Umann /// The diagnostic pieces visitors emitted, which is expected to be collected
218f9d75bedSKristof Umann /// by the time this builder is constructed.
219f9d75bedSKristof Umann std::unique_ptr<const VisitorsDiagnosticsTy> VisitorsDiagnostics;
220f9d75bedSKristof Umann
221f9d75bedSKristof Umann public:
222f9d75bedSKristof Umann /// Find a non-invalidated report for a given equivalence class, and returns
223f9d75bedSKristof Umann /// a PathDiagnosticBuilder able to construct bug reports for different
224f9d75bedSKristof Umann /// consumers. Returns None if no valid report is found.
225f9d75bedSKristof Umann static Optional<PathDiagnosticBuilder>
2262f169e7cSArtem Dergachev findValidReport(ArrayRef<PathSensitiveBugReport *> &bugReports,
227ee92f12fSArtem Dergachev PathSensitiveBugReporter &Reporter);
228f9d75bedSKristof Umann
229f9d75bedSKristof Umann PathDiagnosticBuilder(
230f9d75bedSKristof Umann BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
2312f169e7cSArtem Dergachev PathSensitiveBugReport *r, const ExplodedNode *ErrorNode,
232f9d75bedSKristof Umann std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics);
233f9d75bedSKristof Umann
234f9d75bedSKristof Umann /// This function is responsible for generating diagnostic pieces that are
235f9d75bedSKristof Umann /// *not* provided by bug report visitors.
236f9d75bedSKristof Umann /// These diagnostics may differ depending on the consumer's settings,
237f9d75bedSKristof Umann /// and are therefore constructed separately for each consumer.
238f9d75bedSKristof Umann ///
239f9d75bedSKristof Umann /// There are two path diagnostics generation modes: with adding edges (used
240f9d75bedSKristof Umann /// for plists) and without (used for HTML and text). When edges are added,
241f9d75bedSKristof Umann /// the path is modified to insert artificially generated edges.
242f9d75bedSKristof Umann /// Otherwise, more detailed diagnostics is emitted for block edges,
243f9d75bedSKristof Umann /// explaining the transitions in words.
244f9d75bedSKristof Umann std::unique_ptr<PathDiagnostic>
245f9d75bedSKristof Umann generate(const PathDiagnosticConsumer *PDC) const;
246f9d75bedSKristof Umann
247f9d75bedSKristof Umann private:
2488535b8ecSArtem Dergachev void updateStackPiecesWithMessage(PathDiagnosticPieceRef P,
2498535b8ecSArtem Dergachev const CallWithEntryStack &CallStack) const;
250edb78859SKristof Umann void generatePathDiagnosticsForNode(PathDiagnosticConstruct &C,
251f9d75bedSKristof Umann PathDiagnosticLocation &PrevLoc) const;
252f9d75bedSKristof Umann
253edb78859SKristof Umann void generateMinimalDiagForBlockEdge(PathDiagnosticConstruct &C,
254f9d75bedSKristof Umann BlockEdge BE) const;
255f9d75bedSKristof Umann
256f9d75bedSKristof Umann PathDiagnosticPieceRef
257edb78859SKristof Umann generateDiagForGotoOP(const PathDiagnosticConstruct &C, const Stmt *S,
258f9d75bedSKristof Umann PathDiagnosticLocation &Start) const;
259f9d75bedSKristof Umann
260f9d75bedSKristof Umann PathDiagnosticPieceRef
261edb78859SKristof Umann generateDiagForSwitchOP(const PathDiagnosticConstruct &C, const CFGBlock *Dst,
262f9d75bedSKristof Umann PathDiagnosticLocation &Start) const;
263f9d75bedSKristof Umann
264edb78859SKristof Umann PathDiagnosticPieceRef
265edb78859SKristof Umann generateDiagForBinaryOP(const PathDiagnosticConstruct &C, const Stmt *T,
266edb78859SKristof Umann const CFGBlock *Src, const CFGBlock *DstC) const;
267f9d75bedSKristof Umann
268edb78859SKristof Umann PathDiagnosticLocation
269edb78859SKristof Umann ExecutionContinues(const PathDiagnosticConstruct &C) const;
270f9d75bedSKristof Umann
271edb78859SKristof Umann PathDiagnosticLocation
272edb78859SKristof Umann ExecutionContinues(llvm::raw_string_ostream &os,
273edb78859SKristof Umann const PathDiagnosticConstruct &C) const;
274f9d75bedSKristof Umann
getBugReport() const2752f169e7cSArtem Dergachev const PathSensitiveBugReport *getBugReport() const { return R; }
276f9d75bedSKristof Umann };
277f9d75bedSKristof Umann
278f9d75bedSKristof Umann } // namespace
279f9d75bedSKristof Umann
280f9d75bedSKristof Umann //===----------------------------------------------------------------------===//
2818535b8ecSArtem Dergachev // Base implementation of stack hint generators.
2828535b8ecSArtem Dergachev //===----------------------------------------------------------------------===//
2838535b8ecSArtem Dergachev
2848535b8ecSArtem Dergachev StackHintGenerator::~StackHintGenerator() = default;
2858535b8ecSArtem Dergachev
getMessage(const ExplodedNode * N)2868535b8ecSArtem Dergachev std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
2878535b8ecSArtem Dergachev if (!N)
2888535b8ecSArtem Dergachev return getMessageForSymbolNotFound();
2898535b8ecSArtem Dergachev
2908535b8ecSArtem Dergachev ProgramPoint P = N->getLocation();
2918535b8ecSArtem Dergachev CallExitEnd CExit = P.castAs<CallExitEnd>();
2928535b8ecSArtem Dergachev
2938535b8ecSArtem Dergachev // FIXME: Use CallEvent to abstract this over all calls.
2948535b8ecSArtem Dergachev const Stmt *CallSite = CExit.getCalleeContext()->getCallSite();
2958535b8ecSArtem Dergachev const auto *CE = dyn_cast_or_null<CallExpr>(CallSite);
2968535b8ecSArtem Dergachev if (!CE)
2978535b8ecSArtem Dergachev return {};
2988535b8ecSArtem Dergachev
2998535b8ecSArtem Dergachev // Check if one of the parameters are set to the interesting symbol.
3008535b8ecSArtem Dergachev unsigned ArgIndex = 0;
3018535b8ecSArtem Dergachev for (CallExpr::const_arg_iterator I = CE->arg_begin(),
3028535b8ecSArtem Dergachev E = CE->arg_end(); I != E; ++I, ++ArgIndex){
3038535b8ecSArtem Dergachev SVal SV = N->getSVal(*I);
3048535b8ecSArtem Dergachev
3058535b8ecSArtem Dergachev // Check if the variable corresponding to the symbol is passed by value.
3068535b8ecSArtem Dergachev SymbolRef AS = SV.getAsLocSymbol();
3078535b8ecSArtem Dergachev if (AS == Sym) {
3088535b8ecSArtem Dergachev return getMessageForArg(*I, ArgIndex);
3098535b8ecSArtem Dergachev }
3108535b8ecSArtem Dergachev
3118535b8ecSArtem Dergachev // Check if the parameter is a pointer to the symbol.
3128535b8ecSArtem Dergachev if (Optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
3138535b8ecSArtem Dergachev // Do not attempt to dereference void*.
3148535b8ecSArtem Dergachev if ((*I)->getType()->isVoidPointerType())
3158535b8ecSArtem Dergachev continue;
3168535b8ecSArtem Dergachev SVal PSV = N->getState()->getSVal(Reg->getRegion());
3178535b8ecSArtem Dergachev SymbolRef AS = PSV.getAsLocSymbol();
3188535b8ecSArtem Dergachev if (AS == Sym) {
3198535b8ecSArtem Dergachev return getMessageForArg(*I, ArgIndex);
3208535b8ecSArtem Dergachev }
3218535b8ecSArtem Dergachev }
3228535b8ecSArtem Dergachev }
3238535b8ecSArtem Dergachev
3248535b8ecSArtem Dergachev // Check if we are returning the interesting symbol.
3258535b8ecSArtem Dergachev SVal SV = N->getSVal(CE);
3268535b8ecSArtem Dergachev SymbolRef RetSym = SV.getAsLocSymbol();
3278535b8ecSArtem Dergachev if (RetSym == Sym) {
3288535b8ecSArtem Dergachev return getMessageForReturn(CE);
3298535b8ecSArtem Dergachev }
3308535b8ecSArtem Dergachev
3318535b8ecSArtem Dergachev return getMessageForSymbolNotFound();
3328535b8ecSArtem Dergachev }
3338535b8ecSArtem Dergachev
getMessageForArg(const Expr * ArgE,unsigned ArgIndex)3348535b8ecSArtem Dergachev std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
3358535b8ecSArtem Dergachev unsigned ArgIndex) {
3368535b8ecSArtem Dergachev // Printed parameters start at 1, not 0.
3378535b8ecSArtem Dergachev ++ArgIndex;
3388535b8ecSArtem Dergachev
3398535b8ecSArtem Dergachev return (llvm::Twine(Msg) + " via " + std::to_string(ArgIndex) +
3408535b8ecSArtem Dergachev llvm::getOrdinalSuffix(ArgIndex) + " parameter").str();
3418535b8ecSArtem Dergachev }
3428535b8ecSArtem Dergachev
3438535b8ecSArtem Dergachev //===----------------------------------------------------------------------===//
3442429c6ffSTed Kremenek // Diagnostic cleanup.
3452429c6ffSTed Kremenek //===----------------------------------------------------------------------===//
3462429c6ffSTed Kremenek
347a5958869STed Kremenek static PathDiagnosticEventPiece *
eventsDescribeSameCondition(PathDiagnosticEventPiece * X,PathDiagnosticEventPiece * Y)348a5958869STed Kremenek eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
349a5958869STed Kremenek PathDiagnosticEventPiece *Y) {
350a5958869STed Kremenek // Prefer diagnostics that come from ConditionBRVisitor over
3510c33406aSArtem Dergachev // those that came from TrackConstraintBRVisitor,
3520c33406aSArtem Dergachev // unless the one from ConditionBRVisitor is
3530c33406aSArtem Dergachev // its generic fallback diagnostic.
354a5958869STed Kremenek const void *tagPreferred = ConditionBRVisitor::getTag();
355a5958869STed Kremenek const void *tagLesser = TrackConstraintBRVisitor::getTag();
356a5958869STed Kremenek
357a5958869STed Kremenek if (X->getLocation() != Y->getLocation())
3580dbb783cSCraig Topper return nullptr;
359a5958869STed Kremenek
360a5958869STed Kremenek if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
3610c33406aSArtem Dergachev return ConditionBRVisitor::isPieceMessageGeneric(X) ? Y : X;
362a5958869STed Kremenek
363a5958869STed Kremenek if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
3640c33406aSArtem Dergachev return ConditionBRVisitor::isPieceMessageGeneric(Y) ? X : Y;
365a5958869STed Kremenek
3660dbb783cSCraig Topper return nullptr;
367a5958869STed Kremenek }
368a5958869STed Kremenek
36980810268STed Kremenek /// An optimization pass over PathPieces that removes redundant diagnostics
37080810268STed Kremenek /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
37180810268STed Kremenek /// BugReporterVisitors use different methods to generate diagnostics, with
37280810268STed Kremenek /// one capable of emitting diagnostics in some cases but not in others. This
37380810268STed Kremenek /// can lead to redundant diagnostic pieces at the same point in a path.
removeRedundantMsgs(PathPieces & path)37480810268STed Kremenek static void removeRedundantMsgs(PathPieces &path) {
375a5958869STed Kremenek unsigned N = path.size();
376a5958869STed Kremenek if (N < 2)
377a5958869STed Kremenek return;
37880810268STed Kremenek // NOTE: this loop intentionally is not using an iterator. Instead, we
37980810268STed Kremenek // are streaming the path and modifying it in place. This is done by
38080810268STed Kremenek // grabbing the front, processing it, and if we decide to keep it append
38180810268STed Kremenek // it to the end of the path. The entire path is processed in this way.
382a5958869STed Kremenek for (unsigned i = 0; i < N; ++i) {
3830a0c275fSDavid Blaikie auto piece = std::move(path.front());
384a5958869STed Kremenek path.pop_front();
385a5958869STed Kremenek
386a5958869STed Kremenek switch (piece->getKind()) {
3878b70c4e5SArtem Dergachev case PathDiagnosticPiece::Call:
3880a0c275fSDavid Blaikie removeRedundantMsgs(cast<PathDiagnosticCallPiece>(*piece).path);
389a5958869STed Kremenek break;
3908b70c4e5SArtem Dergachev case PathDiagnosticPiece::Macro:
3910a0c275fSDavid Blaikie removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(*piece).subPieces);
392a5958869STed Kremenek break;
3938b70c4e5SArtem Dergachev case PathDiagnosticPiece::Event: {
394a5958869STed Kremenek if (i == N-1)
395a5958869STed Kremenek break;
396a5958869STed Kremenek
3976a58efdfSEugene Zelenko if (auto *nextEvent =
398f994cef8SAlp Toker dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
3996a58efdfSEugene Zelenko auto *event = cast<PathDiagnosticEventPiece>(piece.get());
400a5958869STed Kremenek // Check to see if we should keep one of the two pieces. If we
401a5958869STed Kremenek // come up with a preference, record which piece to keep, and consume
402a5958869STed Kremenek // another piece from the path.
4030a0c275fSDavid Blaikie if (auto *pieceToKeep =
404a5958869STed Kremenek eventsDescribeSameCondition(event, nextEvent)) {
4050a0c275fSDavid Blaikie piece = std::move(pieceToKeep == event ? piece : path.front());
406a5958869STed Kremenek path.pop_front();
407a5958869STed Kremenek ++i;
408a5958869STed Kremenek }
409a5958869STed Kremenek }
410a5958869STed Kremenek break;
411a5958869STed Kremenek }
4121d7ca677SCsaba Dabis case PathDiagnosticPiece::ControlFlow:
4138b70c4e5SArtem Dergachev case PathDiagnosticPiece::Note:
4141d7ca677SCsaba Dabis case PathDiagnosticPiece::PopUp:
4158b70c4e5SArtem Dergachev break;
416a5958869STed Kremenek }
4170a0c275fSDavid Blaikie path.push_back(std::move(piece));
418a5958869STed Kremenek }
419a5958869STed Kremenek }
420a5958869STed Kremenek
4212429c6ffSTed Kremenek /// Recursively scan through a path and prune out calls and macros pieces
4222429c6ffSTed Kremenek /// that aren't needed. Return true if afterwards the path contains
4239a339136SJordan Rose /// "interesting stuff" which means it shouldn't be pruned from the parent path.
removeUnneededCalls(const PathDiagnosticConstruct & C,PathPieces & pieces,const PathSensitiveBugReport * R,bool IsInteresting=false)424edb78859SKristof Umann static bool removeUnneededCalls(const PathDiagnosticConstruct &C,
4252f169e7cSArtem Dergachev PathPieces &pieces,
4262f169e7cSArtem Dergachev const PathSensitiveBugReport *R,
427c8b1d5f3SArtem Dergachev bool IsInteresting = false) {
428c8b1d5f3SArtem Dergachev bool containsSomethingInteresting = IsInteresting;
4292429c6ffSTed Kremenek const unsigned N = pieces.size();
4302429c6ffSTed Kremenek
4312429c6ffSTed Kremenek for (unsigned i = 0 ; i < N ; ++i) {
4322429c6ffSTed Kremenek // Remove the front piece from the path. If it is still something we
4332429c6ffSTed Kremenek // want to keep once we are done, we will push it back on the end.
4340a0c275fSDavid Blaikie auto piece = std::move(pieces.front());
4352429c6ffSTed Kremenek pieces.pop_front();
4362429c6ffSTed Kremenek
4370a8e00d4STed Kremenek switch (piece->getKind()) {
4380a8e00d4STed Kremenek case PathDiagnosticPiece::Call: {
4390a0c275fSDavid Blaikie auto &call = cast<PathDiagnosticCallPiece>(*piece);
4405d4ec363SAnna Zaks // Check if the location context is interesting.
441f9d75bedSKristof Umann if (!removeUnneededCalls(
442f9d75bedSKristof Umann C, call.path, R,
443f9d75bedSKristof Umann R->isInteresting(C.getLocationContextFor(&call.path))))
4442429c6ffSTed Kremenek continue;
44514f779c4STed Kremenek
4462429c6ffSTed Kremenek containsSomethingInteresting = true;
4470a8e00d4STed Kremenek break;
4482429c6ffSTed Kremenek }
4490a8e00d4STed Kremenek case PathDiagnosticPiece::Macro: {
4500a0c275fSDavid Blaikie auto ¯o = cast<PathDiagnosticMacroPiece>(*piece);
451f9d75bedSKristof Umann if (!removeUnneededCalls(C, macro.subPieces, R, IsInteresting))
4522429c6ffSTed Kremenek continue;
4532429c6ffSTed Kremenek containsSomethingInteresting = true;
4540a8e00d4STed Kremenek break;
4552429c6ffSTed Kremenek }
4560a8e00d4STed Kremenek case PathDiagnosticPiece::Event: {
4570a0c275fSDavid Blaikie auto &event = cast<PathDiagnosticEventPiece>(*piece);
45814f779c4STed Kremenek
4592429c6ffSTed Kremenek // We never throw away an event, but we do throw it away wholesale
4602429c6ffSTed Kremenek // as part of a path if we throw the entire path away.
4610a0c275fSDavid Blaikie containsSomethingInteresting |= !event.isPrunable();
4620a8e00d4STed Kremenek break;
4630a8e00d4STed Kremenek }
4640a8e00d4STed Kremenek case PathDiagnosticPiece::ControlFlow:
4658b70c4e5SArtem Dergachev case PathDiagnosticPiece::Note:
4661d7ca677SCsaba Dabis case PathDiagnosticPiece::PopUp:
4678b70c4e5SArtem Dergachev break;
4682429c6ffSTed Kremenek }
4692429c6ffSTed Kremenek
4700a0c275fSDavid Blaikie pieces.push_back(std::move(piece));
4712429c6ffSTed Kremenek }
4722429c6ffSTed Kremenek
4732429c6ffSTed Kremenek return containsSomethingInteresting;
4742429c6ffSTed Kremenek }
4752429c6ffSTed Kremenek
4761d7ca677SCsaba Dabis /// Same logic as above to remove extra pieces.
removePopUpNotes(PathPieces & Path)4771d7ca677SCsaba Dabis static void removePopUpNotes(PathPieces &Path) {
4781d7ca677SCsaba Dabis for (unsigned int i = 0; i < Path.size(); ++i) {
4791d7ca677SCsaba Dabis auto Piece = std::move(Path.front());
4801d7ca677SCsaba Dabis Path.pop_front();
4811d7ca677SCsaba Dabis if (!isa<PathDiagnosticPopUpPiece>(*Piece))
4821d7ca677SCsaba Dabis Path.push_back(std::move(Piece));
4831d7ca677SCsaba Dabis }
4841d7ca677SCsaba Dabis }
4851d7ca677SCsaba Dabis
48656138268SJordan Rose /// Returns true if the given decl has been implicitly given a body, either by
48756138268SJordan Rose /// the analyzer or by the compiler proper.
hasImplicitBody(const Decl * D)48856138268SJordan Rose static bool hasImplicitBody(const Decl *D) {
48956138268SJordan Rose assert(D);
49056138268SJordan Rose return D->isImplicit() || !D->hasBody();
49156138268SJordan Rose }
49256138268SJordan Rose
4939a339136SJordan Rose /// Recursively scan through a path and make sure that all call pieces have
494b1b95d94SAnna Zaks /// valid locations.
4950dbb783cSCraig Topper static void
adjustCallLocations(PathPieces & Pieces,PathDiagnosticLocation * LastCallLocation=nullptr)4960dbb783cSCraig Topper adjustCallLocations(PathPieces &Pieces,
4970dbb783cSCraig Topper PathDiagnosticLocation *LastCallLocation = nullptr) {
4986a58efdfSEugene Zelenko for (const auto &I : Pieces) {
4996a58efdfSEugene Zelenko auto *Call = dyn_cast<PathDiagnosticCallPiece>(I.get());
5009a339136SJordan Rose
5016a58efdfSEugene Zelenko if (!Call)
5029a339136SJordan Rose continue;
5039a339136SJordan Rose
5049a339136SJordan Rose if (LastCallLocation) {
50556138268SJordan Rose bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
50656138268SJordan Rose if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
5079a339136SJordan Rose Call->callEnter = *LastCallLocation;
50856138268SJordan Rose if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
5099a339136SJordan Rose Call->callReturn = *LastCallLocation;
5109a339136SJordan Rose }
5119a339136SJordan Rose
5129a339136SJordan Rose // Recursively clean out the subclass. Keep this call around if
5139a339136SJordan Rose // it contains any informative diagnostics.
5149a339136SJordan Rose PathDiagnosticLocation *ThisCallLocation;
51578328be4SJordan Rose if (Call->callEnterWithin.asLocation().isValid() &&
51656138268SJordan Rose !hasImplicitBody(Call->getCallee()))
5179a339136SJordan Rose ThisCallLocation = &Call->callEnterWithin;
5189a339136SJordan Rose else
5199a339136SJordan Rose ThisCallLocation = &Call->callEnter;
5209a339136SJordan Rose
5219a339136SJordan Rose assert(ThisCallLocation && "Outermost call has an invalid location");
5229a339136SJordan Rose adjustCallLocations(Call->path, ThisCallLocation);
5239a339136SJordan Rose }
5249a339136SJordan Rose }
5259a339136SJordan Rose
526ac07c8daSJordan Rose /// Remove edges in and out of C++ default initializer expressions. These are
527ac07c8daSJordan Rose /// for fields that have in-class initializers, as opposed to being initialized
528ac07c8daSJordan Rose /// explicitly in a constructor or braced list.
removeEdgesToDefaultInitializers(PathPieces & Pieces)529ac07c8daSJordan Rose static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
530ac07c8daSJordan Rose for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
5310a0c275fSDavid Blaikie if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
532ac07c8daSJordan Rose removeEdgesToDefaultInitializers(C->path);
533ac07c8daSJordan Rose
5340a0c275fSDavid Blaikie if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
535ac07c8daSJordan Rose removeEdgesToDefaultInitializers(M->subPieces);
536ac07c8daSJordan Rose
5370a0c275fSDavid Blaikie if (auto *CF = dyn_cast<PathDiagnosticControlFlowPiece>(I->get())) {
538ac07c8daSJordan Rose const Stmt *Start = CF->getStartLocation().asStmt();
539ac07c8daSJordan Rose const Stmt *End = CF->getEndLocation().asStmt();
54016be17adSBalazs Benics if (isa_and_nonnull<CXXDefaultInitExpr>(Start)) {
541ac07c8daSJordan Rose I = Pieces.erase(I);
542ac07c8daSJordan Rose continue;
54316be17adSBalazs Benics } else if (isa_and_nonnull<CXXDefaultInitExpr>(End)) {
544167e999bSBenjamin Kramer PathPieces::iterator Next = std::next(I);
545ac07c8daSJordan Rose if (Next != E) {
5460a0c275fSDavid Blaikie if (auto *NextCF =
5470a0c275fSDavid Blaikie dyn_cast<PathDiagnosticControlFlowPiece>(Next->get())) {
548ac07c8daSJordan Rose NextCF->setStartLocation(CF->getStartLocation());
549ac07c8daSJordan Rose }
550ac07c8daSJordan Rose }
551ac07c8daSJordan Rose I = Pieces.erase(I);
552ac07c8daSJordan Rose continue;
553ac07c8daSJordan Rose }
554ac07c8daSJordan Rose }
555ac07c8daSJordan Rose
556ac07c8daSJordan Rose I++;
557ac07c8daSJordan Rose }
558ac07c8daSJordan Rose }
559ac07c8daSJordan Rose
560b1b95d94SAnna Zaks /// Remove all pieces with invalid locations as these cannot be serialized.
561b1b95d94SAnna Zaks /// We might have pieces with invalid locations as a result of inlining Body
562b1b95d94SAnna Zaks /// Farm generated functions.
removePiecesWithInvalidLocations(PathPieces & Pieces)563b1b95d94SAnna Zaks static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
564de2ae19cSAnna Zaks for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
5650a0c275fSDavid Blaikie if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
566b1b95d94SAnna Zaks removePiecesWithInvalidLocations(C->path);
567b1b95d94SAnna Zaks
5680a0c275fSDavid Blaikie if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
569b1b95d94SAnna Zaks removePiecesWithInvalidLocations(M->subPieces);
570b1b95d94SAnna Zaks
571b1b95d94SAnna Zaks if (!(*I)->getLocation().isValid() ||
572b1b95d94SAnna Zaks !(*I)->getLocation().asLocation().isValid()) {
573de2ae19cSAnna Zaks I = Pieces.erase(I);
574b1b95d94SAnna Zaks continue;
575b1b95d94SAnna Zaks }
576de2ae19cSAnna Zaks I++;
577b1b95d94SAnna Zaks }
578b1b95d94SAnna Zaks }
579b1b95d94SAnna Zaks
ExecutionContinues(const PathDiagnosticConstruct & C) const580edb78859SKristof Umann PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
581edb78859SKristof Umann const PathDiagnosticConstruct &C) const {
5826b85f8e9SArtem Dergachev if (const Stmt *S = C.getCurrentNode()->getNextStmtForDiagnostics())
583f9d75bedSKristof Umann return PathDiagnosticLocation(S, getSourceManager(),
584f9d75bedSKristof Umann C.getCurrLocationContext());
585fa0734ecSArgyrios Kyrtzidis
586f9d75bedSKristof Umann return PathDiagnosticLocation::createDeclEnd(C.getCurrLocationContext(),
587fa0734ecSArgyrios Kyrtzidis getSourceManager());
588fa0734ecSArgyrios Kyrtzidis }
589fa0734ecSArgyrios Kyrtzidis
ExecutionContinues(llvm::raw_string_ostream & os,const PathDiagnosticConstruct & C) const590edb78859SKristof Umann PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
591edb78859SKristof Umann llvm::raw_string_ostream &os, const PathDiagnosticConstruct &C) const {
592fa0734ecSArgyrios Kyrtzidis // Slow, but probably doesn't matter.
593fa0734ecSArgyrios Kyrtzidis if (os.str().empty())
594fa0734ecSArgyrios Kyrtzidis os << ' ';
595fa0734ecSArgyrios Kyrtzidis
596f9d75bedSKristof Umann const PathDiagnosticLocation &Loc = ExecutionContinues(C);
597fa0734ecSArgyrios Kyrtzidis
598fa0734ecSArgyrios Kyrtzidis if (Loc.asStmt())
599fa0734ecSArgyrios Kyrtzidis os << "Execution continues on line "
600d48db211SChandler Carruth << getSourceManager().getExpansionLineNumber(Loc.asLocation())
601fa0734ecSArgyrios Kyrtzidis << '.';
602fa0734ecSArgyrios Kyrtzidis else {
603fa0734ecSArgyrios Kyrtzidis os << "Execution jumps to the end of the ";
604f9d75bedSKristof Umann const Decl *D = C.getCurrLocationContext()->getDecl();
605fa0734ecSArgyrios Kyrtzidis if (isa<ObjCMethodDecl>(D))
606fa0734ecSArgyrios Kyrtzidis os << "method";
607fa0734ecSArgyrios Kyrtzidis else if (isa<FunctionDecl>(D))
608fa0734ecSArgyrios Kyrtzidis os << "function";
609fa0734ecSArgyrios Kyrtzidis else {
610fa0734ecSArgyrios Kyrtzidis assert(isa<BlockDecl>(D));
611fa0734ecSArgyrios Kyrtzidis os << "anonymous block";
612fa0734ecSArgyrios Kyrtzidis }
613fa0734ecSArgyrios Kyrtzidis os << '.';
614fa0734ecSArgyrios Kyrtzidis }
615fa0734ecSArgyrios Kyrtzidis
616fa0734ecSArgyrios Kyrtzidis return Loc;
617fa0734ecSArgyrios Kyrtzidis }
618fa0734ecSArgyrios Kyrtzidis
getEnclosingParent(const Stmt * S,const ParentMap & PM)619b1db073dSJordan Rose static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
620fa0734ecSArgyrios Kyrtzidis if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
621b1db073dSJordan Rose return PM.getParentIgnoreParens(S);
622fa0734ecSArgyrios Kyrtzidis
623fa0734ecSArgyrios Kyrtzidis const Stmt *Parent = PM.getParentIgnoreParens(S);
624b1db073dSJordan Rose if (!Parent)
6250dbb783cSCraig Topper return nullptr;
626fa0734ecSArgyrios Kyrtzidis
627fa0734ecSArgyrios Kyrtzidis switch (Parent->getStmtClass()) {
628fa0734ecSArgyrios Kyrtzidis case Stmt::ForStmtClass:
629fa0734ecSArgyrios Kyrtzidis case Stmt::DoStmtClass:
630fa0734ecSArgyrios Kyrtzidis case Stmt::WhileStmtClass:
631b1db073dSJordan Rose case Stmt::ObjCForCollectionStmtClass:
632cf10ea8cSJordan Rose case Stmt::CXXForRangeStmtClass:
633b1db073dSJordan Rose return Parent;
634fa0734ecSArgyrios Kyrtzidis default:
635fa0734ecSArgyrios Kyrtzidis break;
636fa0734ecSArgyrios Kyrtzidis }
637fa0734ecSArgyrios Kyrtzidis
6380dbb783cSCraig Topper return nullptr;
639fa0734ecSArgyrios Kyrtzidis }
640fa0734ecSArgyrios Kyrtzidis
641b1db073dSJordan Rose static PathDiagnosticLocation
getEnclosingStmtLocation(const Stmt * S,const LocationContext * LC,bool allowNestedContexts=false)642f9d75bedSKristof Umann getEnclosingStmtLocation(const Stmt *S, const LocationContext *LC,
643f9d75bedSKristof Umann bool allowNestedContexts = false) {
644b1db073dSJordan Rose if (!S)
6456a58efdfSEugene Zelenko return {};
646fa0734ecSArgyrios Kyrtzidis
647f9d75bedSKristof Umann const SourceManager &SMgr = LC->getDecl()->getASTContext().getSourceManager();
648f9d75bedSKristof Umann
649f9d75bedSKristof Umann while (const Stmt *Parent = getEnclosingParent(S, LC->getParentMap())) {
650fa0734ecSArgyrios Kyrtzidis switch (Parent->getStmtClass()) {
651fa0734ecSArgyrios Kyrtzidis case Stmt::BinaryOperatorClass: {
6526a58efdfSEugene Zelenko const auto *B = cast<BinaryOperator>(Parent);
653fa0734ecSArgyrios Kyrtzidis if (B->isLogicalOp())
65406e80072SJordan Rose return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
655fa0734ecSArgyrios Kyrtzidis break;
656fa0734ecSArgyrios Kyrtzidis }
657fa0734ecSArgyrios Kyrtzidis case Stmt::CompoundStmtClass:
658fa0734ecSArgyrios Kyrtzidis case Stmt::StmtExprClass:
6593a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
660fa0734ecSArgyrios Kyrtzidis case Stmt::ChooseExprClass:
661fa0734ecSArgyrios Kyrtzidis // Similar to '?' if we are referring to condition, just have the edge
662fa0734ecSArgyrios Kyrtzidis // point to the entire choose expression.
66306e80072SJordan Rose if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
6643a769bd9SAnna Zaks return PathDiagnosticLocation(Parent, SMgr, LC);
665fa0734ecSArgyrios Kyrtzidis else
6663a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
667c07a0c7eSJohn McCall case Stmt::BinaryConditionalOperatorClass:
668fa0734ecSArgyrios Kyrtzidis case Stmt::ConditionalOperatorClass:
669fa0734ecSArgyrios Kyrtzidis // For '?', if we are referring to condition, just have the edge point
670fa0734ecSArgyrios Kyrtzidis // to the entire '?' expression.
67106e80072SJordan Rose if (allowNestedContexts ||
67206e80072SJordan Rose cast<AbstractConditionalOperator>(Parent)->getCond() == S)
6733a769bd9SAnna Zaks return PathDiagnosticLocation(Parent, SMgr, LC);
674fa0734ecSArgyrios Kyrtzidis else
6753a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
676cf10ea8cSJordan Rose case Stmt::CXXForRangeStmtClass:
677cf10ea8cSJordan Rose if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
678cf10ea8cSJordan Rose return PathDiagnosticLocation(S, SMgr, LC);
679cf10ea8cSJordan Rose break;
680fa0734ecSArgyrios Kyrtzidis case Stmt::DoStmtClass:
6813a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
682fa0734ecSArgyrios Kyrtzidis case Stmt::ForStmtClass:
683fa0734ecSArgyrios Kyrtzidis if (cast<ForStmt>(Parent)->getBody() == S)
6843a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
685fa0734ecSArgyrios Kyrtzidis break;
686fa0734ecSArgyrios Kyrtzidis case Stmt::IfStmtClass:
687fa0734ecSArgyrios Kyrtzidis if (cast<IfStmt>(Parent)->getCond() != S)
6883a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
689fa0734ecSArgyrios Kyrtzidis break;
690fa0734ecSArgyrios Kyrtzidis case Stmt::ObjCForCollectionStmtClass:
691fa0734ecSArgyrios Kyrtzidis if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
6923a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
693fa0734ecSArgyrios Kyrtzidis break;
694fa0734ecSArgyrios Kyrtzidis case Stmt::WhileStmtClass:
695fa0734ecSArgyrios Kyrtzidis if (cast<WhileStmt>(Parent)->getCond() != S)
6963a769bd9SAnna Zaks return PathDiagnosticLocation(S, SMgr, LC);
697fa0734ecSArgyrios Kyrtzidis break;
698fa0734ecSArgyrios Kyrtzidis default:
699fa0734ecSArgyrios Kyrtzidis break;
700fa0734ecSArgyrios Kyrtzidis }
701fa0734ecSArgyrios Kyrtzidis
702fa0734ecSArgyrios Kyrtzidis S = Parent;
703fa0734ecSArgyrios Kyrtzidis }
704fa0734ecSArgyrios Kyrtzidis
705fa0734ecSArgyrios Kyrtzidis assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
706fa0734ecSArgyrios Kyrtzidis
707b1db073dSJordan Rose return PathDiagnosticLocation(S, SMgr, LC);
708fa0734ecSArgyrios Kyrtzidis }
709fa0734ecSArgyrios Kyrtzidis
710fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
711fa0734ecSArgyrios Kyrtzidis // "Minimal" path diagnostic generation algorithm.
712fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
713cba4f298SAnna Zaks
714f9d75bedSKristof Umann /// If the piece contains a special message, add it to all the call pieces on
7158535b8ecSArtem Dergachev /// the active stack. For example, my_malloc allocated memory, so MallocChecker
716f9d75bedSKristof Umann /// will construct an event at the call to malloc(), and add a stack hint that
717f9d75bedSKristof Umann /// an allocated memory was returned. We'll use this hint to construct a message
718f9d75bedSKristof Umann /// when returning from the call to my_malloc
719f9d75bedSKristof Umann ///
720f9d75bedSKristof Umann /// void *my_malloc() { return malloc(sizeof(int)); }
721f9d75bedSKristof Umann /// void fishy() {
722f9d75bedSKristof Umann /// void *ptr = my_malloc(); // returned allocated memory
723f9d75bedSKristof Umann /// } // leak
updateStackPiecesWithMessage(PathDiagnosticPieceRef P,const CallWithEntryStack & CallStack) const7248535b8ecSArtem Dergachev void PathDiagnosticBuilder::updateStackPiecesWithMessage(
7258535b8ecSArtem Dergachev PathDiagnosticPieceRef P, const CallWithEntryStack &CallStack) const {
7268535b8ecSArtem Dergachev if (R->hasCallStackHint(P))
7276a58efdfSEugene Zelenko for (const auto &I : CallStack) {
7286a58efdfSEugene Zelenko PathDiagnosticCallPiece *CP = I.first;
7296a58efdfSEugene Zelenko const ExplodedNode *N = I.second;
7308535b8ecSArtem Dergachev std::string stackMsg = R->getCallStackMessage(P, N);
731cba4f298SAnna Zaks
7321ff57d57SAnna Zaks // The last message on the path to final bug is the most important
7331ff57d57SAnna Zaks // one. Since we traverse the path backwards, do not add the message
7341ff57d57SAnna Zaks // if one has been previously added.
735cba4f298SAnna Zaks if (!CP->hasCallStackMessage())
736cba4f298SAnna Zaks CP->setCallStackMessage(stackMsg);
737cba4f298SAnna Zaks }
7381ff57d57SAnna Zaks }
739fa0734ecSArgyrios Kyrtzidis
7407d6d9eb6SKristof Umann static void CompactMacroExpandedPieces(PathPieces &path,
7417d6d9eb6SKristof Umann const SourceManager& SM);
742fa0734ecSArgyrios Kyrtzidis
generateDiagForSwitchOP(const PathDiagnosticConstruct & C,const CFGBlock * Dst,PathDiagnosticLocation & Start) const743f9d75bedSKristof Umann PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForSwitchOP(
744edb78859SKristof Umann const PathDiagnosticConstruct &C, const CFGBlock *Dst,
745f9d75bedSKristof Umann PathDiagnosticLocation &Start) const {
7468ade5638SGeorge Karpenkov
747f9d75bedSKristof Umann const SourceManager &SM = getSourceManager();
748fa0734ecSArgyrios Kyrtzidis // Figure out what case arm we took.
749fa0734ecSArgyrios Kyrtzidis std::string sbuf;
750fa0734ecSArgyrios Kyrtzidis llvm::raw_string_ostream os(sbuf);
7518ade5638SGeorge Karpenkov PathDiagnosticLocation End;
752fa0734ecSArgyrios Kyrtzidis
753fa0734ecSArgyrios Kyrtzidis if (const Stmt *S = Dst->getLabel()) {
754f9d75bedSKristof Umann End = PathDiagnosticLocation(S, SM, C.getCurrLocationContext());
755fa0734ecSArgyrios Kyrtzidis
756fa0734ecSArgyrios Kyrtzidis switch (S->getStmtClass()) {
757fa0734ecSArgyrios Kyrtzidis default:
758fa0734ecSArgyrios Kyrtzidis os << "No cases match in the switch statement. "
759fa0734ecSArgyrios Kyrtzidis "Control jumps to line "
760d48db211SChandler Carruth << End.asLocation().getExpansionLineNumber();
761fa0734ecSArgyrios Kyrtzidis break;
762fa0734ecSArgyrios Kyrtzidis case Stmt::DefaultStmtClass:
763fa0734ecSArgyrios Kyrtzidis os << "Control jumps to the 'default' case at line "
764d48db211SChandler Carruth << End.asLocation().getExpansionLineNumber();
765fa0734ecSArgyrios Kyrtzidis break;
766fa0734ecSArgyrios Kyrtzidis
767fa0734ecSArgyrios Kyrtzidis case Stmt::CaseStmtClass: {
768fa0734ecSArgyrios Kyrtzidis os << "Control jumps to 'case ";
7696a58efdfSEugene Zelenko const auto *Case = cast<CaseStmt>(S);
770fa0734ecSArgyrios Kyrtzidis const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
771fa0734ecSArgyrios Kyrtzidis
772fa0734ecSArgyrios Kyrtzidis // Determine if it is an enum.
773fa0734ecSArgyrios Kyrtzidis bool GetRawInt = true;
774fa0734ecSArgyrios Kyrtzidis
7756a58efdfSEugene Zelenko if (const auto *DR = dyn_cast<DeclRefExpr>(LHS)) {
776fa0734ecSArgyrios Kyrtzidis // FIXME: Maybe this should be an assertion. Are there cases
777fa0734ecSArgyrios Kyrtzidis // were it is not an EnumConstantDecl?
7786a58efdfSEugene Zelenko const auto *D = dyn_cast<EnumConstantDecl>(DR->getDecl());
779fa0734ecSArgyrios Kyrtzidis
780fa0734ecSArgyrios Kyrtzidis if (D) {
781fa0734ecSArgyrios Kyrtzidis GetRawInt = false;
782b89514a9SBenjamin Kramer os << *D;
783fa0734ecSArgyrios Kyrtzidis }
784fa0734ecSArgyrios Kyrtzidis }
785fa0734ecSArgyrios Kyrtzidis
786fa0734ecSArgyrios Kyrtzidis if (GetRawInt)
787f9d75bedSKristof Umann os << LHS->EvaluateKnownConstInt(getASTContext());
788fa0734ecSArgyrios Kyrtzidis
78946163786SGeorge Karpenkov os << ":' at line " << End.asLocation().getExpansionLineNumber();
790fa0734ecSArgyrios Kyrtzidis break;
791fa0734ecSArgyrios Kyrtzidis }
792fa0734ecSArgyrios Kyrtzidis }
79346163786SGeorge Karpenkov } else {
794fa0734ecSArgyrios Kyrtzidis os << "'Default' branch taken. ";
795f9d75bedSKristof Umann End = ExecutionContinues(os, C);
7968ade5638SGeorge Karpenkov }
7978ade5638SGeorge Karpenkov return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
7988ade5638SGeorge Karpenkov os.str());
799fa0734ecSArgyrios Kyrtzidis }
800fa0734ecSArgyrios Kyrtzidis
generateDiagForGotoOP(const PathDiagnosticConstruct & C,const Stmt * S,PathDiagnosticLocation & Start) const801f9d75bedSKristof Umann PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForGotoOP(
802edb78859SKristof Umann const PathDiagnosticConstruct &C, const Stmt *S,
803f9d75bedSKristof Umann PathDiagnosticLocation &Start) const {
8048ade5638SGeorge Karpenkov std::string sbuf;
8058ade5638SGeorge Karpenkov llvm::raw_string_ostream os(sbuf);
806f9d75bedSKristof Umann const PathDiagnosticLocation &End =
807f9d75bedSKristof Umann getEnclosingStmtLocation(S, C.getCurrLocationContext());
8088ade5638SGeorge Karpenkov os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
8098ade5638SGeorge Karpenkov return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str());
8108ade5638SGeorge Karpenkov }
8118ade5638SGeorge Karpenkov
generateDiagForBinaryOP(const PathDiagnosticConstruct & C,const Stmt * T,const CFGBlock * Src,const CFGBlock * Dst) const812f9d75bedSKristof Umann PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForBinaryOP(
813edb78859SKristof Umann const PathDiagnosticConstruct &C, const Stmt *T, const CFGBlock *Src,
814f9d75bedSKristof Umann const CFGBlock *Dst) const {
815f9d75bedSKristof Umann
816f9d75bedSKristof Umann const SourceManager &SM = getSourceManager();
817fc76d855SKristof Umann
8188ade5638SGeorge Karpenkov const auto *B = cast<BinaryOperator>(T);
8198ade5638SGeorge Karpenkov std::string sbuf;
8208ade5638SGeorge Karpenkov llvm::raw_string_ostream os(sbuf);
8218ade5638SGeorge Karpenkov os << "Left side of '";
8228ade5638SGeorge Karpenkov PathDiagnosticLocation Start, End;
8238ade5638SGeorge Karpenkov
8248ade5638SGeorge Karpenkov if (B->getOpcode() == BO_LAnd) {
8258ade5638SGeorge Karpenkov os << "&&"
8268ade5638SGeorge Karpenkov << "' is ";
8278ade5638SGeorge Karpenkov
8288ade5638SGeorge Karpenkov if (*(Src->succ_begin() + 1) == Dst) {
8298ade5638SGeorge Karpenkov os << "false";
830f9d75bedSKristof Umann End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
8318ade5638SGeorge Karpenkov Start =
8328ade5638SGeorge Karpenkov PathDiagnosticLocation::createOperatorLoc(B, SM);
8338ade5638SGeorge Karpenkov } else {
8348ade5638SGeorge Karpenkov os << "true";
835f9d75bedSKristof Umann Start =
836f9d75bedSKristof Umann PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
837f9d75bedSKristof Umann End = ExecutionContinues(C);
8388ade5638SGeorge Karpenkov }
8398ade5638SGeorge Karpenkov } else {
8408ade5638SGeorge Karpenkov assert(B->getOpcode() == BO_LOr);
8418ade5638SGeorge Karpenkov os << "||"
8428ade5638SGeorge Karpenkov << "' is ";
8438ade5638SGeorge Karpenkov
8448ade5638SGeorge Karpenkov if (*(Src->succ_begin() + 1) == Dst) {
8458ade5638SGeorge Karpenkov os << "false";
846f9d75bedSKristof Umann Start =
847f9d75bedSKristof Umann PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
848f9d75bedSKristof Umann End = ExecutionContinues(C);
8498ade5638SGeorge Karpenkov } else {
8508ade5638SGeorge Karpenkov os << "true";
851f9d75bedSKristof Umann End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
8528ade5638SGeorge Karpenkov Start =
8538ade5638SGeorge Karpenkov PathDiagnosticLocation::createOperatorLoc(B, SM);
8548ade5638SGeorge Karpenkov }
8558ade5638SGeorge Karpenkov }
8568ade5638SGeorge Karpenkov return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
8578ade5638SGeorge Karpenkov os.str());
8588ade5638SGeorge Karpenkov }
8598ade5638SGeorge Karpenkov
generateMinimalDiagForBlockEdge(PathDiagnosticConstruct & C,BlockEdge BE) const860f9d75bedSKristof Umann void PathDiagnosticBuilder::generateMinimalDiagForBlockEdge(
861edb78859SKristof Umann PathDiagnosticConstruct &C, BlockEdge BE) const {
862f9d75bedSKristof Umann const SourceManager &SM = getSourceManager();
863f9d75bedSKristof Umann const LocationContext *LC = C.getCurrLocationContext();
8648ade5638SGeorge Karpenkov const CFGBlock *Src = BE.getSrc();
8658ade5638SGeorge Karpenkov const CFGBlock *Dst = BE.getDst();
8664e53032dSArtem Dergachev const Stmt *T = Src->getTerminatorStmt();
8678ade5638SGeorge Karpenkov if (!T)
8688ade5638SGeorge Karpenkov return;
8698ade5638SGeorge Karpenkov
8708ade5638SGeorge Karpenkov auto Start = PathDiagnosticLocation::createBegin(T, SM, LC);
8718ade5638SGeorge Karpenkov switch (T->getStmtClass()) {
8728ade5638SGeorge Karpenkov default:
8738ade5638SGeorge Karpenkov break;
8748ade5638SGeorge Karpenkov
8758ade5638SGeorge Karpenkov case Stmt::GotoStmtClass:
8768ade5638SGeorge Karpenkov case Stmt::IndirectGotoStmtClass: {
8776b85f8e9SArtem Dergachev if (const Stmt *S = C.getCurrentNode()->getNextStmtForDiagnostics())
878f9d75bedSKristof Umann C.getActivePath().push_front(generateDiagForGotoOP(C, S, Start));
8798ade5638SGeorge Karpenkov break;
8808ade5638SGeorge Karpenkov }
8818ade5638SGeorge Karpenkov
8828ade5638SGeorge Karpenkov case Stmt::SwitchStmtClass: {
883f9d75bedSKristof Umann C.getActivePath().push_front(generateDiagForSwitchOP(C, Dst, Start));
884fa0734ecSArgyrios Kyrtzidis break;
885fa0734ecSArgyrios Kyrtzidis }
886fa0734ecSArgyrios Kyrtzidis
887fa0734ecSArgyrios Kyrtzidis case Stmt::BreakStmtClass:
888fa0734ecSArgyrios Kyrtzidis case Stmt::ContinueStmtClass: {
889fa0734ecSArgyrios Kyrtzidis std::string sbuf;
890fa0734ecSArgyrios Kyrtzidis llvm::raw_string_ostream os(sbuf);
891f9d75bedSKristof Umann PathDiagnosticLocation End = ExecutionContinues(os, C);
892f9d75bedSKristof Umann C.getActivePath().push_front(
89346163786SGeorge Karpenkov std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
894fa0734ecSArgyrios Kyrtzidis break;
895fa0734ecSArgyrios Kyrtzidis }
896fa0734ecSArgyrios Kyrtzidis
897fa0734ecSArgyrios Kyrtzidis // Determine control-flow for ternary '?'.
898c07a0c7eSJohn McCall case Stmt::BinaryConditionalOperatorClass:
899fa0734ecSArgyrios Kyrtzidis case Stmt::ConditionalOperatorClass: {
900fa0734ecSArgyrios Kyrtzidis std::string sbuf;
901fa0734ecSArgyrios Kyrtzidis llvm::raw_string_ostream os(sbuf);
902fa0734ecSArgyrios Kyrtzidis os << "'?' condition is ";
903fa0734ecSArgyrios Kyrtzidis
904fa0734ecSArgyrios Kyrtzidis if (*(Src->succ_begin() + 1) == Dst)
905fa0734ecSArgyrios Kyrtzidis os << "false";
906fa0734ecSArgyrios Kyrtzidis else
907fa0734ecSArgyrios Kyrtzidis os << "true";
908fa0734ecSArgyrios Kyrtzidis
909f9d75bedSKristof Umann PathDiagnosticLocation End = ExecutionContinues(C);
910fa0734ecSArgyrios Kyrtzidis
911fa0734ecSArgyrios Kyrtzidis if (const Stmt *S = End.asStmt())
912f9d75bedSKristof Umann End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
913fa0734ecSArgyrios Kyrtzidis
914f9d75bedSKristof Umann C.getActivePath().push_front(
91546163786SGeorge Karpenkov std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
916fa0734ecSArgyrios Kyrtzidis break;
917fa0734ecSArgyrios Kyrtzidis }
918fa0734ecSArgyrios Kyrtzidis
919fa0734ecSArgyrios Kyrtzidis // Determine control-flow for short-circuited '&&' and '||'.
920fa0734ecSArgyrios Kyrtzidis case Stmt::BinaryOperatorClass: {
921f9d75bedSKristof Umann if (!C.supportsLogicalOpControlFlow())
922fa0734ecSArgyrios Kyrtzidis break;
923fa0734ecSArgyrios Kyrtzidis
924f9d75bedSKristof Umann C.getActivePath().push_front(generateDiagForBinaryOP(C, T, Src, Dst));
925fa0734ecSArgyrios Kyrtzidis break;
926fa0734ecSArgyrios Kyrtzidis }
927fa0734ecSArgyrios Kyrtzidis
9286a58efdfSEugene Zelenko case Stmt::DoStmtClass:
929fa0734ecSArgyrios Kyrtzidis if (*(Src->succ_begin()) == Dst) {
930fa0734ecSArgyrios Kyrtzidis std::string sbuf;
931fa0734ecSArgyrios Kyrtzidis llvm::raw_string_ostream os(sbuf);
932fa0734ecSArgyrios Kyrtzidis
933fa0734ecSArgyrios Kyrtzidis os << "Loop condition is true. ";
934f9d75bedSKristof Umann PathDiagnosticLocation End = ExecutionContinues(os, C);
935fa0734ecSArgyrios Kyrtzidis
936fa0734ecSArgyrios Kyrtzidis if (const Stmt *S = End.asStmt())
937f9d75bedSKristof Umann End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
938fa0734ecSArgyrios Kyrtzidis
939f9d75bedSKristof Umann C.getActivePath().push_front(
9400a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
9410a0c275fSDavid Blaikie os.str()));
94246163786SGeorge Karpenkov } else {
943f9d75bedSKristof Umann PathDiagnosticLocation End = ExecutionContinues(C);
944fa0734ecSArgyrios Kyrtzidis
945fa0734ecSArgyrios Kyrtzidis if (const Stmt *S = End.asStmt())
946f9d75bedSKristof Umann End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
947fa0734ecSArgyrios Kyrtzidis
948f9d75bedSKristof Umann C.getActivePath().push_front(
9490a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(
9505d4ec363SAnna Zaks Start, End, "Loop condition is false. Exiting loop"));
951fa0734ecSArgyrios Kyrtzidis }
952fa0734ecSArgyrios Kyrtzidis break;
953fa0734ecSArgyrios Kyrtzidis
954fa0734ecSArgyrios Kyrtzidis case Stmt::WhileStmtClass:
9556a58efdfSEugene Zelenko case Stmt::ForStmtClass:
956fa0734ecSArgyrios Kyrtzidis if (*(Src->succ_begin() + 1) == Dst) {
957fa0734ecSArgyrios Kyrtzidis std::string sbuf;
958fa0734ecSArgyrios Kyrtzidis llvm::raw_string_ostream os(sbuf);
959fa0734ecSArgyrios Kyrtzidis
960fa0734ecSArgyrios Kyrtzidis os << "Loop condition is false. ";
961f9d75bedSKristof Umann PathDiagnosticLocation End = ExecutionContinues(os, C);
962fa0734ecSArgyrios Kyrtzidis if (const Stmt *S = End.asStmt())
963f9d75bedSKristof Umann End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
964fa0734ecSArgyrios Kyrtzidis
965f9d75bedSKristof Umann C.getActivePath().push_front(
9660a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
9670a0c275fSDavid Blaikie os.str()));
96846163786SGeorge Karpenkov } else {
969f9d75bedSKristof Umann PathDiagnosticLocation End = ExecutionContinues(C);
970fa0734ecSArgyrios Kyrtzidis if (const Stmt *S = End.asStmt())
971f9d75bedSKristof Umann End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
972fa0734ecSArgyrios Kyrtzidis
973f9d75bedSKristof Umann C.getActivePath().push_front(
9740a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(
9755d4ec363SAnna Zaks Start, End, "Loop condition is true. Entering loop body"));
976fa0734ecSArgyrios Kyrtzidis }
977fa0734ecSArgyrios Kyrtzidis
978fa0734ecSArgyrios Kyrtzidis break;
979fa0734ecSArgyrios Kyrtzidis
980fa0734ecSArgyrios Kyrtzidis case Stmt::IfStmtClass: {
981f9d75bedSKristof Umann PathDiagnosticLocation End = ExecutionContinues(C);
982fa0734ecSArgyrios Kyrtzidis
983fa0734ecSArgyrios Kyrtzidis if (const Stmt *S = End.asStmt())
984f9d75bedSKristof Umann End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
985fa0734ecSArgyrios Kyrtzidis
986fa0734ecSArgyrios Kyrtzidis if (*(Src->succ_begin() + 1) == Dst)
987f9d75bedSKristof Umann C.getActivePath().push_front(
9880a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(
9895d4ec363SAnna Zaks Start, End, "Taking false branch"));
990fa0734ecSArgyrios Kyrtzidis else
991f9d75bedSKristof Umann C.getActivePath().push_front(
9920a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(
9935d4ec363SAnna Zaks Start, End, "Taking true branch"));
994fa0734ecSArgyrios Kyrtzidis
995fa0734ecSArgyrios Kyrtzidis break;
996fa0734ecSArgyrios Kyrtzidis }
997fa0734ecSArgyrios Kyrtzidis }
998fa0734ecSArgyrios Kyrtzidis }
99946163786SGeorge Karpenkov
1000efb41d23STed Kremenek //===----------------------------------------------------------------------===//
1001efb41d23STed Kremenek // Functions for determining if a loop was executed 0 times.
1002efb41d23STed Kremenek //===----------------------------------------------------------------------===//
1003efb41d23STed Kremenek
isLoop(const Stmt * Term)1004fe516f89STed Kremenek static bool isLoop(const Stmt *Term) {
1005ca3ed723STed Kremenek switch (Term->getStmtClass()) {
1006ca3ed723STed Kremenek case Stmt::ForStmtClass:
1007ca3ed723STed Kremenek case Stmt::WhileStmtClass:
10082fb5f09eSTed Kremenek case Stmt::ObjCForCollectionStmtClass:
1009cf10ea8cSJordan Rose case Stmt::CXXForRangeStmtClass:
1010fe516f89STed Kremenek return true;
1011ca3ed723STed Kremenek default:
1012ca3ed723STed Kremenek // Note that we intentionally do not include do..while here.
1013ca3ed723STed Kremenek return false;
1014ca3ed723STed Kremenek }
1015fe516f89STed Kremenek }
1016ca3ed723STed Kremenek
isJumpToFalseBranch(const BlockEdge * BE)1017fe516f89STed Kremenek static bool isJumpToFalseBranch(const BlockEdge *BE) {
1018ca3ed723STed Kremenek const CFGBlock *Src = BE->getSrc();
1019ca3ed723STed Kremenek assert(Src->succ_size() == 2);
1020ca3ed723STed Kremenek return (*(Src->succ_begin()+1) == BE->getDst());
1021ca3ed723STed Kremenek }
1022ca3ed723STed Kremenek
isContainedByStmt(const ParentMap & PM,const Stmt * S,const Stmt * SubS)1023fc76d855SKristof Umann static bool isContainedByStmt(const ParentMap &PM, const Stmt *S,
1024fc76d855SKristof Umann const Stmt *SubS) {
1025efb41d23STed Kremenek while (SubS) {
1026efb41d23STed Kremenek if (SubS == S)
1027efb41d23STed Kremenek return true;
1028efb41d23STed Kremenek SubS = PM.getParent(SubS);
1029efb41d23STed Kremenek }
1030efb41d23STed Kremenek return false;
1031efb41d23STed Kremenek }
1032efb41d23STed Kremenek
getStmtBeforeCond(const ParentMap & PM,const Stmt * Term,const ExplodedNode * N)1033fc76d855SKristof Umann static const Stmt *getStmtBeforeCond(const ParentMap &PM, const Stmt *Term,
1034efb41d23STed Kremenek const ExplodedNode *N) {
1035efb41d23STed Kremenek while (N) {
1036efb41d23STed Kremenek Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1037efb41d23STed Kremenek if (SP) {
1038efb41d23STed Kremenek const Stmt *S = SP->getStmt();
1039efb41d23STed Kremenek if (!isContainedByStmt(PM, Term, S))
1040efb41d23STed Kremenek return S;
1041efb41d23STed Kremenek }
10424e16b29cSAnna Zaks N = N->getFirstPred();
1043efb41d23STed Kremenek }
10440dbb783cSCraig Topper return nullptr;
1045efb41d23STed Kremenek }
1046efb41d23STed Kremenek
isInLoopBody(const ParentMap & PM,const Stmt * S,const Stmt * Term)1047fc76d855SKristof Umann static bool isInLoopBody(const ParentMap &PM, const Stmt *S, const Stmt *Term) {
10480dbb783cSCraig Topper const Stmt *LoopBody = nullptr;
1049efb41d23STed Kremenek switch (Term->getStmtClass()) {
1050cf10ea8cSJordan Rose case Stmt::CXXForRangeStmtClass: {
10516a58efdfSEugene Zelenko const auto *FR = cast<CXXForRangeStmt>(Term);
1052cf10ea8cSJordan Rose if (isContainedByStmt(PM, FR->getInc(), S))
1053cf10ea8cSJordan Rose return true;
1054cf10ea8cSJordan Rose if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
1055cf10ea8cSJordan Rose return true;
1056cf10ea8cSJordan Rose LoopBody = FR->getBody();
1057cf10ea8cSJordan Rose break;
1058cf10ea8cSJordan Rose }
1059efb41d23STed Kremenek case Stmt::ForStmtClass: {
10606a58efdfSEugene Zelenko const auto *FS = cast<ForStmt>(Term);
1061efb41d23STed Kremenek if (isContainedByStmt(PM, FS->getInc(), S))
1062efb41d23STed Kremenek return true;
1063efb41d23STed Kremenek LoopBody = FS->getBody();
1064efb41d23STed Kremenek break;
1065efb41d23STed Kremenek }
10662fb5f09eSTed Kremenek case Stmt::ObjCForCollectionStmtClass: {
10676a58efdfSEugene Zelenko const auto *FC = cast<ObjCForCollectionStmt>(Term);
10682fb5f09eSTed Kremenek LoopBody = FC->getBody();
10692fb5f09eSTed Kremenek break;
10702fb5f09eSTed Kremenek }
1071efb41d23STed Kremenek case Stmt::WhileStmtClass:
1072efb41d23STed Kremenek LoopBody = cast<WhileStmt>(Term)->getBody();
1073efb41d23STed Kremenek break;
1074efb41d23STed Kremenek default:
1075efb41d23STed Kremenek return false;
1076efb41d23STed Kremenek }
1077efb41d23STed Kremenek return isContainedByStmt(PM, LoopBody, S);
1078efb41d23STed Kremenek }
1079efb41d23STed Kremenek
10809fc8faf9SAdrian Prantl /// Adds a sanitized control-flow diagnostic edge to a path.
addEdgeToPath(PathPieces & path,PathDiagnosticLocation & PrevLoc,PathDiagnosticLocation NewLoc)1081acf99a1aSTed Kremenek static void addEdgeToPath(PathPieces &path,
1082acf99a1aSTed Kremenek PathDiagnosticLocation &PrevLoc,
1083c82d457dSGeorge Karpenkov PathDiagnosticLocation NewLoc) {
10846cf3c97cSTed Kremenek if (!NewLoc.isValid())
10856cf3c97cSTed Kremenek return;
10866cf3c97cSTed Kremenek
10876cf3c97cSTed Kremenek SourceLocation NewLocL = NewLoc.asLocation();
108822895473SAnna Zaks if (NewLocL.isInvalid())
1089acf99a1aSTed Kremenek return;
1090acf99a1aSTed Kremenek
1091ca0ecb61SJordan Rose if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
1092acf99a1aSTed Kremenek PrevLoc = NewLoc;
1093acf99a1aSTed Kremenek return;
1094acf99a1aSTed Kremenek }
1095acf99a1aSTed Kremenek
1096b67b7b20SJordan Rose // Ignore self-edges, which occur when there are multiple nodes at the same
1097b67b7b20SJordan Rose // statement.
1098b67b7b20SJordan Rose if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
1099acf99a1aSTed Kremenek return;
1100acf99a1aSTed Kremenek
11010a0c275fSDavid Blaikie path.push_front(
11020a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(NewLoc, PrevLoc));
1103acf99a1aSTed Kremenek PrevLoc = NewLoc;
1104acf99a1aSTed Kremenek }
1105acf99a1aSTed Kremenek
1106d4167a66STed Kremenek /// A customized wrapper for CFGBlock::getTerminatorCondition()
1107d4167a66STed Kremenek /// which returns the element for ObjCForCollectionStmts.
getTerminatorCondition(const CFGBlock * B)1108d4167a66STed Kremenek static const Stmt *getTerminatorCondition(const CFGBlock *B) {
1109d4167a66STed Kremenek const Stmt *S = B->getTerminatorCondition();
11106a58efdfSEugene Zelenko if (const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(S))
1111d4167a66STed Kremenek return FS->getElement();
1112d4167a66STed Kremenek return S;
1113d4167a66STed Kremenek }
1114d4167a66STed Kremenek
1115dc5f805dSBenjamin Kramer constexpr llvm::StringLiteral StrEnteringLoop = "Entering loop body";
1116dc5f805dSBenjamin Kramer constexpr llvm::StringLiteral StrLoopBodyZero = "Loop body executed 0 times";
1117dc5f805dSBenjamin Kramer constexpr llvm::StringLiteral StrLoopRangeEmpty =
1118dc5f805dSBenjamin Kramer "Loop body skipped when range is empty";
1119dc5f805dSBenjamin Kramer constexpr llvm::StringLiteral StrLoopCollectionEmpty =
1120236dbd25SJordan Rose "Loop body skipped when collection is empty";
11217c6b4084STed Kremenek
112270ec1dd1SGeorge Karpenkov static std::unique_ptr<FilesToLineNumsMap>
1123fc76d855SKristof Umann findExecutedLines(const SourceManager &SM, const ExplodedNode *N);
112470ec1dd1SGeorge Karpenkov
generatePathDiagnosticsForNode(PathDiagnosticConstruct & C,PathDiagnosticLocation & PrevLoc) const1125f9d75bedSKristof Umann void PathDiagnosticBuilder::generatePathDiagnosticsForNode(
1126edb78859SKristof Umann PathDiagnosticConstruct &C, PathDiagnosticLocation &PrevLoc) const {
1127f9d75bedSKristof Umann ProgramPoint P = C.getCurrentNode()->getLocation();
1128f9d75bedSKristof Umann const SourceManager &SM = getSourceManager();
1129acf99a1aSTed Kremenek
113068a60451STed Kremenek // Have we encountered an entrance to a call? It may be
113168a60451STed Kremenek // the case that we have not encountered a matching
113268a60451STed Kremenek // call exit before this point. This means that the path
113368a60451STed Kremenek // terminated within the call itself.
11348ade5638SGeorge Karpenkov if (auto CE = P.getAs<CallEnter>()) {
11358ade5638SGeorge Karpenkov
1136f9d75bedSKristof Umann if (C.shouldAddPathEdges()) {
1137ca0ecb61SJordan Rose // Add an edge to the start of the function.
1138ca0ecb61SJordan Rose const StackFrameContext *CalleeLC = CE->getCalleeContext();
1139ca0ecb61SJordan Rose const Decl *D = CalleeLC->getDecl();
11407c0ab869SArtem Dergachev // Add the edge only when the callee has body. We jump to the beginning
11417c0ab869SArtem Dergachev // of the *declaration*, however we expect it to be followed by the
11427c0ab869SArtem Dergachev // body. This isn't the case for autosynthesized property accessors in
11437c0ab869SArtem Dergachev // Objective-C. No need for a similar extra check for CallExit points
11447c0ab869SArtem Dergachev // because the exit edge comes from a statement (i.e. return),
11457c0ab869SArtem Dergachev // not from declaration.
11467c0ab869SArtem Dergachev if (D->hasBody())
1147f9d75bedSKristof Umann addEdgeToPath(C.getActivePath(), PrevLoc,
1148c82d457dSGeorge Karpenkov PathDiagnosticLocation::createBegin(D, SM));
11498ade5638SGeorge Karpenkov }
1150ca0ecb61SJordan Rose
115168a60451STed Kremenek // Did we visit an entire call?
1152f9d75bedSKristof Umann bool VisitedEntireCall = C.PD->isWithinCall();
1153f9d75bedSKristof Umann C.PD->popActivePath();
115468a60451STed Kremenek
1155f9d75bedSKristof Umann PathDiagnosticCallPiece *Call;
115668a60451STed Kremenek if (VisitedEntireCall) {
1157f9d75bedSKristof Umann Call = cast<PathDiagnosticCallPiece>(C.getActivePath().front().get());
115868a60451STed Kremenek } else {
1159f9d75bedSKristof Umann // The path terminated within a nested location context, create a new
1160f9d75bedSKristof Umann // call piece to encapsulate the rest of the path pieces.
116168a60451STed Kremenek const Decl *Caller = CE->getLocationContext()->getDecl();
1162f9d75bedSKristof Umann Call = PathDiagnosticCallPiece::construct(C.getActivePath(), Caller);
1163f9d75bedSKristof Umann assert(C.getActivePath().size() == 1 &&
1164f9d75bedSKristof Umann C.getActivePath().front().get() == Call);
116568a60451STed Kremenek
1166f9d75bedSKristof Umann // Since we just transferred the path over to the call piece, reset the
1167f9d75bedSKristof Umann // mapping of the active path to the current location context.
1168f9d75bedSKristof Umann assert(C.isInLocCtxMap(&C.getActivePath()) &&
1169f9d75bedSKristof Umann "When we ascend to a previously unvisited call, the active path's "
1170f9d75bedSKristof Umann "address shouldn't change, but rather should be compacted into "
1171f9d75bedSKristof Umann "a single CallEvent!");
1172f9d75bedSKristof Umann C.updateLocCtxMap(&C.getActivePath(), C.getCurrLocationContext());
1173f9d75bedSKristof Umann
1174f9d75bedSKristof Umann // Record the location context mapping for the path within the call.
1175f9d75bedSKristof Umann assert(!C.isInLocCtxMap(&Call->path) &&
1176f9d75bedSKristof Umann "When we ascend to a previously unvisited call, this must be the "
1177f9d75bedSKristof Umann "first time we encounter the caller context!");
1178f9d75bedSKristof Umann C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
11798ade5638SGeorge Karpenkov }
1180f9d75bedSKristof Umann Call->setCallee(*CE, SM);
118168a60451STed Kremenek
11827291666cSJordan Rose // Update the previous location in the active path.
1183f9d75bedSKristof Umann PrevLoc = Call->getLocation();
11847291666cSJordan Rose
1185f9d75bedSKristof Umann if (!C.CallStack.empty()) {
1186f9d75bedSKristof Umann assert(C.CallStack.back().first == Call);
1187f9d75bedSKristof Umann C.CallStack.pop_back();
118868a60451STed Kremenek }
118946163786SGeorge Karpenkov return;
1190acf99a1aSTed Kremenek }
1191acf99a1aSTed Kremenek
1192f9d75bedSKristof Umann assert(C.getCurrLocationContext() == C.getLocationContextForActivePath() &&
1193f9d75bedSKristof Umann "The current position in the bug path is out of sync with the "
1194f9d75bedSKristof Umann "location context associated with the active path!");
119568a60451STed Kremenek
1196acf99a1aSTed Kremenek // Have we encountered an exit from a function call?
1197acf99a1aSTed Kremenek if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
11988ade5638SGeorge Karpenkov
11998ade5638SGeorge Karpenkov // We are descending into a call (backwards). Construct
12008ade5638SGeorge Karpenkov // a new call piece to contain the path pieces for that call.
1201f9d75bedSKristof Umann auto Call = PathDiagnosticCallPiece::construct(*CE, SM);
12028ade5638SGeorge Karpenkov // Record the mapping from call piece to LocationContext.
1203f9d75bedSKristof Umann assert(!C.isInLocCtxMap(&Call->path) &&
1204f9d75bedSKristof Umann "We just entered a call, this must've been the first time we "
1205f9d75bedSKristof Umann "encounter its context!");
1206f9d75bedSKristof Umann C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
12078ade5638SGeorge Karpenkov
1208f9d75bedSKristof Umann if (C.shouldAddPathEdges()) {
1209acf99a1aSTed Kremenek // Add the edge to the return site.
1210f9d75bedSKristof Umann addEdgeToPath(C.getActivePath(), PrevLoc, Call->callReturn);
12118ade5638SGeorge Karpenkov PrevLoc.invalidate();
12128ade5638SGeorge Karpenkov }
12138ade5638SGeorge Karpenkov
1214f9d75bedSKristof Umann auto *P = Call.get();
1215f9d75bedSKristof Umann C.getActivePath().push_front(std::move(Call));
1216acf99a1aSTed Kremenek
1217acf99a1aSTed Kremenek // Make the contents of the call the active path for now.
1218f9d75bedSKristof Umann C.PD->pushActivePath(&P->path);
1219edb78859SKristof Umann C.CallStack.push_back(CallWithEntry(P, C.getCurrentNode()));
12208ade5638SGeorge Karpenkov return;
12218ade5638SGeorge Karpenkov }
12228ade5638SGeorge Karpenkov
12238ade5638SGeorge Karpenkov if (auto PS = P.getAs<PostStmt>()) {
1224f9d75bedSKristof Umann if (!C.shouldAddPathEdges())
12258ade5638SGeorge Karpenkov return;
12268ade5638SGeorge Karpenkov
1227d4167a66STed Kremenek // Add an edge. If this is an ObjCForCollectionStmt do
1228d4167a66STed Kremenek // not add an edge here as it appears in the CFG both
1229d4167a66STed Kremenek // as a terminator and as a terminator condition.
1230d4167a66STed Kremenek if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
123168a60451STed Kremenek PathDiagnosticLocation L =
1232f9d75bedSKristof Umann PathDiagnosticLocation(PS->getStmt(), SM, C.getCurrLocationContext());
1233f9d75bedSKristof Umann addEdgeToPath(C.getActivePath(), PrevLoc, L);
1234d4167a66STed Kremenek }
12358ade5638SGeorge Karpenkov
12368ade5638SGeorge Karpenkov } else if (auto BE = P.getAs<BlockEdge>()) {
12378ade5638SGeorge Karpenkov
123897bcafa2SValeriy Savchenko if (C.shouldAddControlNotes()) {
1239f9d75bedSKristof Umann generateMinimalDiagForBlockEdge(C, *BE);
124097bcafa2SValeriy Savchenko }
124197bcafa2SValeriy Savchenko
124297bcafa2SValeriy Savchenko if (!C.shouldAddPathEdges()) {
12438ade5638SGeorge Karpenkov return;
12448ade5638SGeorge Karpenkov }
12458ade5638SGeorge Karpenkov
1246acf99a1aSTed Kremenek // Are we jumping to the head of a loop? Add a special diagnostic.
1247acf99a1aSTed Kremenek if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1248f9d75bedSKristof Umann PathDiagnosticLocation L(Loop, SM, C.getCurrLocationContext());
12490dbb783cSCraig Topper const Stmt *Body = nullptr;
1250399980acSTed Kremenek
12516a58efdfSEugene Zelenko if (const auto *FS = dyn_cast<ForStmt>(Loop))
1252cf10ea8cSJordan Rose Body = FS->getBody();
12536a58efdfSEugene Zelenko else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
1254cf10ea8cSJordan Rose Body = WS->getBody();
12556a58efdfSEugene Zelenko else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
1256cf10ea8cSJordan Rose Body = OFS->getBody();
12576a58efdfSEugene Zelenko } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
1258cf10ea8cSJordan Rose Body = FRS->getBody();
1259d4167a66STed Kremenek }
1260cf10ea8cSJordan Rose // do-while statements are explicitly excluded here
1261acf99a1aSTed Kremenek
12620a0c275fSDavid Blaikie auto p = std::make_shared<PathDiagnosticEventPiece>(
126397bcafa2SValeriy Savchenko L, "Looping back to the head of the loop");
1264acf99a1aSTed Kremenek p->setPrunable(true);
1265acf99a1aSTed Kremenek
1266f9d75bedSKristof Umann addEdgeToPath(C.getActivePath(), PrevLoc, p->getLocation());
126797bcafa2SValeriy Savchenko // We might've added a very similar control node already
126897bcafa2SValeriy Savchenko if (!C.shouldAddControlNotes()) {
1269f9d75bedSKristof Umann C.getActivePath().push_front(std::move(p));
127097bcafa2SValeriy Savchenko }
1271399980acSTed Kremenek
12726a58efdfSEugene Zelenko if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
1273f9d75bedSKristof Umann addEdgeToPath(C.getActivePath(), PrevLoc,
1274c82d457dSGeorge Karpenkov PathDiagnosticLocation::createEndBrace(CS, SM));
1275399980acSTed Kremenek }
1276acf99a1aSTed Kremenek }
1277acf99a1aSTed Kremenek
1278acf99a1aSTed Kremenek const CFGBlock *BSrc = BE->getSrc();
1279f9d75bedSKristof Umann const ParentMap &PM = C.getParentMap();
1280acf99a1aSTed Kremenek
12814e53032dSArtem Dergachev if (const Stmt *Term = BSrc->getTerminatorStmt()) {
1282acf99a1aSTed Kremenek // Are we jumping past the loop body without ever executing the
1283acf99a1aSTed Kremenek // loop (because the condition was false)?
1284fe516f89STed Kremenek if (isLoop(Term)) {
1285d4167a66STed Kremenek const Stmt *TermCond = getTerminatorCondition(BSrc);
1286f9d75bedSKristof Umann bool IsInLoopBody = isInLoopBody(
1287f9d75bedSKristof Umann PM, getStmtBeforeCond(PM, TermCond, C.getCurrentNode()), Term);
1288fe516f89STed Kremenek
1289fc76d855SKristof Umann StringRef str;
1290fe516f89STed Kremenek
1291fe516f89STed Kremenek if (isJumpToFalseBranch(&*BE)) {
1292fe516f89STed Kremenek if (!IsInLoopBody) {
1293236dbd25SJordan Rose if (isa<ObjCForCollectionStmt>(Term)) {
1294236dbd25SJordan Rose str = StrLoopCollectionEmpty;
1295236dbd25SJordan Rose } else if (isa<CXXForRangeStmt>(Term)) {
1296236dbd25SJordan Rose str = StrLoopRangeEmpty;
1297236dbd25SJordan Rose } else {
12987c6b4084STed Kremenek str = StrLoopBodyZero;
1299fe516f89STed Kremenek }
1300236dbd25SJordan Rose }
1301f59ba9f5SCraig Topper } else {
13027c6b4084STed Kremenek str = StrEnteringLoop;
1303fe516f89STed Kremenek }
1304fe516f89STed Kremenek
1305fc76d855SKristof Umann if (!str.empty()) {
1306f9d75bedSKristof Umann PathDiagnosticLocation L(TermCond ? TermCond : Term, SM,
1307f9d75bedSKristof Umann C.getCurrLocationContext());
13080a0c275fSDavid Blaikie auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
1309acf99a1aSTed Kremenek PE->setPrunable(true);
1310f9d75bedSKristof Umann addEdgeToPath(C.getActivePath(), PrevLoc, PE->getLocation());
131197bcafa2SValeriy Savchenko
131297bcafa2SValeriy Savchenko // We might've added a very similar control node already
131397bcafa2SValeriy Savchenko if (!C.shouldAddControlNotes()) {
1314f9d75bedSKristof Umann C.getActivePath().push_front(std::move(PE));
1315acf99a1aSTed Kremenek }
131697bcafa2SValeriy Savchenko }
131716be17adSBalazs Benics } else if (isa<BreakStmt, ContinueStmt, GotoStmt>(Term)) {
1318f9d75bedSKristof Umann PathDiagnosticLocation L(Term, SM, C.getCurrLocationContext());
1319f9d75bedSKristof Umann addEdgeToPath(C.getActivePath(), PrevLoc, L);
13203a865221STed Kremenek }
1321fe516f89STed Kremenek }
1322acf99a1aSTed Kremenek }
132346163786SGeorge Karpenkov }
132446163786SGeorge Karpenkov
132570ec1dd1SGeorge Karpenkov static std::unique_ptr<PathDiagnostic>
generateDiagnosticForBasicReport(const BasicBugReport * R)13262f169e7cSArtem Dergachev generateDiagnosticForBasicReport(const BasicBugReport *R) {
13272c2d0b6eSGeorge Karpenkov const BugType &BT = R->getBugType();
13282b3d49b6SJonas Devlieghere return std::make_unique<PathDiagnostic>(
132972649423SKristof Umann BT.getCheckerName(), R->getDeclWithIssue(), BT.getDescription(),
13302f169e7cSArtem Dergachev R->getDescription(), R->getShortDescription(/*UseFallback=*/false),
13312f169e7cSArtem Dergachev BT.getCategory(), R->getUniqueingLocation(), R->getUniqueingDecl(),
13322f169e7cSArtem Dergachev std::make_unique<FilesToLineNumsMap>());
13332f169e7cSArtem Dergachev }
13342f169e7cSArtem Dergachev
13352f169e7cSArtem Dergachev static std::unique_ptr<PathDiagnostic>
generateEmptyDiagnosticForReport(const PathSensitiveBugReport * R,const SourceManager & SM)13362f169e7cSArtem Dergachev generateEmptyDiagnosticForReport(const PathSensitiveBugReport *R,
13372f169e7cSArtem Dergachev const SourceManager &SM) {
13382f169e7cSArtem Dergachev const BugType &BT = R->getBugType();
13392f169e7cSArtem Dergachev return std::make_unique<PathDiagnostic>(
134072649423SKristof Umann BT.getCheckerName(), R->getDeclWithIssue(), BT.getDescription(),
13412f169e7cSArtem Dergachev R->getDescription(), R->getShortDescription(/*UseFallback=*/false),
13422f169e7cSArtem Dergachev BT.getCategory(), R->getUniqueingLocation(), R->getUniqueingDecl(),
134370ec1dd1SGeorge Karpenkov findExecutedLines(SM, R->getErrorNode()));
1344acf99a1aSTed Kremenek }
1345acf99a1aSTed Kremenek
getStmtParent(const Stmt * S,const ParentMap & PM)1346b1db073dSJordan Rose static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
13476cf3c97cSTed Kremenek if (!S)
13480dbb783cSCraig Topper return nullptr;
1349fd8f4b01STed Kremenek
1350fd8f4b01STed Kremenek while (true) {
1351fd8f4b01STed Kremenek S = PM.getParentIgnoreParens(S);
1352fd8f4b01STed Kremenek
1353fd8f4b01STed Kremenek if (!S)
1354fd8f4b01STed Kremenek break;
1355fd8f4b01STed Kremenek
135616be17adSBalazs Benics if (isa<FullExpr, CXXBindTemporaryExpr, SubstNonTypeTemplateParmExpr>(S))
1357fd8f4b01STed Kremenek continue;
1358fd8f4b01STed Kremenek
1359fd8f4b01STed Kremenek break;
1360fd8f4b01STed Kremenek }
1361fd8f4b01STed Kremenek
1362fd8f4b01STed Kremenek return S;
13636cf3c97cSTed Kremenek }
13646cf3c97cSTed Kremenek
isConditionForTerminator(const Stmt * S,const Stmt * Cond)13657b9b5a2cSTed Kremenek static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
13667b9b5a2cSTed Kremenek switch (S->getStmtClass()) {
1367b48f5d9dSTed Kremenek case Stmt::BinaryOperatorClass: {
13686a58efdfSEugene Zelenko const auto *BO = cast<BinaryOperator>(S);
1369b48f5d9dSTed Kremenek if (!BO->isLogicalOp())
1370b48f5d9dSTed Kremenek return false;
1371b48f5d9dSTed Kremenek return BO->getLHS() == Cond || BO->getRHS() == Cond;
1372b48f5d9dSTed Kremenek }
137375b8cdeeSTed Kremenek case Stmt::IfStmtClass:
137475b8cdeeSTed Kremenek return cast<IfStmt>(S)->getCond() == Cond;
13757b9b5a2cSTed Kremenek case Stmt::ForStmtClass:
13767b9b5a2cSTed Kremenek return cast<ForStmt>(S)->getCond() == Cond;
13777b9b5a2cSTed Kremenek case Stmt::WhileStmtClass:
13787b9b5a2cSTed Kremenek return cast<WhileStmt>(S)->getCond() == Cond;
13797b9b5a2cSTed Kremenek case Stmt::DoStmtClass:
13807b9b5a2cSTed Kremenek return cast<DoStmt>(S)->getCond() == Cond;
13817b9b5a2cSTed Kremenek case Stmt::ChooseExprClass:
13827b9b5a2cSTed Kremenek return cast<ChooseExpr>(S)->getCond() == Cond;
13837b9b5a2cSTed Kremenek case Stmt::IndirectGotoStmtClass:
13847b9b5a2cSTed Kremenek return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
13857b9b5a2cSTed Kremenek case Stmt::SwitchStmtClass:
13867b9b5a2cSTed Kremenek return cast<SwitchStmt>(S)->getCond() == Cond;
13877b9b5a2cSTed Kremenek case Stmt::BinaryConditionalOperatorClass:
13887b9b5a2cSTed Kremenek return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
13890e84ac83STed Kremenek case Stmt::ConditionalOperatorClass: {
13906a58efdfSEugene Zelenko const auto *CO = cast<ConditionalOperator>(S);
13910e84ac83STed Kremenek return CO->getCond() == Cond ||
13920e84ac83STed Kremenek CO->getLHS() == Cond ||
13930e84ac83STed Kremenek CO->getRHS() == Cond;
13940e84ac83STed Kremenek }
13957b9b5a2cSTed Kremenek case Stmt::ObjCForCollectionStmtClass:
13967b9b5a2cSTed Kremenek return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
1397cf10ea8cSJordan Rose case Stmt::CXXForRangeStmtClass: {
13986a58efdfSEugene Zelenko const auto *FRS = cast<CXXForRangeStmt>(S);
1399cf10ea8cSJordan Rose return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
1400cf10ea8cSJordan Rose }
14017b9b5a2cSTed Kremenek default:
14027b9b5a2cSTed Kremenek return false;
14037b9b5a2cSTed Kremenek }
14047b9b5a2cSTed Kremenek }
14057b9b5a2cSTed Kremenek
isIncrementOrInitInForLoop(const Stmt * S,const Stmt * FL)14062f2a3042STed Kremenek static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
14076a58efdfSEugene Zelenko if (const auto *FS = dyn_cast<ForStmt>(FL))
14082f2a3042STed Kremenek return FS->getInc() == S || FS->getInit() == S;
14096a58efdfSEugene Zelenko if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
1410cf10ea8cSJordan Rose return FRS->getInc() == S || FRS->getRangeStmt() == S ||
1411cf10ea8cSJordan Rose FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
1412cf10ea8cSJordan Rose return false;
1413ae7c38ddSTed Kremenek }
1414ae7c38ddSTed Kremenek
14156a58efdfSEugene Zelenko using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
14167b9b5a2cSTed Kremenek
1417b1db073dSJordan Rose /// Adds synthetic edges from top-level statements to their subexpressions.
1418b1db073dSJordan Rose ///
1419b1db073dSJordan Rose /// This avoids a "swoosh" effect, where an edge from a top-level statement A
1420b1db073dSJordan Rose /// points to a sub-expression B.1 that's not at the start of B. In these cases,
1421b1db073dSJordan Rose /// we'd like to see an edge from A to B, then another one from B to B.1.
addContextEdges(PathPieces & pieces,const LocationContext * LC)1422f9d75bedSKristof Umann static void addContextEdges(PathPieces &pieces, const LocationContext *LC) {
1423f9d75bedSKristof Umann const ParentMap &PM = LC->getParentMap();
1424b1db073dSJordan Rose PathPieces::iterator Prev = pieces.end();
1425b1db073dSJordan Rose for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
1426b1db073dSJordan Rose Prev = I, ++I) {
14276a58efdfSEugene Zelenko auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1428b1db073dSJordan Rose
1429b1db073dSJordan Rose if (!Piece)
1430b1db073dSJordan Rose continue;
1431b1db073dSJordan Rose
1432b1db073dSJordan Rose PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
143306e80072SJordan Rose SmallVector<PathDiagnosticLocation, 4> SrcContexts;
143406e80072SJordan Rose
1435cf10ea8cSJordan Rose PathDiagnosticLocation NextSrcContext = SrcLoc;
14360dbb783cSCraig Topper const Stmt *InnerStmt = nullptr;
143706e80072SJordan Rose while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
143806e80072SJordan Rose SrcContexts.push_back(NextSrcContext);
143906e80072SJordan Rose InnerStmt = NextSrcContext.asStmt();
1440f9d75bedSKristof Umann NextSrcContext = getEnclosingStmtLocation(InnerStmt, LC,
1441cf10ea8cSJordan Rose /*allowNested=*/true);
144206e80072SJordan Rose }
1443b1db073dSJordan Rose
1444b1db073dSJordan Rose // Repeatedly split the edge as necessary.
1445b1db073dSJordan Rose // This is important for nested logical expressions (||, &&, ?:) where we
1446b1db073dSJordan Rose // want to show all the levels of context.
1447b1db073dSJordan Rose while (true) {
14481cf8cdc6SGeorge Karpenkov const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
1449b1db073dSJordan Rose
1450b1db073dSJordan Rose // We are looking at an edge. Is the destination within a larger
1451b1db073dSJordan Rose // expression?
1452b1db073dSJordan Rose PathDiagnosticLocation DstContext =
1453f9d75bedSKristof Umann getEnclosingStmtLocation(Dst, LC, /*allowNested=*/true);
1454b1db073dSJordan Rose if (!DstContext.isValid() || DstContext.asStmt() == Dst)
1455b1db073dSJordan Rose break;
1456b1db073dSJordan Rose
1457b1db073dSJordan Rose // If the source is in the same context, we're already good.
1458e567f37dSKazu Hirata if (llvm::is_contained(SrcContexts, DstContext))
1459b1db073dSJordan Rose break;
1460b1db073dSJordan Rose
1461b1db073dSJordan Rose // Update the subexpression node to point to the context edge.
1462b1db073dSJordan Rose Piece->setStartLocation(DstContext);
1463b1db073dSJordan Rose
1464b1db073dSJordan Rose // Try to extend the previous edge if it's at the same level as the source
1465b1db073dSJordan Rose // context.
1466b1db073dSJordan Rose if (Prev != E) {
14670a0c275fSDavid Blaikie auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
1468b1db073dSJordan Rose
1469b1db073dSJordan Rose if (PrevPiece) {
14701cf8cdc6SGeorge Karpenkov if (const Stmt *PrevSrc =
14711cf8cdc6SGeorge Karpenkov PrevPiece->getStartLocation().getStmtOrNull()) {
1472b1db073dSJordan Rose const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
14731cf8cdc6SGeorge Karpenkov if (PrevSrcParent ==
14741cf8cdc6SGeorge Karpenkov getStmtParent(DstContext.getStmtOrNull(), PM)) {
1475b1db073dSJordan Rose PrevPiece->setEndLocation(DstContext);
1476b1db073dSJordan Rose break;
1477b1db073dSJordan Rose }
1478b1db073dSJordan Rose }
1479b1db073dSJordan Rose }
1480b1db073dSJordan Rose }
1481b1db073dSJordan Rose
1482b1db073dSJordan Rose // Otherwise, split the current edge into a context edge and a
1483b1db073dSJordan Rose // subexpression edge. Note that the context statement may itself have
1484b1db073dSJordan Rose // context.
14850a0c275fSDavid Blaikie auto P =
14860a0c275fSDavid Blaikie std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
14870a0c275fSDavid Blaikie Piece = P.get();
14880a0c275fSDavid Blaikie I = pieces.insert(I, std::move(P));
1489b1db073dSJordan Rose }
1490b1db073dSJordan Rose }
1491b1db073dSJordan Rose }
1492b1db073dSJordan Rose
14939fc8faf9SAdrian Prantl /// Move edges from a branch condition to a branch target
1494b1db073dSJordan Rose /// when the condition is simple.
1495b1db073dSJordan Rose ///
1496b1db073dSJordan Rose /// This restructures some of the work of addContextEdges. That function
1497b1db073dSJordan Rose /// creates edges this may destroy, but they work together to create a more
1498b1db073dSJordan Rose /// aesthetically set of edges around branches. After the call to
1499b1db073dSJordan Rose /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
1500b1db073dSJordan Rose /// the branch to the branch condition, and (3) an edge from the branch
1501b1db073dSJordan Rose /// condition to the branch target. We keep (1), but may wish to remove (2)
1502b1db073dSJordan Rose /// and move the source of (3) to the branch if the branch condition is simple.
simplifySimpleBranches(PathPieces & pieces)1503b1db073dSJordan Rose static void simplifySimpleBranches(PathPieces &pieces) {
1504b1db073dSJordan Rose for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
15056a58efdfSEugene Zelenko const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1506b1db073dSJordan Rose
1507b1db073dSJordan Rose if (!PieceI)
1508b1db073dSJordan Rose continue;
1509b1db073dSJordan Rose
15101cf8cdc6SGeorge Karpenkov const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
15111cf8cdc6SGeorge Karpenkov const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
1512b1db073dSJordan Rose
1513b1db073dSJordan Rose if (!s1Start || !s1End)
1514b1db073dSJordan Rose continue;
1515b1db073dSJordan Rose
1516b1db073dSJordan Rose PathPieces::iterator NextI = I; ++NextI;
1517b1db073dSJordan Rose if (NextI == E)
1518b1db073dSJordan Rose break;
1519b1db073dSJordan Rose
15200dbb783cSCraig Topper PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
1521b1db073dSJordan Rose
1522b1db073dSJordan Rose while (true) {
1523b1db073dSJordan Rose if (NextI == E)
1524b1db073dSJordan Rose break;
1525b1db073dSJordan Rose
15266a58efdfSEugene Zelenko const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1527b1db073dSJordan Rose if (EV) {
1528b1db073dSJordan Rose StringRef S = EV->getString();
1529236dbd25SJordan Rose if (S == StrEnteringLoop || S == StrLoopBodyZero ||
1530236dbd25SJordan Rose S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
1531b1db073dSJordan Rose ++NextI;
1532b1db073dSJordan Rose continue;
1533b1db073dSJordan Rose }
1534b1db073dSJordan Rose break;
1535b1db073dSJordan Rose }
1536b1db073dSJordan Rose
15370a0c275fSDavid Blaikie PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1538b1db073dSJordan Rose break;
1539b1db073dSJordan Rose }
1540b1db073dSJordan Rose
1541b1db073dSJordan Rose if (!PieceNextI)
1542b1db073dSJordan Rose continue;
1543b1db073dSJordan Rose
15441cf8cdc6SGeorge Karpenkov const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
15451cf8cdc6SGeorge Karpenkov const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
1546b1db073dSJordan Rose
1547b1db073dSJordan Rose if (!s2Start || !s2End || s1End != s2Start)
1548b1db073dSJordan Rose continue;
1549b1db073dSJordan Rose
1550b1db073dSJordan Rose // We only perform this transformation for specific branch kinds.
1551b1db073dSJordan Rose // We don't want to do this for do..while, for example.
155216be17adSBalazs Benics if (!isa<ForStmt, WhileStmt, IfStmt, ObjCForCollectionStmt,
155316be17adSBalazs Benics CXXForRangeStmt>(s1Start))
1554b1db073dSJordan Rose continue;
1555b1db073dSJordan Rose
1556b1db073dSJordan Rose // Is s1End the branch condition?
1557b1db073dSJordan Rose if (!isConditionForTerminator(s1Start, s1End))
1558b1db073dSJordan Rose continue;
1559b1db073dSJordan Rose
1560b1db073dSJordan Rose // Perform the hoisting by eliminating (2) and changing the start
1561b1db073dSJordan Rose // location of (3).
1562b1db073dSJordan Rose PieceNextI->setStartLocation(PieceI->getStartLocation());
1563b1db073dSJordan Rose I = pieces.erase(I);
1564b1db073dSJordan Rose }
1565b1db073dSJordan Rose }
1566b1db073dSJordan Rose
15677ce598aeSJordan Rose /// Returns the number of bytes in the given (character-based) SourceRange.
15685f16849bSJordan Rose ///
15695f16849bSJordan Rose /// If the locations in the range are not on the same line, returns None.
15705f16849bSJordan Rose ///
15715f16849bSJordan Rose /// Note that this does not do a precise user-visible character or column count.
getLengthOnSingleLine(const SourceManager & SM,SourceRange Range)1572fc76d855SKristof Umann static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
15735f16849bSJordan Rose SourceRange Range) {
15745f16849bSJordan Rose SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
1575b5f8171aSRichard Smith SM.getExpansionRange(Range.getEnd()).getEnd());
15765f16849bSJordan Rose
15775f16849bSJordan Rose FileID FID = SM.getFileID(ExpansionRange.getBegin());
15785f16849bSJordan Rose if (FID != SM.getFileID(ExpansionRange.getEnd()))
15795f16849bSJordan Rose return None;
15805f16849bSJordan Rose
1581af4fb416SDuncan P. N. Exon Smith Optional<MemoryBufferRef> Buffer = SM.getBufferOrNone(FID);
1582af4fb416SDuncan P. N. Exon Smith if (!Buffer)
15835f16849bSJordan Rose return None;
15845f16849bSJordan Rose
15855f16849bSJordan Rose unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
15865f16849bSJordan Rose unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
15875f16849bSJordan Rose StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
15885f16849bSJordan Rose
15895f16849bSJordan Rose // We're searching the raw bytes of the buffer here, which might include
15905f16849bSJordan Rose // escaped newlines and such. That's okay; we're trying to decide whether the
15915f16849bSJordan Rose // SourceRange is covering a large or small amount of space in the user's
15925f16849bSJordan Rose // editor.
15935f16849bSJordan Rose if (Snippet.find_first_of("\r\n") != StringRef::npos)
15945f16849bSJordan Rose return None;
15955f16849bSJordan Rose
15965f16849bSJordan Rose // This isn't Unicode-aware, but it doesn't need to be.
15975f16849bSJordan Rose return Snippet.size();
15985f16849bSJordan Rose }
15995f16849bSJordan Rose
16005f16849bSJordan Rose /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
getLengthOnSingleLine(const SourceManager & SM,const Stmt * S)1601fc76d855SKristof Umann static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
16025f16849bSJordan Rose const Stmt *S) {
16035f16849bSJordan Rose return getLengthOnSingleLine(SM, S->getSourceRange());
16045f16849bSJordan Rose }
16055f16849bSJordan Rose
16065f16849bSJordan Rose /// Eliminate two-edge cycles created by addContextEdges().
16075f16849bSJordan Rose ///
16085f16849bSJordan Rose /// Once all the context edges are in place, there are plenty of cases where
16095f16849bSJordan Rose /// there's a single edge from a top-level statement to a subexpression,
16105f16849bSJordan Rose /// followed by a single path note, and then a reverse edge to get back out to
16115f16849bSJordan Rose /// the top level. If the statement is simple enough, the subexpression edges
16125f16849bSJordan Rose /// just add noise and make it harder to understand what's going on.
16135f16849bSJordan Rose ///
16145f16849bSJordan Rose /// This function only removes edges in pairs, because removing only one edge
16155f16849bSJordan Rose /// might leave other edges dangling.
16165f16849bSJordan Rose ///
16175f16849bSJordan Rose /// This will not remove edges in more complicated situations:
16185f16849bSJordan Rose /// - if there is more than one "hop" leading to or from a subexpression.
16195f16849bSJordan Rose /// - if there is an inlined call between the edges instead of a single event.
16205f16849bSJordan Rose /// - if the whole statement is large enough that having subexpression arrows
16215f16849bSJordan Rose /// might be helpful.
removeContextCycles(PathPieces & Path,const SourceManager & SM)1622fc76d855SKristof Umann static void removeContextCycles(PathPieces &Path, const SourceManager &SM) {
16238c54b44fSJordan Rose for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
16248c54b44fSJordan Rose // Pattern match the current piece and its successor.
16256a58efdfSEugene Zelenko const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
16268c54b44fSJordan Rose
16278c54b44fSJordan Rose if (!PieceI) {
16288c54b44fSJordan Rose ++I;
16298c54b44fSJordan Rose continue;
16308c54b44fSJordan Rose }
16318c54b44fSJordan Rose
16321cf8cdc6SGeorge Karpenkov const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
16331cf8cdc6SGeorge Karpenkov const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
16348c54b44fSJordan Rose
16358c54b44fSJordan Rose PathPieces::iterator NextI = I; ++NextI;
16368c54b44fSJordan Rose if (NextI == E)
16378c54b44fSJordan Rose break;
16388c54b44fSJordan Rose
16396a58efdfSEugene Zelenko const auto *PieceNextI =
16400a0c275fSDavid Blaikie dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
16418c54b44fSJordan Rose
16428c54b44fSJordan Rose if (!PieceNextI) {
16430a0c275fSDavid Blaikie if (isa<PathDiagnosticEventPiece>(NextI->get())) {
16448c54b44fSJordan Rose ++NextI;
16458c54b44fSJordan Rose if (NextI == E)
16468c54b44fSJordan Rose break;
16470a0c275fSDavid Blaikie PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
16488c54b44fSJordan Rose }
16498c54b44fSJordan Rose
16508c54b44fSJordan Rose if (!PieceNextI) {
16518c54b44fSJordan Rose ++I;
16528c54b44fSJordan Rose continue;
16538c54b44fSJordan Rose }
16548c54b44fSJordan Rose }
16558c54b44fSJordan Rose
16561cf8cdc6SGeorge Karpenkov const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
16571cf8cdc6SGeorge Karpenkov const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
16588c54b44fSJordan Rose
16598c54b44fSJordan Rose if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
16605f16849bSJordan Rose const size_t MAX_SHORT_LINE_LENGTH = 80;
16615f16849bSJordan Rose Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
16625f16849bSJordan Rose if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
16635f16849bSJordan Rose Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
16645f16849bSJordan Rose if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
16658c54b44fSJordan Rose Path.erase(I);
16668c54b44fSJordan Rose I = Path.erase(NextI);
16678c54b44fSJordan Rose continue;
16688c54b44fSJordan Rose }
16695f16849bSJordan Rose }
16705f16849bSJordan Rose }
16718c54b44fSJordan Rose
16728c54b44fSJordan Rose ++I;
16738c54b44fSJordan Rose }
16748c54b44fSJordan Rose }
16758c54b44fSJordan Rose
16769fc8faf9SAdrian Prantl /// Return true if X is contained by Y.
lexicalContains(const ParentMap & PM,const Stmt * X,const Stmt * Y)1677fc76d855SKristof Umann static bool lexicalContains(const ParentMap &PM, const Stmt *X, const Stmt *Y) {
16789f0629f6STed Kremenek while (X) {
16799f0629f6STed Kremenek if (X == Y)
16809f0629f6STed Kremenek return true;
16819f0629f6STed Kremenek X = PM.getParent(X);
16829f0629f6STed Kremenek }
16839f0629f6STed Kremenek return false;
16849f0629f6STed Kremenek }
16859f0629f6STed Kremenek
168655efcadcSTed Kremenek // Remove short edges on the same line less than 3 columns in difference.
removePunyEdges(PathPieces & path,const SourceManager & SM,const ParentMap & PM)1687fc76d855SKristof Umann static void removePunyEdges(PathPieces &path, const SourceManager &SM,
1688fc76d855SKristof Umann const ParentMap &PM) {
168955efcadcSTed Kremenek bool erased = false;
169055efcadcSTed Kremenek
169155efcadcSTed Kremenek for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
169255efcadcSTed Kremenek erased ? I : ++I) {
169355efcadcSTed Kremenek erased = false;
169455efcadcSTed Kremenek
16956a58efdfSEugene Zelenko const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
169655efcadcSTed Kremenek
169755efcadcSTed Kremenek if (!PieceI)
169855efcadcSTed Kremenek continue;
169955efcadcSTed Kremenek
17001cf8cdc6SGeorge Karpenkov const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
17011cf8cdc6SGeorge Karpenkov const Stmt *end = PieceI->getEndLocation().getStmtOrNull();
170255efcadcSTed Kremenek
170355efcadcSTed Kremenek if (!start || !end)
170455efcadcSTed Kremenek continue;
170555efcadcSTed Kremenek
170655efcadcSTed Kremenek const Stmt *endParent = PM.getParent(end);
170755efcadcSTed Kremenek if (!endParent)
170855efcadcSTed Kremenek continue;
170955efcadcSTed Kremenek
171055efcadcSTed Kremenek if (isConditionForTerminator(end, endParent))
171155efcadcSTed Kremenek continue;
171255efcadcSTed Kremenek
1713f2ceec48SStephen Kelly SourceLocation FirstLoc = start->getBeginLoc();
1714f2ceec48SStephen Kelly SourceLocation SecondLoc = end->getBeginLoc();
171555efcadcSTed Kremenek
17165ba37d52SEli Friedman if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
17175f16849bSJordan Rose continue;
17185f16849bSJordan Rose if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
17195f16849bSJordan Rose std::swap(SecondLoc, FirstLoc);
17205f16849bSJordan Rose
17215f16849bSJordan Rose SourceRange EdgeRange(FirstLoc, SecondLoc);
17225f16849bSJordan Rose Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
17235f16849bSJordan Rose
17245f16849bSJordan Rose // If the statements are on different lines, continue.
17255f16849bSJordan Rose if (!ByteWidth)
172655efcadcSTed Kremenek continue;
172755efcadcSTed Kremenek
17285f16849bSJordan Rose const size_t MAX_PUNY_EDGE_LENGTH = 2;
17295f16849bSJordan Rose if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
17305f16849bSJordan Rose // FIXME: There are enough /bytes/ between the endpoints of the edge, but
17315f16849bSJordan Rose // there might not be enough /columns/. A proper user-visible column count
17325f16849bSJordan Rose // is probably too expensive, though.
1733561060b7STed Kremenek I = path.erase(I);
173455efcadcSTed Kremenek erased = true;
173555efcadcSTed Kremenek continue;
173655efcadcSTed Kremenek }
173755efcadcSTed Kremenek }
173855efcadcSTed Kremenek }
173955efcadcSTed Kremenek
removeIdenticalEvents(PathPieces & path)17400962e56fSTed Kremenek static void removeIdenticalEvents(PathPieces &path) {
17410962e56fSTed Kremenek for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
17426a58efdfSEugene Zelenko const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
17430962e56fSTed Kremenek
17440962e56fSTed Kremenek if (!PieceI)
17450962e56fSTed Kremenek continue;
17460962e56fSTed Kremenek
17470962e56fSTed Kremenek PathPieces::iterator NextI = I; ++NextI;
17480962e56fSTed Kremenek if (NextI == E)
17490962e56fSTed Kremenek return;
17500962e56fSTed Kremenek
17516a58efdfSEugene Zelenko const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
17520962e56fSTed Kremenek
17530962e56fSTed Kremenek if (!PieceNextI)
17540962e56fSTed Kremenek continue;
17550962e56fSTed Kremenek
17560962e56fSTed Kremenek // Erase the second piece if it has the same exact message text.
17570962e56fSTed Kremenek if (PieceI->getString() == PieceNextI->getString()) {
17580962e56fSTed Kremenek path.erase(NextI);
17590962e56fSTed Kremenek }
17600962e56fSTed Kremenek }
17610962e56fSTed Kremenek }
17620962e56fSTed Kremenek
optimizeEdges(const PathDiagnosticConstruct & C,PathPieces & path,OptimizedCallsSet & OCS)1763edb78859SKristof Umann static bool optimizeEdges(const PathDiagnosticConstruct &C, PathPieces &path,
1764f9d75bedSKristof Umann OptimizedCallsSet &OCS) {
17656cf3c97cSTed Kremenek bool hasChanges = false;
1766f9d75bedSKristof Umann const LocationContext *LC = C.getLocationContextFor(&path);
17676cf3c97cSTed Kremenek assert(LC);
1768fc76d855SKristof Umann const ParentMap &PM = LC->getParentMap();
1769f9d75bedSKristof Umann const SourceManager &SM = C.getSourceManager();
17706cf3c97cSTed Kremenek
17719af6baaaSTed Kremenek for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
17726cf3c97cSTed Kremenek // Optimize subpaths.
17730a0c275fSDavid Blaikie if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
17749af6baaaSTed Kremenek // Record the fact that a call has been optimized so we only do the
17759af6baaaSTed Kremenek // effort once.
17767b9b5a2cSTed Kremenek if (!OCS.count(CallI)) {
1777f9d75bedSKristof Umann while (optimizeEdges(C, CallI->path, OCS)) {
1778f9d75bedSKristof Umann }
17797b9b5a2cSTed Kremenek OCS.insert(CallI);
17807b9b5a2cSTed Kremenek }
17819af6baaaSTed Kremenek ++I;
17826cf3c97cSTed Kremenek continue;
17836cf3c97cSTed Kremenek }
17846cf3c97cSTed Kremenek
17856cf3c97cSTed Kremenek // Pattern match the current piece and its successor.
17860a0c275fSDavid Blaikie auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
17876cf3c97cSTed Kremenek
17889af6baaaSTed Kremenek if (!PieceI) {
17899af6baaaSTed Kremenek ++I;
17906cf3c97cSTed Kremenek continue;
17919af6baaaSTed Kremenek }
17926cf3c97cSTed Kremenek
17931cf8cdc6SGeorge Karpenkov const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
17941cf8cdc6SGeorge Karpenkov const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
1795bcd6b0d8STed Kremenek const Stmt *level1 = getStmtParent(s1Start, PM);
1796bcd6b0d8STed Kremenek const Stmt *level2 = getStmtParent(s1End, PM);
1797bcd6b0d8STed Kremenek
17987b9b5a2cSTed Kremenek PathPieces::iterator NextI = I; ++NextI;
17997b9b5a2cSTed Kremenek if (NextI == E)
18007b9b5a2cSTed Kremenek break;
18017b9b5a2cSTed Kremenek
18026a58efdfSEugene Zelenko const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
18036cf3c97cSTed Kremenek
18049af6baaaSTed Kremenek if (!PieceNextI) {
18059af6baaaSTed Kremenek ++I;
18066cf3c97cSTed Kremenek continue;
18079af6baaaSTed Kremenek }
18086cf3c97cSTed Kremenek
18091cf8cdc6SGeorge Karpenkov const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
18101cf8cdc6SGeorge Karpenkov const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
1811bcd6b0d8STed Kremenek const Stmt *level3 = getStmtParent(s2Start, PM);
1812bcd6b0d8STed Kremenek const Stmt *level4 = getStmtParent(s2End, PM);
18136cf3c97cSTed Kremenek
18146cf3c97cSTed Kremenek // Rule I.
18156cf3c97cSTed Kremenek //
18166cf3c97cSTed Kremenek // If we have two consecutive control edges whose end/begin locations
18179af6baaaSTed Kremenek // are at the same level (e.g. statements or top-level expressions within
18189af6baaaSTed Kremenek // a compound statement, or siblings share a single ancestor expression),
18199af6baaaSTed Kremenek // then merge them if they have no interesting intermediate event.
18206cf3c97cSTed Kremenek //
18216cf3c97cSTed Kremenek // For example:
18226cf3c97cSTed Kremenek //
18236cf3c97cSTed Kremenek // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
18249af6baaaSTed Kremenek // parent is '1'. Here 'x.y.z' represents the hierarchy of statements.
18256cf3c97cSTed Kremenek //
18266cf3c97cSTed Kremenek // NOTE: this will be limited later in cases where we add barriers
18276cf3c97cSTed Kremenek // to prevent this optimization.
18289af6baaaSTed Kremenek if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
18296cf3c97cSTed Kremenek PieceI->setEndLocation(PieceNextI->getEndLocation());
18306cf3c97cSTed Kremenek path.erase(NextI);
18316cf3c97cSTed Kremenek hasChanges = true;
18326cf3c97cSTed Kremenek continue;
18336cf3c97cSTed Kremenek }
1834ccb6d1eaSTed Kremenek
1835ccb6d1eaSTed Kremenek // Rule II.
1836ccb6d1eaSTed Kremenek //
183775b8cdeeSTed Kremenek // Eliminate edges between subexpressions and parent expressions
183875b8cdeeSTed Kremenek // when the subexpression is consumed.
1839ccb6d1eaSTed Kremenek //
1840ccb6d1eaSTed Kremenek // NOTE: this will be limited later in cases where we add barriers
1841ccb6d1eaSTed Kremenek // to prevent this optimization.
18422f2a3042STed Kremenek if (s1End && s1End == s2Start && level2) {
18439f0629f6STed Kremenek bool removeEdge = false;
18449f0629f6STed Kremenek // Remove edges into the increment or initialization of a
18459f0629f6STed Kremenek // loop that have no interleaving event. This means that
18469f0629f6STed Kremenek // they aren't interesting.
18479f0629f6STed Kremenek if (isIncrementOrInitInForLoop(s1End, level2))
18489f0629f6STed Kremenek removeEdge = true;
18499f0629f6STed Kremenek // Next only consider edges that are not anchored on
18509f0629f6STed Kremenek // the condition of a terminator. This are intermediate edges
18519f0629f6STed Kremenek // that we might want to trim.
18529f0629f6STed Kremenek else if (!isConditionForTerminator(level2, s1End)) {
18539f0629f6STed Kremenek // Trim edges on expressions that are consumed by
18549f0629f6STed Kremenek // the parent expression.
18559f0629f6STed Kremenek if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
18569f0629f6STed Kremenek removeEdge = true;
18579f0629f6STed Kremenek }
18589f0629f6STed Kremenek // Trim edges where a lexical containment doesn't exist.
18599f0629f6STed Kremenek // For example:
18609f0629f6STed Kremenek //
18619f0629f6STed Kremenek // X -> Y -> Z
18629f0629f6STed Kremenek //
18639f0629f6STed Kremenek // If 'Z' lexically contains Y (it is an ancestor) and
18649f0629f6STed Kremenek // 'X' does not lexically contain Y (it is a descendant OR
18659f0629f6STed Kremenek // it has no lexical relationship at all) then trim.
18669f0629f6STed Kremenek //
18679f0629f6STed Kremenek // This can eliminate edges where we dive into a subexpression
18689f0629f6STed Kremenek // and then pop back out, etc.
18699f0629f6STed Kremenek else if (s1Start && s2End &&
18709f0629f6STed Kremenek lexicalContains(PM, s2Start, s2End) &&
18719f0629f6STed Kremenek !lexicalContains(PM, s1End, s1Start)) {
18729f0629f6STed Kremenek removeEdge = true;
18739f0629f6STed Kremenek }
18747ce598aeSJordan Rose // Trim edges from a subexpression back to the top level if the
18757ce598aeSJordan Rose // subexpression is on a different line.
18767ce598aeSJordan Rose //
18777ce598aeSJordan Rose // A.1 -> A -> B
18787ce598aeSJordan Rose // becomes
18797ce598aeSJordan Rose // A.1 -> B
18807ce598aeSJordan Rose //
18817ce598aeSJordan Rose // These edges just look ugly and don't usually add anything.
18827ce598aeSJordan Rose else if (s1Start && s2End &&
18837ce598aeSJordan Rose lexicalContains(PM, s1Start, s1End)) {
18847ce598aeSJordan Rose SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
18857ce598aeSJordan Rose PieceI->getStartLocation().asLocation());
1886452db157SKazu Hirata if (!getLengthOnSingleLine(SM, EdgeRange))
18877ce598aeSJordan Rose removeEdge = true;
18887ce598aeSJordan Rose }
18899f0629f6STed Kremenek }
18909f0629f6STed Kremenek
18919f0629f6STed Kremenek if (removeEdge) {
1892ccb6d1eaSTed Kremenek PieceI->setEndLocation(PieceNextI->getEndLocation());
1893ccb6d1eaSTed Kremenek path.erase(NextI);
1894ccb6d1eaSTed Kremenek hasChanges = true;
1895ccb6d1eaSTed Kremenek continue;
1896ccb6d1eaSTed Kremenek }
18972f2a3042STed Kremenek }
1898bcd6b0d8STed Kremenek
1899d4167a66STed Kremenek // Optimize edges for ObjC fast-enumeration loops.
1900d4167a66STed Kremenek //
1901d4167a66STed Kremenek // (X -> collection) -> (collection -> element)
1902d4167a66STed Kremenek //
1903d4167a66STed Kremenek // becomes:
1904d4167a66STed Kremenek //
1905d4167a66STed Kremenek // (X -> element)
1906d4167a66STed Kremenek if (s1End == s2Start) {
19076a58efdfSEugene Zelenko const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
1908d4167a66STed Kremenek if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
1909d4167a66STed Kremenek s2End == FS->getElement()) {
1910d4167a66STed Kremenek PieceI->setEndLocation(PieceNextI->getEndLocation());
1911d4167a66STed Kremenek path.erase(NextI);
1912d4167a66STed Kremenek hasChanges = true;
1913d4167a66STed Kremenek continue;
1914d4167a66STed Kremenek }
1915d4167a66STed Kremenek }
1916d4167a66STed Kremenek
19179af6baaaSTed Kremenek // No changes at this index? Move to the next one.
19189af6baaaSTed Kremenek ++I;
19196cf3c97cSTed Kremenek }
19206cf3c97cSTed Kremenek
192155efcadcSTed Kremenek if (!hasChanges) {
1922b1db073dSJordan Rose // Adjust edges into subexpressions to make them more uniform
1923b1db073dSJordan Rose // and aesthetically pleasing.
1924f9d75bedSKristof Umann addContextEdges(path, LC);
19258c54b44fSJordan Rose // Remove "cyclical" edges that include one or more context edges.
1926c82d457dSGeorge Karpenkov removeContextCycles(path, SM);
1927b1db073dSJordan Rose // Hoist edges originating from branch conditions to branches
1928b1db073dSJordan Rose // for simple branches.
1929b1db073dSJordan Rose simplifySimpleBranches(path);
193055efcadcSTed Kremenek // Remove any puny edges left over after primary optimization pass.
193155efcadcSTed Kremenek removePunyEdges(path, SM, PM);
19320962e56fSTed Kremenek // Remove identical events.
19330962e56fSTed Kremenek removeIdenticalEvents(path);
193455efcadcSTed Kremenek }
193555efcadcSTed Kremenek
19366cf3c97cSTed Kremenek return hasChanges;
19376cf3c97cSTed Kremenek }
19386cf3c97cSTed Kremenek
1939c892bb04SJordan Rose /// Drop the very first edge in a path, which should be a function entry edge.
19407a8bd943SJordan Rose ///
19417a8bd943SJordan Rose /// If the first edge is not a function entry edge (say, because the first
19427a8bd943SJordan Rose /// statement had an invalid source location), this function does nothing.
19437a8bd943SJordan Rose // FIXME: We should just generate invalid edges anyway and have the optimizer
19447a8bd943SJordan Rose // deal with them.
dropFunctionEntryEdge(const PathDiagnosticConstruct & C,PathPieces & Path)1945edb78859SKristof Umann static void dropFunctionEntryEdge(const PathDiagnosticConstruct &C,
1946f9d75bedSKristof Umann PathPieces &Path) {
19470a0c275fSDavid Blaikie const auto *FirstEdge =
19480a0c275fSDavid Blaikie dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
19497a8bd943SJordan Rose if (!FirstEdge)
19507a8bd943SJordan Rose return;
19517a8bd943SJordan Rose
1952f9d75bedSKristof Umann const Decl *D = C.getLocationContextFor(&Path)->getDecl();
1953f9d75bedSKristof Umann PathDiagnosticLocation EntryLoc =
1954f9d75bedSKristof Umann PathDiagnosticLocation::createBegin(D, C.getSourceManager());
19557a8bd943SJordan Rose if (FirstEdge->getStartLocation() != EntryLoc)
19567a8bd943SJordan Rose return;
1957c892bb04SJordan Rose
1958c892bb04SJordan Rose Path.pop_front();
1959c892bb04SJordan Rose }
1960c892bb04SJordan Rose
19615f8d361cSGeorge Karpenkov /// Populate executes lines with lines containing at least one diagnostics.
updateExecutedLinesWithDiagnosticPieces(PathDiagnostic & PD)19626d716ef1SKristof Umann static void updateExecutedLinesWithDiagnosticPieces(PathDiagnostic &PD) {
19635f8d361cSGeorge Karpenkov
19645f8d361cSGeorge Karpenkov PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
19655f8d361cSGeorge Karpenkov FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
19665f8d361cSGeorge Karpenkov
19675f8d361cSGeorge Karpenkov for (const auto &P : path) {
19685f8d361cSGeorge Karpenkov FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
19695f8d361cSGeorge Karpenkov FileID FID = Loc.getFileID();
19705f8d361cSGeorge Karpenkov unsigned LineNo = Loc.getLineNumber();
197155e3d1ecSGeorge Karpenkov assert(FID.isValid());
1972a3fdd179SGeorge Karpenkov ExecutedLines[FID].insert(LineNo);
19735f8d361cSGeorge Karpenkov }
19745f8d361cSGeorge Karpenkov }
19755f8d361cSGeorge Karpenkov
PathDiagnosticConstruct(const PathDiagnosticConsumer * PDC,const ExplodedNode * ErrorNode,const PathSensitiveBugReport * R)1976edb78859SKristof Umann PathDiagnosticConstruct::PathDiagnosticConstruct(
1977edb78859SKristof Umann const PathDiagnosticConsumer *PDC, const ExplodedNode *ErrorNode,
19782f169e7cSArtem Dergachev const PathSensitiveBugReport *R)
1979f9d75bedSKristof Umann : Consumer(PDC), CurrentNode(ErrorNode),
1980f9d75bedSKristof Umann SM(CurrentNode->getCodeDecl().getASTContext().getSourceManager()),
1981f9d75bedSKristof Umann PD(generateEmptyDiagnosticForReport(R, getSourceManager())) {
1982f9d75bedSKristof Umann LCM[&PD->getActivePath()] = ErrorNode->getLocationContext();
1983f9d75bedSKristof Umann }
198470ec1dd1SGeorge Karpenkov
PathDiagnosticBuilder(BugReporterContext BRC,std::unique_ptr<ExplodedGraph> BugPath,PathSensitiveBugReport * r,const ExplodedNode * ErrorNode,std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics)1985f9d75bedSKristof Umann PathDiagnosticBuilder::PathDiagnosticBuilder(
1986f9d75bedSKristof Umann BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
19872f169e7cSArtem Dergachev PathSensitiveBugReport *r, const ExplodedNode *ErrorNode,
1988f9d75bedSKristof Umann std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics)
1989f9d75bedSKristof Umann : BugReporterContext(BRC), BugPath(std::move(BugPath)), R(r),
1990f9d75bedSKristof Umann ErrorNode(ErrorNode),
1991f9d75bedSKristof Umann VisitorsDiagnostics(std::move(VisitorsDiagnostics)) {}
199270ec1dd1SGeorge Karpenkov
1993f9d75bedSKristof Umann std::unique_ptr<PathDiagnostic>
generate(const PathDiagnosticConsumer * PDC) const1994f9d75bedSKristof Umann PathDiagnosticBuilder::generate(const PathDiagnosticConsumer *PDC) const {
1995edb78859SKristof Umann PathDiagnosticConstruct Construct(PDC, ErrorNode, R);
1996f9d75bedSKristof Umann
1997f9d75bedSKristof Umann const SourceManager &SM = getSourceManager();
1998f9d75bedSKristof Umann const AnalyzerOptions &Opts = getAnalyzerOptions();
1999a079a427SCsaba Dabis
2000a079a427SCsaba Dabis if (!PDC->shouldGenerateDiagnostics())
2001a079a427SCsaba Dabis return generateEmptyDiagnosticForReport(R, getSourceManager());
2002f9d75bedSKristof Umann
2003f9d75bedSKristof Umann // Construct the final (warning) event for the bug report.
2004f9d75bedSKristof Umann auto EndNotes = VisitorsDiagnostics->find(ErrorNode);
20056d716ef1SKristof Umann PathDiagnosticPieceRef LastPiece;
2006f9d75bedSKristof Umann if (EndNotes != VisitorsDiagnostics->end()) {
200770ec1dd1SGeorge Karpenkov assert(!EndNotes->second.empty());
200870ec1dd1SGeorge Karpenkov LastPiece = EndNotes->second[0];
200970ec1dd1SGeorge Karpenkov } else {
2010f9d75bedSKristof Umann LastPiece = BugReporterVisitor::getDefaultEndPath(*this, ErrorNode,
2011f9d75bedSKristof Umann *getBugReport());
201270ec1dd1SGeorge Karpenkov }
2013f9d75bedSKristof Umann Construct.PD->setEndOfPath(LastPiece);
201470ec1dd1SGeorge Karpenkov
2015f9d75bedSKristof Umann PathDiagnosticLocation PrevLoc = Construct.PD->getLocation();
2016f9d75bedSKristof Umann // From the error node to the root, ascend the bug path and construct the bug
2017f9d75bedSKristof Umann // report.
2018f9d75bedSKristof Umann while (Construct.ascendToPrevNode()) {
2019f9d75bedSKristof Umann generatePathDiagnosticsForNode(Construct, PrevLoc);
202070ec1dd1SGeorge Karpenkov
2021f9d75bedSKristof Umann auto VisitorNotes = VisitorsDiagnostics->find(Construct.getCurrentNode());
2022f9d75bedSKristof Umann if (VisitorNotes == VisitorsDiagnostics->end())
202370ec1dd1SGeorge Karpenkov continue;
202470ec1dd1SGeorge Karpenkov
202570ec1dd1SGeorge Karpenkov // This is a workaround due to inability to put shared PathDiagnosticPiece
202670ec1dd1SGeorge Karpenkov // into a FoldingSet.
202770ec1dd1SGeorge Karpenkov std::set<llvm::FoldingSetNodeID> DeduplicationSet;
202870ec1dd1SGeorge Karpenkov
202970ec1dd1SGeorge Karpenkov // Add pieces from custom visitors.
20306d716ef1SKristof Umann for (const PathDiagnosticPieceRef &Note : VisitorNotes->second) {
203170ec1dd1SGeorge Karpenkov llvm::FoldingSetNodeID ID;
203270ec1dd1SGeorge Karpenkov Note->Profile(ID);
2033fc76d855SKristof Umann if (!DeduplicationSet.insert(ID).second)
203470ec1dd1SGeorge Karpenkov continue;
203570ec1dd1SGeorge Karpenkov
2036f9d75bedSKristof Umann if (PDC->shouldAddPathEdges())
2037f9d75bedSKristof Umann addEdgeToPath(Construct.getActivePath(), PrevLoc, Note->getLocation());
20388535b8ecSArtem Dergachev updateStackPiecesWithMessage(Note, Construct.CallStack);
2039f9d75bedSKristof Umann Construct.getActivePath().push_front(Note);
204070ec1dd1SGeorge Karpenkov }
204170ec1dd1SGeorge Karpenkov }
204270ec1dd1SGeorge Karpenkov
2043f9d75bedSKristof Umann if (PDC->shouldAddPathEdges()) {
204470ec1dd1SGeorge Karpenkov // Add an edge to the start of the function.
204570ec1dd1SGeorge Karpenkov // We'll prune it out later, but it helps make diagnostics more uniform.
2046f9d75bedSKristof Umann const StackFrameContext *CalleeLC =
2047f9d75bedSKristof Umann Construct.getLocationContextForActivePath()->getStackFrame();
204870ec1dd1SGeorge Karpenkov const Decl *D = CalleeLC->getDecl();
2049f9d75bedSKristof Umann addEdgeToPath(Construct.getActivePath(), PrevLoc,
2050c82d457dSGeorge Karpenkov PathDiagnosticLocation::createBegin(D, SM));
205170ec1dd1SGeorge Karpenkov }
205270ec1dd1SGeorge Karpenkov
205370ec1dd1SGeorge Karpenkov
205470ec1dd1SGeorge Karpenkov // Finally, prune the diagnostic path of uninteresting stuff.
2055f9d75bedSKristof Umann if (!Construct.PD->path.empty()) {
2056549f9cd4SKristof Umann if (R->shouldPrunePath() && Opts.ShouldPrunePaths) {
205770ec1dd1SGeorge Karpenkov bool stillHasNotes =
2058f9d75bedSKristof Umann removeUnneededCalls(Construct, Construct.getMutablePieces(), R);
205970ec1dd1SGeorge Karpenkov assert(stillHasNotes);
206070ec1dd1SGeorge Karpenkov (void)stillHasNotes;
206170ec1dd1SGeorge Karpenkov }
206270ec1dd1SGeorge Karpenkov
20631d7ca677SCsaba Dabis // Remove pop-up notes if needed.
20641d7ca677SCsaba Dabis if (!Opts.ShouldAddPopUpNotes)
2065f9d75bedSKristof Umann removePopUpNotes(Construct.getMutablePieces());
20661d7ca677SCsaba Dabis
206770ec1dd1SGeorge Karpenkov // Redirect all call pieces to have valid locations.
2068f9d75bedSKristof Umann adjustCallLocations(Construct.getMutablePieces());
2069f9d75bedSKristof Umann removePiecesWithInvalidLocations(Construct.getMutablePieces());
207070ec1dd1SGeorge Karpenkov
2071f9d75bedSKristof Umann if (PDC->shouldAddPathEdges()) {
207270ec1dd1SGeorge Karpenkov
207370ec1dd1SGeorge Karpenkov // Reduce the number of edges from a very conservative set
207470ec1dd1SGeorge Karpenkov // to an aesthetically pleasing subset that conveys the
207570ec1dd1SGeorge Karpenkov // necessary information.
207670ec1dd1SGeorge Karpenkov OptimizedCallsSet OCS;
2077f9d75bedSKristof Umann while (optimizeEdges(Construct, Construct.getMutablePieces(), OCS)) {
2078f9d75bedSKristof Umann }
207970ec1dd1SGeorge Karpenkov
208070ec1dd1SGeorge Karpenkov // Drop the very first function-entry edge. It's not really necessary
208170ec1dd1SGeorge Karpenkov // for top-level functions.
2082f9d75bedSKristof Umann dropFunctionEntryEdge(Construct, Construct.getMutablePieces());
208370ec1dd1SGeorge Karpenkov }
208470ec1dd1SGeorge Karpenkov
208570ec1dd1SGeorge Karpenkov // Remove messages that are basically the same, and edges that may not
208670ec1dd1SGeorge Karpenkov // make sense.
208770ec1dd1SGeorge Karpenkov // We have to do this after edge optimization in the Extensive mode.
2088f9d75bedSKristof Umann removeRedundantMsgs(Construct.getMutablePieces());
2089f9d75bedSKristof Umann removeEdgesToDefaultInitializers(Construct.getMutablePieces());
209070ec1dd1SGeorge Karpenkov }
20917d6d9eb6SKristof Umann
2092f9d75bedSKristof Umann if (Opts.ShouldDisplayMacroExpansions)
2093f9d75bedSKristof Umann CompactMacroExpandedPieces(Construct.getMutablePieces(), SM);
20947d6d9eb6SKristof Umann
2095f9d75bedSKristof Umann return std::move(Construct.PD);
209670ec1dd1SGeorge Karpenkov }
209770ec1dd1SGeorge Karpenkov
2098fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2099fa0734ecSArgyrios Kyrtzidis // Methods for BugType and subclasses.
2100fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
21016a58efdfSEugene Zelenko
anchor()21026feda287SJordan Rose void BugType::anchor() {}
2103a1540db6SArgyrios Kyrtzidis
anchor()210468e081d6SDavid Blaikie void BuiltinBug::anchor() {}
210568e081d6SDavid Blaikie
2106fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2107fa0734ecSArgyrios Kyrtzidis // Methods for BugReport and subclasses.
2108fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
21093a6bdf8fSAnna Zaks
2110cfd6b4b8SKirstóf Umann LLVM_ATTRIBUTE_USED static bool
isDependency(const CheckerRegistryData & Registry,StringRef CheckerName)2111cfd6b4b8SKirstóf Umann isDependency(const CheckerRegistryData &Registry, StringRef CheckerName) {
2112b2956076SKirstóf Umann for (const std::pair<StringRef, StringRef> &Pair : Registry.Dependencies) {
2113b2956076SKirstóf Umann if (Pair.second == CheckerName)
2114b2956076SKirstóf Umann return true;
2115b2956076SKirstóf Umann }
2116b2956076SKirstóf Umann return false;
2117b2956076SKirstóf Umann }
2118b2956076SKirstóf Umann
isHidden(const CheckerRegistryData & Registry,StringRef CheckerName)2119cfd6b4b8SKirstóf Umann LLVM_ATTRIBUTE_USED static bool isHidden(const CheckerRegistryData &Registry,
2120cfd6b4b8SKirstóf Umann StringRef CheckerName) {
2121cfd6b4b8SKirstóf Umann for (const CheckerInfo &Checker : Registry.Checkers) {
2122cfd6b4b8SKirstóf Umann if (Checker.FullName == CheckerName)
2123cfd6b4b8SKirstóf Umann return Checker.IsHidden;
2124cfd6b4b8SKirstóf Umann }
2125cfd6b4b8SKirstóf Umann llvm_unreachable(
2126cfd6b4b8SKirstóf Umann "Checker name not found in CheckerRegistry -- did you retrieve it "
2127cfd6b4b8SKirstóf Umann "correctly from CheckerManager::getCurrentCheckerName?");
2128cfd6b4b8SKirstóf Umann }
2129cfd6b4b8SKirstóf Umann
PathSensitiveBugReport(const BugType & bt,StringRef shortDesc,StringRef desc,const ExplodedNode * errorNode,PathDiagnosticLocation LocationToUnique,const Decl * DeclToUnique)2130b2956076SKirstóf Umann PathSensitiveBugReport::PathSensitiveBugReport(
2131b2956076SKirstóf Umann const BugType &bt, StringRef shortDesc, StringRef desc,
2132b2956076SKirstóf Umann const ExplodedNode *errorNode, PathDiagnosticLocation LocationToUnique,
2133b2956076SKirstóf Umann const Decl *DeclToUnique)
2134b2956076SKirstóf Umann : BugReport(Kind::PathSensitive, bt, shortDesc, desc), ErrorNode(errorNode),
2135b2956076SKirstóf Umann ErrorNodeRange(getStmt() ? getStmt()->getSourceRange() : SourceRange()),
2136b2956076SKirstóf Umann UniqueingLocation(LocationToUnique), UniqueingDecl(DeclToUnique) {
2137b2956076SKirstóf Umann assert(!isDependency(ErrorNode->getState()
2138b2956076SKirstóf Umann ->getAnalysisManager()
2139b2956076SKirstóf Umann .getCheckerManager()
2140b2956076SKirstóf Umann ->getCheckerRegistryData(),
2141b2956076SKirstóf Umann bt.getCheckerName()) &&
2142b2956076SKirstóf Umann "Some checkers depend on this one! We don't allow dependency "
2143b2956076SKirstóf Umann "checkers to emit warnings, because checkers should depend on "
2144b2956076SKirstóf Umann "*modeling*, not *diagnostics*.");
2145cfd6b4b8SKirstóf Umann
2146cfd6b4b8SKirstóf Umann assert(
2147cfcf8e17SMikael Holmen (bt.getCheckerName().startswith("debug") ||
2148cfd6b4b8SKirstóf Umann !isHidden(ErrorNode->getState()
2149cfd6b4b8SKirstóf Umann ->getAnalysisManager()
2150cfd6b4b8SKirstóf Umann .getCheckerManager()
2151cfd6b4b8SKirstóf Umann ->getCheckerRegistryData(),
2152cfcf8e17SMikael Holmen bt.getCheckerName())) &&
2153cfd6b4b8SKirstóf Umann "Hidden checkers musn't emit diagnostics as they are by definition "
2154cfd6b4b8SKirstóf Umann "non-user facing!");
2155b2956076SKirstóf Umann }
2156b2956076SKirstóf Umann
addVisitor(std::unique_ptr<BugReporterVisitor> visitor)21572f169e7cSArtem Dergachev void PathSensitiveBugReport::addVisitor(
21582f169e7cSArtem Dergachev std::unique_ptr<BugReporterVisitor> visitor) {
2159f4dd4ae7SAnna Zaks if (!visitor)
2160f4dd4ae7SAnna Zaks return;
2161f4dd4ae7SAnna Zaks
2162f4dd4ae7SAnna Zaks llvm::FoldingSetNodeID ID;
2163f4dd4ae7SAnna Zaks visitor->Profile(ID);
2164f4dd4ae7SAnna Zaks
216570ec1dd1SGeorge Karpenkov void *InsertPos = nullptr;
216670ec1dd1SGeorge Karpenkov if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
2167f4dd4ae7SAnna Zaks return;
216870ec1dd1SGeorge Karpenkov }
2169f4dd4ae7SAnna Zaks
217091e79026SDavid Blaikie Callbacks.push_back(std::move(visitor));
217170ec1dd1SGeorge Karpenkov }
217270ec1dd1SGeorge Karpenkov
clearVisitors()21732f169e7cSArtem Dergachev void PathSensitiveBugReport::clearVisitors() {
217470ec1dd1SGeorge Karpenkov Callbacks.clear();
2175f4dd4ae7SAnna Zaks }
2176f4dd4ae7SAnna Zaks
getDeclWithIssue() const21772f169e7cSArtem Dergachev const Decl *PathSensitiveBugReport::getDeclWithIssue() const {
21785a10f08bSTed Kremenek const ExplodedNode *N = getErrorNode();
21795a10f08bSTed Kremenek if (!N)
21800dbb783cSCraig Topper return nullptr;
21815a10f08bSTed Kremenek
21825a10f08bSTed Kremenek const LocationContext *LC = N->getLocationContext();
2183dd18b11bSGeorge Karpenkov return LC->getStackFrame()->getDecl();
21845a10f08bSTed Kremenek }
21855a10f08bSTed Kremenek
Profile(llvm::FoldingSetNodeID & hash) const21862f169e7cSArtem Dergachev void BasicBugReport::Profile(llvm::FoldingSetNodeID& hash) const {
21872f169e7cSArtem Dergachev hash.AddInteger(static_cast<int>(getKind()));
21882f169e7cSArtem Dergachev hash.AddPointer(&BT);
21892f169e7cSArtem Dergachev hash.AddString(Description);
21902f169e7cSArtem Dergachev assert(Location.isValid());
21912f169e7cSArtem Dergachev Location.Profile(hash);
21922f169e7cSArtem Dergachev
21932f169e7cSArtem Dergachev for (SourceRange range : Ranges) {
21942f169e7cSArtem Dergachev if (!range.isValid())
21952f169e7cSArtem Dergachev continue;
2196443ab4d2SMikhail Maltsev hash.Add(range.getBegin());
2197443ab4d2SMikhail Maltsev hash.Add(range.getEnd());
21982f169e7cSArtem Dergachev }
21992f169e7cSArtem Dergachev }
22002f169e7cSArtem Dergachev
Profile(llvm::FoldingSetNodeID & hash) const22012f169e7cSArtem Dergachev void PathSensitiveBugReport::Profile(llvm::FoldingSetNodeID &hash) const {
22022f169e7cSArtem Dergachev hash.AddInteger(static_cast<int>(getKind()));
22033a6bdf8fSAnna Zaks hash.AddPointer(&BT);
22043a6bdf8fSAnna Zaks hash.AddString(Description);
2205a043d0ceSAnna Zaks PathDiagnosticLocation UL = getUniqueingLocation();
2206a043d0ceSAnna Zaks if (UL.isValid()) {
2207a043d0ceSAnna Zaks UL.Profile(hash);
2208c29bed39SAnna Zaks } else {
22096b85f8e9SArtem Dergachev // TODO: The statement may be null if the report was emitted before any
22106b85f8e9SArtem Dergachev // statements were executed. In particular, some checkers by design
22116b85f8e9SArtem Dergachev // occasionally emit their reports in empty functions (that have no
22126b85f8e9SArtem Dergachev // statements in their body). Do we profile correctly in this case?
22136b85f8e9SArtem Dergachev hash.AddPointer(ErrorNode->getCurrentOrPreviousStmtForDiagnostics());
2214c29bed39SAnna Zaks }
22153a6bdf8fSAnna Zaks
2216e335f259SCraig Topper for (SourceRange range : Ranges) {
22173a6bdf8fSAnna Zaks if (!range.isValid())
22183a6bdf8fSAnna Zaks continue;
2219443ab4d2SMikhail Maltsev hash.Add(range.getBegin());
2220443ab4d2SMikhail Maltsev hash.Add(range.getEnd());
22213a6bdf8fSAnna Zaks }
22223a6bdf8fSAnna Zaks }
2223fa0734ecSArgyrios Kyrtzidis
2224fff01c8eSKristof Umann template <class T>
insertToInterestingnessMap(llvm::DenseMap<T,bugreporter::TrackingKind> & InterestingnessMap,T Val,bugreporter::TrackingKind TKind)2225fff01c8eSKristof Umann static void insertToInterestingnessMap(
2226fff01c8eSKristof Umann llvm::DenseMap<T, bugreporter::TrackingKind> &InterestingnessMap, T Val,
2227fff01c8eSKristof Umann bugreporter::TrackingKind TKind) {
2228fff01c8eSKristof Umann auto Result = InterestingnessMap.insert({Val, TKind});
2229fff01c8eSKristof Umann
2230fff01c8eSKristof Umann if (Result.second)
2231fff01c8eSKristof Umann return;
2232fff01c8eSKristof Umann
2233fff01c8eSKristof Umann // Even if this symbol/region was already marked as interesting as a
2234fff01c8eSKristof Umann // condition, if we later mark it as interesting again but with
2235fff01c8eSKristof Umann // thorough tracking, overwrite it. Entities marked with thorough
2236fff01c8eSKristof Umann // interestiness are the most important (or most interesting, if you will),
2237fff01c8eSKristof Umann // and we wouldn't like to downplay their importance.
2238fff01c8eSKristof Umann
2239fff01c8eSKristof Umann switch (TKind) {
2240fff01c8eSKristof Umann case bugreporter::TrackingKind::Thorough:
2241fff01c8eSKristof Umann Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
2242fff01c8eSKristof Umann return;
2243fff01c8eSKristof Umann case bugreporter::TrackingKind::Condition:
2244fff01c8eSKristof Umann return;
2245fff01c8eSKristof Umann }
2246fff01c8eSKristof Umann
2247fff01c8eSKristof Umann llvm_unreachable(
2248fff01c8eSKristof Umann "BugReport::markInteresting currently can only handle 2 different "
2249fff01c8eSKristof Umann "tracking kinds! Please define what tracking kind should this entitiy"
2250fff01c8eSKristof Umann "have, if it was already marked as interesting with a different kind!");
2251fff01c8eSKristof Umann }
2252fff01c8eSKristof Umann
markInteresting(SymbolRef sym,bugreporter::TrackingKind TKind)22532f169e7cSArtem Dergachev void PathSensitiveBugReport::markInteresting(SymbolRef sym,
2254fff01c8eSKristof Umann bugreporter::TrackingKind TKind) {
22551e809b4cSTed Kremenek if (!sym)
22561e809b4cSTed Kremenek return;
225743a9af73SJordy Rose
2258fff01c8eSKristof Umann insertToInterestingnessMap(InterestingSymbols, sym, TKind);
2259735724fbSJordy Rose
2260b0d38ad0SBalázs Kéri // FIXME: No tests exist for this code and it is questionable:
2261b0d38ad0SBalázs Kéri // How to handle multiple metadata for the same region?
22626a58efdfSEugene Zelenko if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2263fff01c8eSKristof Umann markInteresting(meta->getRegion(), TKind);
22641e809b4cSTed Kremenek }
22651e809b4cSTed Kremenek
markNotInteresting(SymbolRef sym)2266b0d38ad0SBalázs Kéri void PathSensitiveBugReport::markNotInteresting(SymbolRef sym) {
2267b0d38ad0SBalázs Kéri if (!sym)
2268b0d38ad0SBalázs Kéri return;
2269b0d38ad0SBalázs Kéri InterestingSymbols.erase(sym);
2270b0d38ad0SBalázs Kéri
2271b0d38ad0SBalázs Kéri // The metadata part of markInteresting is not reversed here.
2272b0d38ad0SBalázs Kéri // Just making the same region not interesting is incorrect
2273b0d38ad0SBalázs Kéri // in specific cases.
22740cd98befSDeep Majumder if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
22750cd98befSDeep Majumder markNotInteresting(meta->getRegion());
2276b0d38ad0SBalázs Kéri }
2277b0d38ad0SBalázs Kéri
markInteresting(const MemRegion * R,bugreporter::TrackingKind TKind)22782f169e7cSArtem Dergachev void PathSensitiveBugReport::markInteresting(const MemRegion *R,
2279fff01c8eSKristof Umann bugreporter::TrackingKind TKind) {
22801e809b4cSTed Kremenek if (!R)
22811e809b4cSTed Kremenek return;
228243a9af73SJordy Rose
22831e809b4cSTed Kremenek R = R->getBaseRegion();
2284fff01c8eSKristof Umann insertToInterestingnessMap(InterestingRegions, R, TKind);
22851e809b4cSTed Kremenek
22866a58efdfSEugene Zelenko if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2287fff01c8eSKristof Umann markInteresting(SR->getSymbol(), TKind);
22881e809b4cSTed Kremenek }
22891e809b4cSTed Kremenek
markNotInteresting(const MemRegion * R)2290b0d38ad0SBalázs Kéri void PathSensitiveBugReport::markNotInteresting(const MemRegion *R) {
2291b0d38ad0SBalázs Kéri if (!R)
2292b0d38ad0SBalázs Kéri return;
2293b0d38ad0SBalázs Kéri
2294b0d38ad0SBalázs Kéri R = R->getBaseRegion();
2295b0d38ad0SBalázs Kéri InterestingRegions.erase(R);
2296b0d38ad0SBalázs Kéri
2297b0d38ad0SBalázs Kéri if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2298b0d38ad0SBalázs Kéri markNotInteresting(SR->getSymbol());
2299b0d38ad0SBalázs Kéri }
2300b0d38ad0SBalázs Kéri
markInteresting(SVal V,bugreporter::TrackingKind TKind)23012f169e7cSArtem Dergachev void PathSensitiveBugReport::markInteresting(SVal V,
23022f169e7cSArtem Dergachev bugreporter::TrackingKind TKind) {
2303fff01c8eSKristof Umann markInteresting(V.getAsRegion(), TKind);
2304fff01c8eSKristof Umann markInteresting(V.getAsSymbol(), TKind);
23051e809b4cSTed Kremenek }
23061e809b4cSTed Kremenek
markInteresting(const LocationContext * LC)23072f169e7cSArtem Dergachev void PathSensitiveBugReport::markInteresting(const LocationContext *LC) {
23085d4ec363SAnna Zaks if (!LC)
23095d4ec363SAnna Zaks return;
23105d4ec363SAnna Zaks InterestingLocationContexts.insert(LC);
23115d4ec363SAnna Zaks }
23125d4ec363SAnna Zaks
2313fff01c8eSKristof Umann Optional<bugreporter::TrackingKind>
getInterestingnessKind(SVal V) const23142f169e7cSArtem Dergachev PathSensitiveBugReport::getInterestingnessKind(SVal V) const {
2315fff01c8eSKristof Umann auto RKind = getInterestingnessKind(V.getAsRegion());
2316fff01c8eSKristof Umann auto SKind = getInterestingnessKind(V.getAsSymbol());
2317fff01c8eSKristof Umann if (!RKind)
2318fff01c8eSKristof Umann return SKind;
2319fff01c8eSKristof Umann if (!SKind)
2320fff01c8eSKristof Umann return RKind;
2321fff01c8eSKristof Umann
2322fff01c8eSKristof Umann // If either is marked with throrough tracking, return that, we wouldn't like
2323fff01c8eSKristof Umann // to downplay a note's importance by 'only' mentioning it as a condition.
2324fff01c8eSKristof Umann switch(*RKind) {
2325fff01c8eSKristof Umann case bugreporter::TrackingKind::Thorough:
2326fff01c8eSKristof Umann return RKind;
2327fff01c8eSKristof Umann case bugreporter::TrackingKind::Condition:
2328fff01c8eSKristof Umann return SKind;
2329fff01c8eSKristof Umann }
2330fff01c8eSKristof Umann
2331fff01c8eSKristof Umann llvm_unreachable(
2332fff01c8eSKristof Umann "BugReport::getInterestingnessKind currently can only handle 2 different "
2333fff01c8eSKristof Umann "tracking kinds! Please define what tracking kind should we return here "
2334fff01c8eSKristof Umann "when the kind of getAsRegion() and getAsSymbol() is different!");
2335fff01c8eSKristof Umann return None;
2336fff01c8eSKristof Umann }
2337fff01c8eSKristof Umann
2338fff01c8eSKristof Umann Optional<bugreporter::TrackingKind>
getInterestingnessKind(SymbolRef sym) const23392f169e7cSArtem Dergachev PathSensitiveBugReport::getInterestingnessKind(SymbolRef sym) const {
2340fff01c8eSKristof Umann if (!sym)
2341fff01c8eSKristof Umann return None;
2342fff01c8eSKristof Umann // We don't currently consider metadata symbols to be interesting
2343fff01c8eSKristof Umann // even if we know their region is interesting. Is that correct behavior?
2344fff01c8eSKristof Umann auto It = InterestingSymbols.find(sym);
2345fff01c8eSKristof Umann if (It == InterestingSymbols.end())
2346fff01c8eSKristof Umann return None;
2347fff01c8eSKristof Umann return It->getSecond();
2348fff01c8eSKristof Umann }
2349fff01c8eSKristof Umann
2350fff01c8eSKristof Umann Optional<bugreporter::TrackingKind>
getInterestingnessKind(const MemRegion * R) const23512f169e7cSArtem Dergachev PathSensitiveBugReport::getInterestingnessKind(const MemRegion *R) const {
2352fff01c8eSKristof Umann if (!R)
2353fff01c8eSKristof Umann return None;
2354fff01c8eSKristof Umann
2355fff01c8eSKristof Umann R = R->getBaseRegion();
2356fff01c8eSKristof Umann auto It = InterestingRegions.find(R);
2357fff01c8eSKristof Umann if (It != InterestingRegions.end())
2358fff01c8eSKristof Umann return It->getSecond();
2359fff01c8eSKristof Umann
2360fff01c8eSKristof Umann if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2361fff01c8eSKristof Umann return getInterestingnessKind(SR->getSymbol());
2362fff01c8eSKristof Umann return None;
2363fff01c8eSKristof Umann }
2364fff01c8eSKristof Umann
isInteresting(SVal V) const23652f169e7cSArtem Dergachev bool PathSensitiveBugReport::isInteresting(SVal V) const {
2366*53daa177SKazu Hirata return getInterestingnessKind(V).has_value();
23671e809b4cSTed Kremenek }
23681e809b4cSTed Kremenek
isInteresting(SymbolRef sym) const23692f169e7cSArtem Dergachev bool PathSensitiveBugReport::isInteresting(SymbolRef sym) const {
2370*53daa177SKazu Hirata return getInterestingnessKind(sym).has_value();
23711e809b4cSTed Kremenek }
23721e809b4cSTed Kremenek
isInteresting(const MemRegion * R) const23732f169e7cSArtem Dergachev bool PathSensitiveBugReport::isInteresting(const MemRegion *R) const {
2374*53daa177SKazu Hirata return getInterestingnessKind(R).has_value();
23751e809b4cSTed Kremenek }
23761e809b4cSTed Kremenek
isInteresting(const LocationContext * LC) const23772f169e7cSArtem Dergachev bool PathSensitiveBugReport::isInteresting(const LocationContext *LC) const {
23785d4ec363SAnna Zaks if (!LC)
23795d4ec363SAnna Zaks return false;
23805d4ec363SAnna Zaks return InterestingLocationContexts.count(LC);
23815d4ec363SAnna Zaks }
23825d4ec363SAnna Zaks
getStmt() const23832f169e7cSArtem Dergachev const Stmt *PathSensitiveBugReport::getStmt() const {
23843a6bdf8fSAnna Zaks if (!ErrorNode)
23850dbb783cSCraig Topper return nullptr;
23863a6bdf8fSAnna Zaks
2387fa0734ecSArgyrios Kyrtzidis ProgramPoint ProgP = ErrorNode->getLocation();
23880dbb783cSCraig Topper const Stmt *S = nullptr;
2389fa0734ecSArgyrios Kyrtzidis
239087396b9bSDavid Blaikie if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2391fa0734ecSArgyrios Kyrtzidis CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2392fa0734ecSArgyrios Kyrtzidis if (BE->getBlock() == &Exit)
23936b85f8e9SArtem Dergachev S = ErrorNode->getPreviousStmtForDiagnostics();
2394fa0734ecSArgyrios Kyrtzidis }
2395fa0734ecSArgyrios Kyrtzidis if (!S)
23966b85f8e9SArtem Dergachev S = ErrorNode->getStmtForDiagnostics();
2397fa0734ecSArgyrios Kyrtzidis
2398fa0734ecSArgyrios Kyrtzidis return S;
2399fa0734ecSArgyrios Kyrtzidis }
2400fa0734ecSArgyrios Kyrtzidis
24012f169e7cSArtem Dergachev ArrayRef<SourceRange>
getRanges() const24022f169e7cSArtem Dergachev PathSensitiveBugReport::getRanges() const {
24033a6bdf8fSAnna Zaks // If no custom ranges, add the range of the statement corresponding to
24043a6bdf8fSAnna Zaks // the error node.
24052f169e7cSArtem Dergachev if (Ranges.empty() && isa_and_nonnull<Expr>(getStmt()))
24062f169e7cSArtem Dergachev return ErrorNodeRange;
24072f169e7cSArtem Dergachev
24082f169e7cSArtem Dergachev return Ranges;
2409fa0734ecSArgyrios Kyrtzidis }
2410fa0734ecSArgyrios Kyrtzidis
24112f169e7cSArtem Dergachev PathDiagnosticLocation
getLocation() const24122f169e7cSArtem Dergachev PathSensitiveBugReport::getLocation() const {
24136b85f8e9SArtem Dergachev assert(ErrorNode && "Cannot create a location with a null node.");
24146b85f8e9SArtem Dergachev const Stmt *S = ErrorNode->getStmtForDiagnostics();
24156b85f8e9SArtem Dergachev ProgramPoint P = ErrorNode->getLocation();
24166b85f8e9SArtem Dergachev const LocationContext *LC = P.getLocationContext();
24176b85f8e9SArtem Dergachev SourceManager &SM =
24186b85f8e9SArtem Dergachev ErrorNode->getState()->getStateManager().getContext().getSourceManager();
24196b85f8e9SArtem Dergachev
24206b85f8e9SArtem Dergachev if (!S) {
24216b85f8e9SArtem Dergachev // If this is an implicit call, return the implicit call point location.
24226b85f8e9SArtem Dergachev if (Optional<PreImplicitCall> PIE = P.getAs<PreImplicitCall>())
24236b85f8e9SArtem Dergachev return PathDiagnosticLocation(PIE->getLocation(), SM);
24246b85f8e9SArtem Dergachev if (auto FE = P.getAs<FunctionExitPoint>()) {
24256b85f8e9SArtem Dergachev if (const ReturnStmt *RS = FE->getStmt())
24266b85f8e9SArtem Dergachev return PathDiagnosticLocation::createBegin(RS, SM, LC);
24276b85f8e9SArtem Dergachev }
24286b85f8e9SArtem Dergachev S = ErrorNode->getNextStmtForDiagnostics();
24296b85f8e9SArtem Dergachev }
24306b85f8e9SArtem Dergachev
24316b85f8e9SArtem Dergachev if (S) {
24326b85f8e9SArtem Dergachev // For member expressions, return the location of the '.' or '->'.
24336b85f8e9SArtem Dergachev if (const auto *ME = dyn_cast<MemberExpr>(S))
24346b85f8e9SArtem Dergachev return PathDiagnosticLocation::createMemberLoc(ME, SM);
24356b85f8e9SArtem Dergachev
24366b85f8e9SArtem Dergachev // For binary operators, return the location of the operator.
24376b85f8e9SArtem Dergachev if (const auto *B = dyn_cast<BinaryOperator>(S))
24386b85f8e9SArtem Dergachev return PathDiagnosticLocation::createOperatorLoc(B, SM);
24396b85f8e9SArtem Dergachev
24406b85f8e9SArtem Dergachev if (P.getAs<PostStmtPurgeDeadSymbols>())
24416b85f8e9SArtem Dergachev return PathDiagnosticLocation::createEnd(S, SM, LC);
24426b85f8e9SArtem Dergachev
24436b85f8e9SArtem Dergachev if (S->getBeginLoc().isValid())
24446b85f8e9SArtem Dergachev return PathDiagnosticLocation(S, SM, LC);
24456b85f8e9SArtem Dergachev
24466b85f8e9SArtem Dergachev return PathDiagnosticLocation(
24476b85f8e9SArtem Dergachev PathDiagnosticLocation::getValidSourceLocation(S, LC), SM);
24486b85f8e9SArtem Dergachev }
24496b85f8e9SArtem Dergachev
24506b85f8e9SArtem Dergachev return PathDiagnosticLocation::createDeclEnd(ErrorNode->getLocationContext(),
24516b85f8e9SArtem Dergachev SM);
2452fa0734ecSArgyrios Kyrtzidis }
2453fa0734ecSArgyrios Kyrtzidis
2454fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2455fa0734ecSArgyrios Kyrtzidis // Methods for BugReporter and subclasses.
2456fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2457fa0734ecSArgyrios Kyrtzidis
getGraph() const2458ee92f12fSArtem Dergachev const ExplodedGraph &PathSensitiveBugReporter::getGraph() const {
2459ee92f12fSArtem Dergachev return Eng.getGraph();
2460ee92f12fSArtem Dergachev }
2461fa0734ecSArgyrios Kyrtzidis
getStateManager() const2462ee92f12fSArtem Dergachev ProgramStateManager &PathSensitiveBugReporter::getStateManager() const {
2463ee92f12fSArtem Dergachev return Eng.getStateManager();
2464ee92f12fSArtem Dergachev }
2465fc76d855SKristof Umann
BugReporter(BugReporterData & d)2466cbae0d82SDavid Blaikie BugReporter::BugReporter(BugReporterData &d) : D(d) {}
~BugReporter()2467be28d6c6SAnna Zaks BugReporter::~BugReporter() {
24683fdc427fSArtem Dergachev // Make sure reports are flushed.
24693fdc427fSArtem Dergachev assert(StrBugTypes.empty() &&
24703fdc427fSArtem Dergachev "Destroying BugReporter before diagnostics are emitted!");
2471be28d6c6SAnna Zaks
2472be28d6c6SAnna Zaks // Free the bug reports we are tracking.
24736a58efdfSEugene Zelenko for (const auto I : EQClassesVector)
24746a58efdfSEugene Zelenko delete I;
2475be28d6c6SAnna Zaks }
2476fa0734ecSArgyrios Kyrtzidis
FlushReports()2477fa0734ecSArgyrios Kyrtzidis void BugReporter::FlushReports() {
24784c03dfd4SAnna Zaks // We need to flush reports in deterministic order to ensure the order
24794c03dfd4SAnna Zaks // of the reports is consistent between runs.
24806a58efdfSEugene Zelenko for (const auto EQ : EQClassesVector)
24816a58efdfSEugene Zelenko FlushReport(*EQ);
2482fa0734ecSArgyrios Kyrtzidis
2483a1540db6SArgyrios Kyrtzidis // BugReporter owns and deletes only BugTypes created implicitly through
2484a1540db6SArgyrios Kyrtzidis // EmitBasicReport.
2485a1540db6SArgyrios Kyrtzidis // FIXME: There are leaks from checkers that assume that the BugTypes they
2486a1540db6SArgyrios Kyrtzidis // create will be destroyed by the BugReporter.
2487cbae0d82SDavid Blaikie StrBugTypes.clear();
2488fa0734ecSArgyrios Kyrtzidis }
2489fa0734ecSArgyrios Kyrtzidis
2490fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2491fa0734ecSArgyrios Kyrtzidis // PathDiagnostics generation.
2492fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2493fa0734ecSArgyrios Kyrtzidis
24947a007bfbSJordan Rose namespace {
24956a58efdfSEugene Zelenko
2496ed9cc407SKristof Umann /// A wrapper around an ExplodedGraph that contains a single path from the root
24976b9d7c9dSDmitri Gribenko /// to the error node.
2498ed9cc407SKristof Umann class BugPathInfo {
24997a007bfbSJordan Rose public:
2500f9d75bedSKristof Umann std::unique_ptr<ExplodedGraph> BugPath;
25012f169e7cSArtem Dergachev PathSensitiveBugReport *Report;
2502f342adefSJordan Rose const ExplodedNode *ErrorNode;
25037a007bfbSJordan Rose };
2504fa0734ecSArgyrios Kyrtzidis
2505ed9cc407SKristof Umann /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
2506ed9cc407SKristof Umann /// conveniently retrieve bug paths from a single error node to the root.
2507ed9cc407SKristof Umann class BugPathGetter {
2508ed9cc407SKristof Umann std::unique_ptr<ExplodedGraph> TrimmedGraph;
2509ed9cc407SKristof Umann
25106a58efdfSEugene Zelenko using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
25116a58efdfSEugene Zelenko
2512ed9cc407SKristof Umann /// Assign each node with its distance from the root.
251386e04ceaSJordan Rose PriorityMapTy PriorityMap;
251486e04ceaSJordan Rose
2515ed9cc407SKristof Umann /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
2516ed9cc407SKristof Umann /// we need to pair it to the error node of the constructed trimmed graph.
25172f169e7cSArtem Dergachev using ReportNewNodePair =
25182f169e7cSArtem Dergachev std::pair<PathSensitiveBugReport *, const ExplodedNode *>;
2519ed9cc407SKristof Umann SmallVector<ReportNewNodePair, 32> ReportNodes;
25206a58efdfSEugene Zelenko
2521ed9cc407SKristof Umann BugPathInfo CurrentBugPath;
2522f342adefSJordan Rose
2523f342adefSJordan Rose /// A helper class for sorting ExplodedNodes by priority.
2524f342adefSJordan Rose template <bool Descending>
2525f342adefSJordan Rose class PriorityCompare {
2526f342adefSJordan Rose const PriorityMapTy &PriorityMap;
2527f342adefSJordan Rose
2528f342adefSJordan Rose public:
PriorityCompare(const PriorityMapTy & M)2529f342adefSJordan Rose PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2530f342adefSJordan Rose
operator ()(const ExplodedNode * LHS,const ExplodedNode * RHS) const2531f342adefSJordan Rose bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2532f342adefSJordan Rose PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2533f342adefSJordan Rose PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2534f342adefSJordan Rose PriorityMapTy::const_iterator E = PriorityMap.end();
2535f342adefSJordan Rose
2536f342adefSJordan Rose if (LI == E)
2537f342adefSJordan Rose return Descending;
2538f342adefSJordan Rose if (RI == E)
2539f342adefSJordan Rose return !Descending;
2540f342adefSJordan Rose
2541f342adefSJordan Rose return Descending ? LI->second > RI->second
2542f342adefSJordan Rose : LI->second < RI->second;
2543f342adefSJordan Rose }
2544f342adefSJordan Rose
operator ()(const ReportNewNodePair & LHS,const ReportNewNodePair & RHS) const2545ed9cc407SKristof Umann bool operator()(const ReportNewNodePair &LHS,
2546ed9cc407SKristof Umann const ReportNewNodePair &RHS) const {
2547ed9cc407SKristof Umann return (*this)(LHS.second, RHS.second);
2548f342adefSJordan Rose }
2549f342adefSJordan Rose };
2550f342adefSJordan Rose
25517a007bfbSJordan Rose public:
2552ed9cc407SKristof Umann BugPathGetter(const ExplodedGraph *OriginalGraph,
25532f169e7cSArtem Dergachev ArrayRef<PathSensitiveBugReport *> &bugReports);
255486e04ceaSJordan Rose
2555ed9cc407SKristof Umann BugPathInfo *getNextBugPath();
255686e04ceaSJordan Rose };
25576a58efdfSEugene Zelenko
25586a58efdfSEugene Zelenko } // namespace
255986e04ceaSJordan Rose
BugPathGetter(const ExplodedGraph * OriginalGraph,ArrayRef<PathSensitiveBugReport * > & bugReports)2560ed9cc407SKristof Umann BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
25612f169e7cSArtem Dergachev ArrayRef<PathSensitiveBugReport *> &bugReports) {
2562ed9cc407SKristof Umann SmallVector<const ExplodedNode *, 32> Nodes;
2563ed9cc407SKristof Umann for (const auto I : bugReports) {
2564ed9cc407SKristof Umann assert(I->isValid() &&
2565ed9cc407SKristof Umann "We only allow BugReporterVisitors and BugReporter itself to "
2566ed9cc407SKristof Umann "invalidate reports!");
2567ed9cc407SKristof Umann Nodes.emplace_back(I->getErrorNode());
2568ed9cc407SKristof Umann }
2569ed9cc407SKristof Umann
25702d0edec9SJordan Rose // The trimmed graph is created in the body of the constructor to ensure
25712d0edec9SJordan Rose // that the DenseMaps have been initialized already.
2572f342adefSJordan Rose InterExplodedGraphMap ForwardMap;
25736b9d7c9dSDmitri Gribenko TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap);
257486e04ceaSJordan Rose
257586e04ceaSJordan Rose // Find the (first) error node in the trimmed graph. We just need to consult
257686e04ceaSJordan Rose // the node map which maps from nodes in the original graph to nodes
257786e04ceaSJordan Rose // in the new graph.
2578f342adefSJordan Rose llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
257986e04ceaSJordan Rose
25802f169e7cSArtem Dergachev for (PathSensitiveBugReport *Report : bugReports) {
2581ed9cc407SKristof Umann const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
2582ed9cc407SKristof Umann assert(NewNode &&
2583ed9cc407SKristof Umann "Failed to construct a trimmed graph that contains this error "
2584ed9cc407SKristof Umann "node!");
2585ed9cc407SKristof Umann ReportNodes.emplace_back(Report, NewNode);
2586f342adefSJordan Rose RemainingNodes.insert(NewNode);
258786e04ceaSJordan Rose }
25882d0edec9SJordan Rose
2589f342adefSJordan Rose assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
25902d0edec9SJordan Rose
2591f342adefSJordan Rose // Perform a forward BFS to find all the shortest paths.
2592f342adefSJordan Rose std::queue<const ExplodedNode *> WS;
2593f342adefSJordan Rose
2594ed9cc407SKristof Umann assert(TrimmedGraph->num_roots() == 1);
2595ed9cc407SKristof Umann WS.push(*TrimmedGraph->roots_begin());
2596f342adefSJordan Rose unsigned Priority = 0;
2597f342adefSJordan Rose
259886e04ceaSJordan Rose while (!WS.empty()) {
2599f342adefSJordan Rose const ExplodedNode *Node = WS.front();
260086e04ceaSJordan Rose WS.pop();
260186e04ceaSJordan Rose
260286e04ceaSJordan Rose PriorityMapTy::iterator PriorityEntry;
260386e04ceaSJordan Rose bool IsNew;
2604ed9cc407SKristof Umann std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
2605f342adefSJordan Rose ++Priority;
260686e04ceaSJordan Rose
260786e04ceaSJordan Rose if (!IsNew) {
260886e04ceaSJordan Rose assert(PriorityEntry->second <= Priority);
260986e04ceaSJordan Rose continue;
26102d0edec9SJordan Rose }
26112d0edec9SJordan Rose
2612f342adefSJordan Rose if (RemainingNodes.erase(Node))
2613f342adefSJordan Rose if (RemainingNodes.empty())
2614f342adefSJordan Rose break;
261586e04ceaSJordan Rose
2616ed9cc407SKristof Umann for (const ExplodedNode *Succ : Node->succs())
2617ed9cc407SKristof Umann WS.push(Succ);
261886e04ceaSJordan Rose }
261986e04ceaSJordan Rose
2620f342adefSJordan Rose // Sort the error paths from longest to shortest.
262155fab260SFangrui Song llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
262286e04ceaSJordan Rose }
26237a007bfbSJordan Rose
getNextBugPath()2624ed9cc407SKristof Umann BugPathInfo *BugPathGetter::getNextBugPath() {
2625f342adefSJordan Rose if (ReportNodes.empty())
2626ed9cc407SKristof Umann return nullptr;
2627fa0734ecSArgyrios Kyrtzidis
2628f342adefSJordan Rose const ExplodedNode *OrigN;
2629ed9cc407SKristof Umann std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
2630f342adefSJordan Rose assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2631f342adefSJordan Rose "error node not accessible from root");
2632fa0734ecSArgyrios Kyrtzidis
2633ed9cc407SKristof Umann // Create a new graph with a single path. This is the graph that will be
2634ed9cc407SKristof Umann // returned to the caller.
26352b3d49b6SJonas Devlieghere auto GNew = std::make_unique<ExplodedGraph>();
2636fa0734ecSArgyrios Kyrtzidis
2637f342adefSJordan Rose // Now walk from the error node up the BFS path, always taking the
2638f342adefSJordan Rose // predeccessor with the lowest number.
26390dbb783cSCraig Topper ExplodedNode *Succ = nullptr;
2640f342adefSJordan Rose while (true) {
2641fa0734ecSArgyrios Kyrtzidis // Create the equivalent node in the new graph with the same state
2642fa0734ecSArgyrios Kyrtzidis // and location.
2643ed9cc407SKristof Umann ExplodedNode *NewN = GNew->createUncachedNode(
264414e9eb3dSArtem Dergachev OrigN->getLocation(), OrigN->getState(),
264514e9eb3dSArtem Dergachev OrigN->getID(), OrigN->isSink());
2646fa0734ecSArgyrios Kyrtzidis
2647fa0734ecSArgyrios Kyrtzidis // Link up the new node with the previous node.
2648f342adefSJordan Rose if (Succ)
2649f342adefSJordan Rose Succ->addPredecessor(NewN, *GNew);
2650f342adefSJordan Rose else
2651ed9cc407SKristof Umann CurrentBugPath.ErrorNode = NewN;
2652fa0734ecSArgyrios Kyrtzidis
2653f342adefSJordan Rose Succ = NewN;
2654fa0734ecSArgyrios Kyrtzidis
2655fa0734ecSArgyrios Kyrtzidis // Are we at the final node?
2656f342adefSJordan Rose if (OrigN->pred_empty()) {
2657f342adefSJordan Rose GNew->addRoot(NewN);
2658fa0734ecSArgyrios Kyrtzidis break;
2659fa0734ecSArgyrios Kyrtzidis }
2660fa0734ecSArgyrios Kyrtzidis
2661f342adefSJordan Rose // Find the next predeccessor node. We choose the node that is marked
266286e04ceaSJordan Rose // with the lowest BFS number.
2663f342adefSJordan Rose OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2664f342adefSJordan Rose PriorityCompare<false>(PriorityMap));
2665fa0734ecSArgyrios Kyrtzidis }
2666fa0734ecSArgyrios Kyrtzidis
2667f9d75bedSKristof Umann CurrentBugPath.BugPath = std::move(GNew);
2668ad464dbfSDavid Blaikie
2669ed9cc407SKristof Umann return &CurrentBugPath;
267086e04ceaSJordan Rose }
267186e04ceaSJordan Rose
26727d6d9eb6SKristof Umann /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
26737d6d9eb6SKristof Umann /// object and collapses PathDiagosticPieces that are expanded by macros.
CompactMacroExpandedPieces(PathPieces & path,const SourceManager & SM)26747d6d9eb6SKristof Umann static void CompactMacroExpandedPieces(PathPieces &path,
26757d6d9eb6SKristof Umann const SourceManager& SM) {
26766d716ef1SKristof Umann using MacroStackTy = std::vector<
26776a58efdfSEugene Zelenko std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
2678fa0734ecSArgyrios Kyrtzidis
26796d716ef1SKristof Umann using PiecesTy = std::vector<PathDiagnosticPieceRef>;
2680fa0734ecSArgyrios Kyrtzidis
2681fa0734ecSArgyrios Kyrtzidis MacroStackTy MacroStack;
2682fa0734ecSArgyrios Kyrtzidis PiecesTy Pieces;
2683fa0734ecSArgyrios Kyrtzidis
2684eba09facSTed Kremenek for (PathPieces::const_iterator I = path.begin(), E = path.end();
268560a7820fSTed Kremenek I != E; ++I) {
26866a58efdfSEugene Zelenko const auto &piece = *I;
2687f9e9d330STed Kremenek
2688f9e9d330STed Kremenek // Recursively compact calls.
26890a0c275fSDavid Blaikie if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
26907d6d9eb6SKristof Umann CompactMacroExpandedPieces(call->path, SM);
2691f9e9d330STed Kremenek }
2692f9e9d330STed Kremenek
2693fa0734ecSArgyrios Kyrtzidis // Get the location of the PathDiagnosticPiece.
2694f9e9d330STed Kremenek const FullSourceLoc Loc = piece->getLocation().asLocation();
2695fa0734ecSArgyrios Kyrtzidis
2696fa0734ecSArgyrios Kyrtzidis // Determine the instantiation location, which is the location we group
2697fa0734ecSArgyrios Kyrtzidis // related PathDiagnosticPieces.
2698fa0734ecSArgyrios Kyrtzidis SourceLocation InstantiationLoc = Loc.isMacroID() ?
269935f5320dSChandler Carruth SM.getExpansionLoc(Loc) :
2700fa0734ecSArgyrios Kyrtzidis SourceLocation();
2701fa0734ecSArgyrios Kyrtzidis
2702fa0734ecSArgyrios Kyrtzidis if (Loc.isFileID()) {
2703fa0734ecSArgyrios Kyrtzidis MacroStack.clear();
2704f9e9d330STed Kremenek Pieces.push_back(piece);
2705fa0734ecSArgyrios Kyrtzidis continue;
2706fa0734ecSArgyrios Kyrtzidis }
2707fa0734ecSArgyrios Kyrtzidis
2708fa0734ecSArgyrios Kyrtzidis assert(Loc.isMacroID());
2709fa0734ecSArgyrios Kyrtzidis
2710fa0734ecSArgyrios Kyrtzidis // Is the PathDiagnosticPiece within the same macro group?
2711fa0734ecSArgyrios Kyrtzidis if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2712f9e9d330STed Kremenek MacroStack.back().first->subPieces.push_back(piece);
2713fa0734ecSArgyrios Kyrtzidis continue;
2714fa0734ecSArgyrios Kyrtzidis }
2715fa0734ecSArgyrios Kyrtzidis
2716fa0734ecSArgyrios Kyrtzidis // We aren't in the same group. Are we descending into a new macro
2717fa0734ecSArgyrios Kyrtzidis // or are part of an old one?
27180a0c275fSDavid Blaikie std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
2719fa0734ecSArgyrios Kyrtzidis
2720fa0734ecSArgyrios Kyrtzidis SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
272135f5320dSChandler Carruth SM.getExpansionLoc(Loc) :
2722fa0734ecSArgyrios Kyrtzidis SourceLocation();
2723fa0734ecSArgyrios Kyrtzidis
2724fa0734ecSArgyrios Kyrtzidis // Walk the entire macro stack.
2725fa0734ecSArgyrios Kyrtzidis while (!MacroStack.empty()) {
2726fa0734ecSArgyrios Kyrtzidis if (InstantiationLoc == MacroStack.back().second) {
2727fa0734ecSArgyrios Kyrtzidis MacroGroup = MacroStack.back().first;
2728fa0734ecSArgyrios Kyrtzidis break;
2729fa0734ecSArgyrios Kyrtzidis }
2730fa0734ecSArgyrios Kyrtzidis
2731fa0734ecSArgyrios Kyrtzidis if (ParentInstantiationLoc == MacroStack.back().second) {
2732fa0734ecSArgyrios Kyrtzidis MacroGroup = MacroStack.back().first;
2733fa0734ecSArgyrios Kyrtzidis break;
2734fa0734ecSArgyrios Kyrtzidis }
2735fa0734ecSArgyrios Kyrtzidis
2736fa0734ecSArgyrios Kyrtzidis MacroStack.pop_back();
2737fa0734ecSArgyrios Kyrtzidis }
2738fa0734ecSArgyrios Kyrtzidis
2739fa0734ecSArgyrios Kyrtzidis if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2740fa0734ecSArgyrios Kyrtzidis // Create a new macro group and add it to the stack.
27410a0c275fSDavid Blaikie auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
2742f9e9d330STed Kremenek PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2743fa0734ecSArgyrios Kyrtzidis
2744fa0734ecSArgyrios Kyrtzidis if (MacroGroup)
2745afa6e249STed Kremenek MacroGroup->subPieces.push_back(NewGroup);
2746fa0734ecSArgyrios Kyrtzidis else {
2747fa0734ecSArgyrios Kyrtzidis assert(InstantiationLoc.isFileID());
2748fa0734ecSArgyrios Kyrtzidis Pieces.push_back(NewGroup);
2749fa0734ecSArgyrios Kyrtzidis }
2750fa0734ecSArgyrios Kyrtzidis
2751fa0734ecSArgyrios Kyrtzidis MacroGroup = NewGroup;
2752fa0734ecSArgyrios Kyrtzidis MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2753fa0734ecSArgyrios Kyrtzidis }
2754fa0734ecSArgyrios Kyrtzidis
2755fa0734ecSArgyrios Kyrtzidis // Finally, add the PathDiagnosticPiece to the group.
2756f9e9d330STed Kremenek MacroGroup->subPieces.push_back(piece);
2757fa0734ecSArgyrios Kyrtzidis }
2758fa0734ecSArgyrios Kyrtzidis
2759fa0734ecSArgyrios Kyrtzidis // Now take the pieces and construct a new PathDiagnostic.
2760f9e9d330STed Kremenek path.clear();
2761fa0734ecSArgyrios Kyrtzidis
2762f989042fSBenjamin Kramer path.insert(path.end(), Pieces.begin(), Pieces.end());
2763fa0734ecSArgyrios Kyrtzidis }
2764fa0734ecSArgyrios Kyrtzidis
276570ec1dd1SGeorge Karpenkov /// Generate notes from all visitors.
27661cb15b10SAaron Puchert /// Notes associated with @c ErrorNode are generated using
27671cb15b10SAaron Puchert /// @c getEndPath, and the rest are generated with @c VisitNode.
276870ec1dd1SGeorge Karpenkov static std::unique_ptr<VisitorsDiagnosticsTy>
generateVisitorsDiagnostics(PathSensitiveBugReport * R,const ExplodedNode * ErrorNode,BugReporterContext & BRC)27692f169e7cSArtem Dergachev generateVisitorsDiagnostics(PathSensitiveBugReport *R,
27702f169e7cSArtem Dergachev const ExplodedNode *ErrorNode,
277170ec1dd1SGeorge Karpenkov BugReporterContext &BRC) {
2772f9d75bedSKristof Umann std::unique_ptr<VisitorsDiagnosticsTy> Notes =
27732b3d49b6SJonas Devlieghere std::make_unique<VisitorsDiagnosticsTy>();
27742f169e7cSArtem Dergachev PathSensitiveBugReport::VisitorList visitors;
27755a751b99SJordan Rose
277670ec1dd1SGeorge Karpenkov // Run visitors on all nodes starting from the node *before* the last one.
27771cb15b10SAaron Puchert // The last node is reserved for notes generated with @c getEndPath.
277870ec1dd1SGeorge Karpenkov const ExplodedNode *NextNode = ErrorNode->getFirstPred();
277970ec1dd1SGeorge Karpenkov while (NextNode) {
278070ec1dd1SGeorge Karpenkov
2781ed9cc407SKristof Umann // At each iteration, move all visitors from report to visitor list. This is
2782ed9cc407SKristof Umann // important, because the Profile() functions of the visitors make sure that
2783ed9cc407SKristof Umann // a visitor isn't added multiple times for the same node, but it's fine
2784ed9cc407SKristof Umann // to add the a visitor with Profile() for different nodes (e.g. tracking
2785ed9cc407SKristof Umann // a region at different points of the symbolic execution).
2786ed9cc407SKristof Umann for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
2787ed9cc407SKristof Umann visitors.push_back(std::move(Visitor));
2788ed9cc407SKristof Umann
278970ec1dd1SGeorge Karpenkov R->clearVisitors();
279070ec1dd1SGeorge Karpenkov
279170ec1dd1SGeorge Karpenkov const ExplodedNode *Pred = NextNode->getFirstPred();
279270ec1dd1SGeorge Karpenkov if (!Pred) {
27936d716ef1SKristof Umann PathDiagnosticPieceRef LastPiece;
279470ec1dd1SGeorge Karpenkov for (auto &V : visitors) {
279570ec1dd1SGeorge Karpenkov V->finalizeVisitor(BRC, ErrorNode, *R);
279670ec1dd1SGeorge Karpenkov
279770ec1dd1SGeorge Karpenkov if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
279870ec1dd1SGeorge Karpenkov assert(!LastPiece &&
279970ec1dd1SGeorge Karpenkov "There can only be one final piece in a diagnostic.");
2800ed9cc407SKristof Umann assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
2801ed9cc407SKristof Umann "The final piece must contain a message!");
280270ec1dd1SGeorge Karpenkov LastPiece = std::move(Piece);
280370ec1dd1SGeorge Karpenkov (*Notes)[ErrorNode].push_back(LastPiece);
28045a751b99SJordan Rose }
280553159311SJordan Rose }
280670ec1dd1SGeorge Karpenkov break;
280770ec1dd1SGeorge Karpenkov }
280853159311SJordan Rose
280970ec1dd1SGeorge Karpenkov for (auto &V : visitors) {
2810c82d457dSGeorge Karpenkov auto P = V->VisitNode(NextNode, BRC, *R);
281170ec1dd1SGeorge Karpenkov if (P)
281270ec1dd1SGeorge Karpenkov (*Notes)[NextNode].push_back(std::move(P));
281370ec1dd1SGeorge Karpenkov }
28145a751b99SJordan Rose
281570ec1dd1SGeorge Karpenkov if (!R->isValid())
281670ec1dd1SGeorge Karpenkov break;
28176a58efdfSEugene Zelenko
281870ec1dd1SGeorge Karpenkov NextNode = Pred;
281970ec1dd1SGeorge Karpenkov }
2820fa0734ecSArgyrios Kyrtzidis
282170ec1dd1SGeorge Karpenkov return Notes;
282270ec1dd1SGeorge Karpenkov }
282370ec1dd1SGeorge Karpenkov
findValidReport(ArrayRef<PathSensitiveBugReport * > & bugReports,PathSensitiveBugReporter & Reporter)28242f169e7cSArtem Dergachev Optional<PathDiagnosticBuilder> PathDiagnosticBuilder::findValidReport(
28252f169e7cSArtem Dergachev ArrayRef<PathSensitiveBugReport *> &bugReports,
2826ee92f12fSArtem Dergachev PathSensitiveBugReporter &Reporter) {
2827f9d75bedSKristof Umann
2828ed9cc407SKristof Umann BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
2829ed9cc407SKristof Umann
2830ed9cc407SKristof Umann while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
2831fa0734ecSArgyrios Kyrtzidis // Find the BugReport with the original location.
28322f169e7cSArtem Dergachev PathSensitiveBugReport *R = BugPath->Report;
2833fa0734ecSArgyrios Kyrtzidis assert(R && "No original report found for sliced graph.");
2834e42122e6SJordan Rose assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2835ed9cc407SKristof Umann const ExplodedNode *ErrorNode = BugPath->ErrorNode;
2836fa0734ecSArgyrios Kyrtzidis
28378cd2ee1fSMikhail R. Gadelha // Register refutation visitors first, if they mark the bug invalid no
28388cd2ee1fSMikhail R. Gadelha // further analysis is required
283992d03c20SValeriy Savchenko R->addVisitor<LikelyFalsePositiveSuppressionBRVisitor>();
28408cd2ee1fSMikhail R. Gadelha
2841f4dd4ae7SAnna Zaks // Register additional node visitors.
284292d03c20SValeriy Savchenko R->addVisitor<NilReceiverBRVisitor>();
284392d03c20SValeriy Savchenko R->addVisitor<ConditionBRVisitor>();
284492d03c20SValeriy Savchenko R->addVisitor<TagVisitor>();
2845a2bbac3fSTed Kremenek
28466b9d7c9dSDmitri Gribenko BugReporterContext BRC(Reporter);
284743a9af73SJordy Rose
284870ec1dd1SGeorge Karpenkov // Run all visitors on a given graph, once.
284970ec1dd1SGeorge Karpenkov std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
285070ec1dd1SGeorge Karpenkov generateVisitorsDiagnostics(R, ErrorNode, BRC);
285143a9af73SJordy Rose
2852c7f89ad6SMikhail R. Gadelha if (R->isValid()) {
2853ed9cc407SKristof Umann if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
2854c7f89ad6SMikhail R. Gadelha // If crosscheck is enabled, remove all visitors, add the refutation
2855c7f89ad6SMikhail R. Gadelha // visitor and check again
2856c7f89ad6SMikhail R. Gadelha R->clearVisitors();
285792d03c20SValeriy Savchenko R->addVisitor<FalsePositiveRefutationBRVisitor>();
2858c7f89ad6SMikhail R. Gadelha
2859de361df3SBalazs Benics // We don't overwrite the notes inserted by other visitors because the
2860c7f89ad6SMikhail R. Gadelha // refutation manager does not add any new note to the path
2861ed9cc407SKristof Umann generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
2862c7f89ad6SMikhail R. Gadelha }
2863c7f89ad6SMikhail R. Gadelha
2864c7f89ad6SMikhail R. Gadelha // Check if the bug is still valid
286570ec1dd1SGeorge Karpenkov if (R->isValid())
2866f9d75bedSKristof Umann return PathDiagnosticBuilder(
2867f9d75bedSKristof Umann std::move(BRC), std::move(BugPath->BugPath), BugPath->Report,
2868f9d75bedSKristof Umann BugPath->ErrorNode, std::move(visitorNotes));
286970ec1dd1SGeorge Karpenkov }
2870c7f89ad6SMikhail R. Gadelha }
2871c7f89ad6SMikhail R. Gadelha
2872ed9cc407SKristof Umann return {};
287370ec1dd1SGeorge Karpenkov }
287443a9af73SJordy Rose
287570ec1dd1SGeorge Karpenkov std::unique_ptr<DiagnosticForConsumerMapTy>
generatePathDiagnostics(ArrayRef<PathDiagnosticConsumer * > consumers,ArrayRef<PathSensitiveBugReport * > & bugReports)2876ee92f12fSArtem Dergachev PathSensitiveBugReporter::generatePathDiagnostics(
287770ec1dd1SGeorge Karpenkov ArrayRef<PathDiagnosticConsumer *> consumers,
28782f169e7cSArtem Dergachev ArrayRef<PathSensitiveBugReport *> &bugReports) {
287970ec1dd1SGeorge Karpenkov assert(!bugReports.empty());
288070ec1dd1SGeorge Karpenkov
28812b3d49b6SJonas Devlieghere auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
2882be608303SAnna Zaks
2883f9d75bedSKristof Umann Optional<PathDiagnosticBuilder> PDB =
2884f9d75bedSKristof Umann PathDiagnosticBuilder::findValidReport(bugReports, *this);
288570ec1dd1SGeorge Karpenkov
2886a079a427SCsaba Dabis if (PDB) {
2887a079a427SCsaba Dabis for (PathDiagnosticConsumer *PC : consumers) {
2888a079a427SCsaba Dabis if (std::unique_ptr<PathDiagnostic> PD = PDB->generate(PC)) {
2889a079a427SCsaba Dabis (*Out)[PC] = std::move(PD);
2890a079a427SCsaba Dabis }
2891a079a427SCsaba Dabis }
2892a079a427SCsaba Dabis }
289388255cc5SAnna Zaks
289470ec1dd1SGeorge Karpenkov return Out;
2895e42122e6SJordan Rose }
2896e42122e6SJordan Rose
emitReport(std::unique_ptr<BugReport> R)28978d3a7a56SAaron Ballman void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
28982f169e7cSArtem Dergachev bool ValidSourceLoc = R->getLocation().isValid();
28995fbe7f97SJordan Rose assert(ValidSourceLoc);
29005fbe7f97SJordan Rose // If we mess up in a release build, we'd still prefer to just drop the bug
29015fbe7f97SJordan Rose // instead of trying to go on.
29025fbe7f97SJordan Rose if (!ValidSourceLoc)
29035fbe7f97SJordan Rose return;
29045fbe7f97SJordan Rose
2905fa0734ecSArgyrios Kyrtzidis // Compute the bug report's hash to determine its equivalence class.
2906fa0734ecSArgyrios Kyrtzidis llvm::FoldingSetNodeID ID;
2907fa0734ecSArgyrios Kyrtzidis R->Profile(ID);
2908fa0734ecSArgyrios Kyrtzidis
2909fa0734ecSArgyrios Kyrtzidis // Lookup the equivance class. If there isn't one, create it.
2910fa0734ecSArgyrios Kyrtzidis void *InsertPos;
2911a1540db6SArgyrios Kyrtzidis BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2912fa0734ecSArgyrios Kyrtzidis
2913fa0734ecSArgyrios Kyrtzidis if (!EQ) {
29148d3a7a56SAaron Ballman EQ = new BugReportEquivClass(std::move(R));
2915a1540db6SArgyrios Kyrtzidis EQClasses.InsertNode(EQ, InsertPos);
2916be28d6c6SAnna Zaks EQClassesVector.push_back(EQ);
291743e3717bSDavid Blaikie } else
29188d3a7a56SAaron Ballman EQ->AddReport(std::move(R));
2919fa0734ecSArgyrios Kyrtzidis }
2920fa0734ecSArgyrios Kyrtzidis
emitReport(std::unique_ptr<BugReport> R)29212f169e7cSArtem Dergachev void PathSensitiveBugReporter::emitReport(std::unique_ptr<BugReport> R) {
29222f169e7cSArtem Dergachev if (auto PR = dyn_cast<PathSensitiveBugReport>(R.get()))
29232f169e7cSArtem Dergachev if (const ExplodedNode *E = PR->getErrorNode()) {
29242f169e7cSArtem Dergachev // An error node must either be a sink or have a tag, otherwise
29252f169e7cSArtem Dergachev // it could get reclaimed before the path diagnostic is created.
29262f169e7cSArtem Dergachev assert((E->isSink() || E->getLocation().getTag()) &&
29272f169e7cSArtem Dergachev "Error node must either be a sink or have a tag");
29282f169e7cSArtem Dergachev
29292f169e7cSArtem Dergachev const AnalysisDeclContext *DeclCtx =
29302f169e7cSArtem Dergachev E->getLocationContext()->getAnalysisDeclContext();
29312f169e7cSArtem Dergachev // The source of autosynthesized body can be handcrafted AST or a model
29322f169e7cSArtem Dergachev // file. The locations from handcrafted ASTs have no valid source
29332f169e7cSArtem Dergachev // locations and have to be discarded. Locations from model files should
29342f169e7cSArtem Dergachev // be preserved for processing and reporting.
29352f169e7cSArtem Dergachev if (DeclCtx->isBodyAutosynthesized() &&
29362f169e7cSArtem Dergachev !DeclCtx->isBodyAutosynthesizedFromModelFile())
29372f169e7cSArtem Dergachev return;
29382f169e7cSArtem Dergachev }
29392f169e7cSArtem Dergachev
29402f169e7cSArtem Dergachev BugReporter::emitReport(std::move(R));
29412f169e7cSArtem Dergachev }
29422f169e7cSArtem Dergachev
2943fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2944fa0734ecSArgyrios Kyrtzidis // Emitting reports in equivalence classes.
2945fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
2946fa0734ecSArgyrios Kyrtzidis
2947fa0734ecSArgyrios Kyrtzidis namespace {
29486a58efdfSEugene Zelenko
2949fa0734ecSArgyrios Kyrtzidis struct FRIEC_WLItem {
2950fa0734ecSArgyrios Kyrtzidis const ExplodedNode *N;
2951fa0734ecSArgyrios Kyrtzidis ExplodedNode::const_succ_iterator I, E;
2952fa0734ecSArgyrios Kyrtzidis
FRIEC_WLItem__anon1dcbea900311::FRIEC_WLItem2953fa0734ecSArgyrios Kyrtzidis FRIEC_WLItem(const ExplodedNode *n)
2954fa0734ecSArgyrios Kyrtzidis : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2955fa0734ecSArgyrios Kyrtzidis };
29566a58efdfSEugene Zelenko
29576a58efdfSEugene Zelenko } // namespace
2958fa0734ecSArgyrios Kyrtzidis
findReportInEquivalenceClass(BugReportEquivClass & EQ,SmallVectorImpl<BugReport * > & bugReports)29592f169e7cSArtem Dergachev BugReport *PathSensitiveBugReporter::findReportInEquivalenceClass(
29602f169e7cSArtem Dergachev BugReportEquivClass &EQ, SmallVectorImpl<BugReport *> &bugReports) {
2961fa0734ecSArgyrios Kyrtzidis // If we don't need to suppress any of the nodes because they are
2962fa0734ecSArgyrios Kyrtzidis // post-dominated by a sink, simply add all the nodes in the equivalence class
2963fa0734ecSArgyrios Kyrtzidis // to 'Nodes'. Any of the reports will serve as a "representative" report.
2964589273beSArtem Dergachev assert(EQ.getReports().size() > 0);
2965589273beSArtem Dergachev const BugType& BT = EQ.getReports()[0]->getBugType();
2966fa0734ecSArgyrios Kyrtzidis if (!BT.isSuppressOnSink()) {
2967589273beSArtem Dergachev BugReport *R = EQ.getReports()[0].get();
2968589273beSArtem Dergachev for (auto &J : EQ.getReports()) {
2969589273beSArtem Dergachev if (auto *PR = dyn_cast<PathSensitiveBugReport>(J.get())) {
29702f169e7cSArtem Dergachev R = PR;
29712f169e7cSArtem Dergachev bugReports.push_back(PR);
2972fa0734ecSArgyrios Kyrtzidis }
2973fa0734ecSArgyrios Kyrtzidis }
2974fa0734ecSArgyrios Kyrtzidis return R;
2975fa0734ecSArgyrios Kyrtzidis }
2976fa0734ecSArgyrios Kyrtzidis
2977fa0734ecSArgyrios Kyrtzidis // For bug reports that should be suppressed when all paths are post-dominated
2978fa0734ecSArgyrios Kyrtzidis // by a sink node, iterate through the reports in the equivalence class
2979fa0734ecSArgyrios Kyrtzidis // until we find one that isn't post-dominated (if one exists). We use a
2980fa0734ecSArgyrios Kyrtzidis // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
2981fa0734ecSArgyrios Kyrtzidis // this as a recursive function, but we don't want to risk blowing out the
2982fa0734ecSArgyrios Kyrtzidis // stack for very long paths.
29830dbb783cSCraig Topper BugReport *exampleReport = nullptr;
2984fa0734ecSArgyrios Kyrtzidis
2985589273beSArtem Dergachev for (const auto &I: EQ.getReports()) {
2986589273beSArtem Dergachev auto *R = dyn_cast<PathSensitiveBugReport>(I.get());
29872f169e7cSArtem Dergachev if (!R)
2988fa0734ecSArgyrios Kyrtzidis continue;
29892f169e7cSArtem Dergachev
29902f169e7cSArtem Dergachev const ExplodedNode *errorNode = R->getErrorNode();
2991fa0734ecSArgyrios Kyrtzidis if (errorNode->isSink()) {
299283d382b1SDavid Blaikie llvm_unreachable(
2993fa0734ecSArgyrios Kyrtzidis "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2994fa0734ecSArgyrios Kyrtzidis }
2995fa0734ecSArgyrios Kyrtzidis // No successors? By definition this nodes isn't post-dominated by a sink.
2996fa0734ecSArgyrios Kyrtzidis if (errorNode->succ_empty()) {
29972f169e7cSArtem Dergachev bugReports.push_back(R);
2998fa0734ecSArgyrios Kyrtzidis if (!exampleReport)
29992f169e7cSArtem Dergachev exampleReport = R;
3000fa0734ecSArgyrios Kyrtzidis continue;
3001fa0734ecSArgyrios Kyrtzidis }
3002fa0734ecSArgyrios Kyrtzidis
30030e0a8b4dSArtem Dergachev // See if we are in a no-return CFG block. If so, treat this similarly
30040e0a8b4dSArtem Dergachev // to being post-dominated by a sink. This works better when the analysis
3005a7c80a4cSArtem Dergachev // is incomplete and we have never reached the no-return function call(s)
3006a7c80a4cSArtem Dergachev // that we'd inevitably bump into on this path.
3007dd53bdbfSKristof Umann if (const CFGBlock *ErrorB = errorNode->getCFGBlock())
3008dd53bdbfSKristof Umann if (ErrorB->isInevitablySinking())
30090e0a8b4dSArtem Dergachev continue;
30100e0a8b4dSArtem Dergachev
3011fa0734ecSArgyrios Kyrtzidis // At this point we know that 'N' is not a sink and it has at least one
3012fa0734ecSArgyrios Kyrtzidis // successor. Use a DFS worklist to find a non-sink end-of-path node.
30136a58efdfSEugene Zelenko using WLItem = FRIEC_WLItem;
30146a58efdfSEugene Zelenko using DFSWorkList = SmallVector<WLItem, 10>;
30156a58efdfSEugene Zelenko
3016fa0734ecSArgyrios Kyrtzidis llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
3017fa0734ecSArgyrios Kyrtzidis
3018fa0734ecSArgyrios Kyrtzidis DFSWorkList WL;
3019fa0734ecSArgyrios Kyrtzidis WL.push_back(errorNode);
3020fa0734ecSArgyrios Kyrtzidis Visited[errorNode] = 1;
3021fa0734ecSArgyrios Kyrtzidis
3022fa0734ecSArgyrios Kyrtzidis while (!WL.empty()) {
3023fa0734ecSArgyrios Kyrtzidis WLItem &WI = WL.back();
3024fa0734ecSArgyrios Kyrtzidis assert(!WI.N->succ_empty());
3025fa0734ecSArgyrios Kyrtzidis
3026fa0734ecSArgyrios Kyrtzidis for (; WI.I != WI.E; ++WI.I) {
3027fa0734ecSArgyrios Kyrtzidis const ExplodedNode *Succ = *WI.I;
3028fa0734ecSArgyrios Kyrtzidis // End-of-path node?
3029fa0734ecSArgyrios Kyrtzidis if (Succ->succ_empty()) {
3030fa0734ecSArgyrios Kyrtzidis // If we found an end-of-path node that is not a sink.
3031fa0734ecSArgyrios Kyrtzidis if (!Succ->isSink()) {
30322f169e7cSArtem Dergachev bugReports.push_back(R);
3033fa0734ecSArgyrios Kyrtzidis if (!exampleReport)
30342f169e7cSArtem Dergachev exampleReport = R;
3035fa0734ecSArgyrios Kyrtzidis WL.clear();
3036fa0734ecSArgyrios Kyrtzidis break;
3037fa0734ecSArgyrios Kyrtzidis }
3038fa0734ecSArgyrios Kyrtzidis // Found a sink? Continue on to the next successor.
3039fa0734ecSArgyrios Kyrtzidis continue;
3040fa0734ecSArgyrios Kyrtzidis }
3041fa0734ecSArgyrios Kyrtzidis // Mark the successor as visited. If it hasn't been explored,
3042fa0734ecSArgyrios Kyrtzidis // enqueue it to the DFS worklist.
3043fa0734ecSArgyrios Kyrtzidis unsigned &mark = Visited[Succ];
3044fa0734ecSArgyrios Kyrtzidis if (!mark) {
3045fa0734ecSArgyrios Kyrtzidis mark = 1;
3046fa0734ecSArgyrios Kyrtzidis WL.push_back(Succ);
3047fa0734ecSArgyrios Kyrtzidis break;
3048fa0734ecSArgyrios Kyrtzidis }
3049fa0734ecSArgyrios Kyrtzidis }
3050fa0734ecSArgyrios Kyrtzidis
3051fa0734ecSArgyrios Kyrtzidis // The worklist may have been cleared at this point. First
3052fa0734ecSArgyrios Kyrtzidis // check if it is empty before checking the last item.
3053fa0734ecSArgyrios Kyrtzidis if (!WL.empty() && &WL.back() == &WI)
3054fa0734ecSArgyrios Kyrtzidis WL.pop_back();
3055fa0734ecSArgyrios Kyrtzidis }
3056fa0734ecSArgyrios Kyrtzidis }
3057fa0734ecSArgyrios Kyrtzidis
3058fa0734ecSArgyrios Kyrtzidis // ExampleReport will be NULL if all the nodes in the equivalence class
3059fa0734ecSArgyrios Kyrtzidis // were post-dominated by sinks.
3060fa0734ecSArgyrios Kyrtzidis return exampleReport;
3061fa0734ecSArgyrios Kyrtzidis }
3062fa0734ecSArgyrios Kyrtzidis
FlushReport(BugReportEquivClass & EQ)3063fa0734ecSArgyrios Kyrtzidis void BugReporter::FlushReport(BugReportEquivClass& EQ) {
30640e62c1ccSChris Lattner SmallVector<BugReport*, 10> bugReports;
30652f169e7cSArtem Dergachev BugReport *report = findReportInEquivalenceClass(EQ, bugReports);
306670ec1dd1SGeorge Karpenkov if (!report)
306770ec1dd1SGeorge Karpenkov return;
306870ec1dd1SGeorge Karpenkov
30699cca5c13SKirstóf Umann // See whether we need to silence the checker/package.
30709cca5c13SKirstóf Umann for (const std::string &CheckerOrPackage :
30719cca5c13SKirstóf Umann getAnalyzerOptions().SilencedCheckersAndPackages) {
30729cca5c13SKirstóf Umann if (report->getBugType().getCheckerName().startswith(
30739cca5c13SKirstóf Umann CheckerOrPackage))
30749cca5c13SKirstóf Umann return;
30759cca5c13SKirstóf Umann }
30769cca5c13SKirstóf Umann
307770ec1dd1SGeorge Karpenkov ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
307870ec1dd1SGeorge Karpenkov std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
307970ec1dd1SGeorge Karpenkov generateDiagnosticForConsumerMap(report, Consumers, bugReports);
308070ec1dd1SGeorge Karpenkov
308170ec1dd1SGeorge Karpenkov for (auto &P : *Diagnostics) {
308270ec1dd1SGeorge Karpenkov PathDiagnosticConsumer *Consumer = P.first;
308370ec1dd1SGeorge Karpenkov std::unique_ptr<PathDiagnostic> &PD = P.second;
308470ec1dd1SGeorge Karpenkov
308570ec1dd1SGeorge Karpenkov // If the path is empty, generate a single step path with the location
308670ec1dd1SGeorge Karpenkov // of the issue.
308770ec1dd1SGeorge Karpenkov if (PD->path.empty()) {
30882f169e7cSArtem Dergachev PathDiagnosticLocation L = report->getLocation();
30892b3d49b6SJonas Devlieghere auto piece = std::make_unique<PathDiagnosticEventPiece>(
309070ec1dd1SGeorge Karpenkov L, report->getDescription());
309170ec1dd1SGeorge Karpenkov for (SourceRange Range : report->getRanges())
309270ec1dd1SGeorge Karpenkov piece->addRange(Range);
309370ec1dd1SGeorge Karpenkov PD->setEndOfPath(std::move(piece));
30949bf9af92STed Kremenek }
309570ec1dd1SGeorge Karpenkov
309670ec1dd1SGeorge Karpenkov PathPieces &Pieces = PD->getMutablePieces();
3097549f9cd4SKristof Umann if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
309870ec1dd1SGeorge Karpenkov // For path diagnostic consumers that don't support extra notes,
309970ec1dd1SGeorge Karpenkov // we may optionally convert those to path notes.
310070ec1dd1SGeorge Karpenkov for (auto I = report->getNotes().rbegin(),
310170ec1dd1SGeorge Karpenkov E = report->getNotes().rend(); I != E; ++I) {
310270ec1dd1SGeorge Karpenkov PathDiagnosticNotePiece *Piece = I->get();
310370ec1dd1SGeorge Karpenkov auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
310470ec1dd1SGeorge Karpenkov Piece->getLocation(), Piece->getString());
310570ec1dd1SGeorge Karpenkov for (const auto &R: Piece->getRanges())
310670ec1dd1SGeorge Karpenkov ConvertedPiece->addRange(R);
310770ec1dd1SGeorge Karpenkov
310870ec1dd1SGeorge Karpenkov Pieces.push_front(std::move(ConvertedPiece));
310970ec1dd1SGeorge Karpenkov }
311070ec1dd1SGeorge Karpenkov } else {
311170ec1dd1SGeorge Karpenkov for (auto I = report->getNotes().rbegin(),
311270ec1dd1SGeorge Karpenkov E = report->getNotes().rend(); I != E; ++I)
311370ec1dd1SGeorge Karpenkov Pieces.push_front(*I);
311470ec1dd1SGeorge Karpenkov }
311570ec1dd1SGeorge Karpenkov
31166cee434eSArtem Dergachev for (const auto &I : report->getFixits())
31176cee434eSArtem Dergachev Pieces.back()->addFixit(I);
31186cee434eSArtem Dergachev
31195f8d361cSGeorge Karpenkov updateExecutedLinesWithDiagnosticPieces(*PD);
312070ec1dd1SGeorge Karpenkov Consumer->HandlePathDiagnostic(std::move(PD));
31219bf9af92STed Kremenek }
31229bf9af92STed Kremenek }
3123fa0734ecSArgyrios Kyrtzidis
3124a5ddd3caSGeorge Karpenkov /// Insert all lines participating in the function signature \p Signature
3125a5ddd3caSGeorge Karpenkov /// into \p ExecutedLines.
populateExecutedLinesWithFunctionSignature(const Decl * Signature,const SourceManager & SM,FilesToLineNumsMap & ExecutedLines)3126a5ddd3caSGeorge Karpenkov static void populateExecutedLinesWithFunctionSignature(
3127fc76d855SKristof Umann const Decl *Signature, const SourceManager &SM,
3128784c60acSGeorge Karpenkov FilesToLineNumsMap &ExecutedLines) {
3129a5ddd3caSGeorge Karpenkov SourceRange SignatureSourceRange;
3130a5ddd3caSGeorge Karpenkov const Stmt* Body = Signature->getBody();
31316a58efdfSEugene Zelenko if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
3132a5ddd3caSGeorge Karpenkov SignatureSourceRange = FD->getSourceRange();
31336a58efdfSEugene Zelenko } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
3134a5ddd3caSGeorge Karpenkov SignatureSourceRange = OD->getSourceRange();
3135a5ddd3caSGeorge Karpenkov } else {
3136a5ddd3caSGeorge Karpenkov return;
3137a5ddd3caSGeorge Karpenkov }
3138a5ddd3caSGeorge Karpenkov SourceLocation Start = SignatureSourceRange.getBegin();
3139a5ddd3caSGeorge Karpenkov SourceLocation End = Body ? Body->getSourceRange().getBegin()
3140a5ddd3caSGeorge Karpenkov : SignatureSourceRange.getEnd();
314155e3d1ecSGeorge Karpenkov if (!Start.isValid() || !End.isValid())
314255e3d1ecSGeorge Karpenkov return;
3143a5ddd3caSGeorge Karpenkov unsigned StartLine = SM.getExpansionLineNumber(Start);
3144a5ddd3caSGeorge Karpenkov unsigned EndLine = SM.getExpansionLineNumber(End);
3145a5ddd3caSGeorge Karpenkov
3146a5ddd3caSGeorge Karpenkov FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
3147a5ddd3caSGeorge Karpenkov for (unsigned Line = StartLine; Line <= EndLine; Line++)
3148784c60acSGeorge Karpenkov ExecutedLines[FID].insert(Line);
3149a5ddd3caSGeorge Karpenkov }
3150a5ddd3caSGeorge Karpenkov
populateExecutedLinesWithStmt(const Stmt * S,const SourceManager & SM,FilesToLineNumsMap & ExecutedLines)315180e4ba24SGeorge Karpenkov static void populateExecutedLinesWithStmt(
3152fc76d855SKristof Umann const Stmt *S, const SourceManager &SM,
3153784c60acSGeorge Karpenkov FilesToLineNumsMap &ExecutedLines) {
315480e4ba24SGeorge Karpenkov SourceLocation Loc = S->getSourceRange().getBegin();
315555e3d1ecSGeorge Karpenkov if (!Loc.isValid())
315655e3d1ecSGeorge Karpenkov return;
315780e4ba24SGeorge Karpenkov SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
315880e4ba24SGeorge Karpenkov FileID FID = SM.getFileID(ExpansionLoc);
315980e4ba24SGeorge Karpenkov unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
3160784c60acSGeorge Karpenkov ExecutedLines[FID].insert(LineNo);
316180e4ba24SGeorge Karpenkov }
316280e4ba24SGeorge Karpenkov
3163a5ddd3caSGeorge Karpenkov /// \return all executed lines including function signatures on the path
3164a5ddd3caSGeorge Karpenkov /// starting from \p N.
3165a5ddd3caSGeorge Karpenkov static std::unique_ptr<FilesToLineNumsMap>
findExecutedLines(const SourceManager & SM,const ExplodedNode * N)3166fc76d855SKristof Umann findExecutedLines(const SourceManager &SM, const ExplodedNode *N) {
31672b3d49b6SJonas Devlieghere auto ExecutedLines = std::make_unique<FilesToLineNumsMap>();
3168a5ddd3caSGeorge Karpenkov
3169a5ddd3caSGeorge Karpenkov while (N) {
3170a5ddd3caSGeorge Karpenkov if (N->getFirstPred() == nullptr) {
3171a5ddd3caSGeorge Karpenkov // First node: show signature of the entrance point.
3172a5ddd3caSGeorge Karpenkov const Decl *D = N->getLocationContext()->getDecl();
3173784c60acSGeorge Karpenkov populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
3174a5ddd3caSGeorge Karpenkov } else if (auto CE = N->getLocationAs<CallEnter>()) {
3175a5ddd3caSGeorge Karpenkov // Inlined function: show signature.
3176a5ddd3caSGeorge Karpenkov const Decl* D = CE->getCalleeContext()->getDecl();
3177784c60acSGeorge Karpenkov populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
31786b85f8e9SArtem Dergachev } else if (const Stmt *S = N->getStmtForDiagnostics()) {
3179784c60acSGeorge Karpenkov populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
3180a5ddd3caSGeorge Karpenkov
318180e4ba24SGeorge Karpenkov // Show extra context for some parent kinds.
318280e4ba24SGeorge Karpenkov const Stmt *P = N->getParentMap().getParent(S);
318380e4ba24SGeorge Karpenkov
318480e4ba24SGeorge Karpenkov // The path exploration can die before the node with the associated
318580e4ba24SGeorge Karpenkov // return statement is generated, but we do want to show the whole
318680e4ba24SGeorge Karpenkov // return.
31876a58efdfSEugene Zelenko if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
3188784c60acSGeorge Karpenkov populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
318980e4ba24SGeorge Karpenkov P = N->getParentMap().getParent(RS);
319080e4ba24SGeorge Karpenkov }
319180e4ba24SGeorge Karpenkov
319216be17adSBalazs Benics if (isa_and_nonnull<SwitchCase, LabelStmt>(P))
3193784c60acSGeorge Karpenkov populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
3194a5ddd3caSGeorge Karpenkov }
3195a5ddd3caSGeorge Karpenkov
3196a5ddd3caSGeorge Karpenkov N = N->getFirstPred();
3197a5ddd3caSGeorge Karpenkov }
3198a5ddd3caSGeorge Karpenkov return ExecutedLines;
3199a5ddd3caSGeorge Karpenkov }
3200a5ddd3caSGeorge Karpenkov
320170ec1dd1SGeorge Karpenkov std::unique_ptr<DiagnosticForConsumerMapTy>
generateDiagnosticForConsumerMap(BugReport * exampleReport,ArrayRef<PathDiagnosticConsumer * > consumers,ArrayRef<BugReport * > bugReports)320270ec1dd1SGeorge Karpenkov BugReporter::generateDiagnosticForConsumerMap(
32032f169e7cSArtem Dergachev BugReport *exampleReport, ArrayRef<PathDiagnosticConsumer *> consumers,
32049bf9af92STed Kremenek ArrayRef<BugReport *> bugReports) {
32052f169e7cSArtem Dergachev auto *basicReport = cast<BasicBugReport>(exampleReport);
32062b3d49b6SJonas Devlieghere auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
320770ec1dd1SGeorge Karpenkov for (auto *Consumer : consumers)
32082f169e7cSArtem Dergachev (*Out)[Consumer] = generateDiagnosticForBasicReport(basicReport);
320970ec1dd1SGeorge Karpenkov return Out;
321070ec1dd1SGeorge Karpenkov }
3211fa0734ecSArgyrios Kyrtzidis
32122bce23a4SArtem Dergachev static PathDiagnosticCallPiece *
getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece * CP,const SourceManager & SMgr)32132bce23a4SArtem Dergachev getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
32142bce23a4SArtem Dergachev const SourceManager &SMgr) {
32152bce23a4SArtem Dergachev SourceLocation CallLoc = CP->callEnter.asLocation();
32162bce23a4SArtem Dergachev
32172bce23a4SArtem Dergachev // If the call is within a macro, don't do anything (for now).
32182bce23a4SArtem Dergachev if (CallLoc.isMacroID())
32192bce23a4SArtem Dergachev return nullptr;
32202bce23a4SArtem Dergachev
32212bce23a4SArtem Dergachev assert(AnalysisManager::isInCodeFile(CallLoc, SMgr) &&
32222bce23a4SArtem Dergachev "The call piece should not be in a header file.");
32232bce23a4SArtem Dergachev
32242bce23a4SArtem Dergachev // Check if CP represents a path through a function outside of the main file.
32252bce23a4SArtem Dergachev if (!AnalysisManager::isInCodeFile(CP->callEnterWithin.asLocation(), SMgr))
32262bce23a4SArtem Dergachev return CP;
32272bce23a4SArtem Dergachev
32282bce23a4SArtem Dergachev const PathPieces &Path = CP->path;
32292bce23a4SArtem Dergachev if (Path.empty())
32302bce23a4SArtem Dergachev return nullptr;
32312bce23a4SArtem Dergachev
32322bce23a4SArtem Dergachev // Check if the last piece in the callee path is a call to a function outside
32332bce23a4SArtem Dergachev // of the main file.
32342bce23a4SArtem Dergachev if (auto *CPInner = dyn_cast<PathDiagnosticCallPiece>(Path.back().get()))
32352bce23a4SArtem Dergachev return getFirstStackedCallToHeaderFile(CPInner, SMgr);
32362bce23a4SArtem Dergachev
32372bce23a4SArtem Dergachev // Otherwise, the last piece is in the main file.
32382bce23a4SArtem Dergachev return nullptr;
32392bce23a4SArtem Dergachev }
32402bce23a4SArtem Dergachev
resetDiagnosticLocationToMainFile(PathDiagnostic & PD)32412bce23a4SArtem Dergachev static void resetDiagnosticLocationToMainFile(PathDiagnostic &PD) {
32422bce23a4SArtem Dergachev if (PD.path.empty())
32432bce23a4SArtem Dergachev return;
32442bce23a4SArtem Dergachev
32452bce23a4SArtem Dergachev PathDiagnosticPiece *LastP = PD.path.back().get();
32462bce23a4SArtem Dergachev assert(LastP);
32472bce23a4SArtem Dergachev const SourceManager &SMgr = LastP->getLocation().getManager();
32482bce23a4SArtem Dergachev
32492bce23a4SArtem Dergachev // We only need to check if the report ends inside headers, if the last piece
32502bce23a4SArtem Dergachev // is a call piece.
32512bce23a4SArtem Dergachev if (auto *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
32522bce23a4SArtem Dergachev CP = getFirstStackedCallToHeaderFile(CP, SMgr);
32532bce23a4SArtem Dergachev if (CP) {
32542bce23a4SArtem Dergachev // Mark the piece.
32552bce23a4SArtem Dergachev CP->setAsLastInMainSourceFile();
32562bce23a4SArtem Dergachev
32572bce23a4SArtem Dergachev // Update the path diagnostic message.
32582bce23a4SArtem Dergachev const auto *ND = dyn_cast<NamedDecl>(CP->getCallee());
32592bce23a4SArtem Dergachev if (ND) {
32602bce23a4SArtem Dergachev SmallString<200> buf;
32612bce23a4SArtem Dergachev llvm::raw_svector_ostream os(buf);
32622bce23a4SArtem Dergachev os << " (within a call to '" << ND->getDeclName() << "')";
32632bce23a4SArtem Dergachev PD.appendToDesc(os.str());
32642bce23a4SArtem Dergachev }
32652bce23a4SArtem Dergachev
32662bce23a4SArtem Dergachev // Reset the report containing declaration and location.
32672bce23a4SArtem Dergachev PD.setDeclWithIssue(CP->getCaller());
32682bce23a4SArtem Dergachev PD.setLocation(CP->getLocation());
32692bce23a4SArtem Dergachev
32702bce23a4SArtem Dergachev return;
32712bce23a4SArtem Dergachev }
32722bce23a4SArtem Dergachev }
32732bce23a4SArtem Dergachev }
32742bce23a4SArtem Dergachev
32752bce23a4SArtem Dergachev
32762bce23a4SArtem Dergachev
32772f169e7cSArtem Dergachev std::unique_ptr<DiagnosticForConsumerMapTy>
generateDiagnosticForConsumerMap(BugReport * exampleReport,ArrayRef<PathDiagnosticConsumer * > consumers,ArrayRef<BugReport * > bugReports)32782f169e7cSArtem Dergachev PathSensitiveBugReporter::generateDiagnosticForConsumerMap(
32792f169e7cSArtem Dergachev BugReport *exampleReport, ArrayRef<PathDiagnosticConsumer *> consumers,
32802f169e7cSArtem Dergachev ArrayRef<BugReport *> bugReports) {
32812f169e7cSArtem Dergachev std::vector<BasicBugReport *> BasicBugReports;
32822f169e7cSArtem Dergachev std::vector<PathSensitiveBugReport *> PathSensitiveBugReports;
32832f169e7cSArtem Dergachev if (isa<BasicBugReport>(exampleReport))
32842f169e7cSArtem Dergachev return BugReporter::generateDiagnosticForConsumerMap(exampleReport,
32852f169e7cSArtem Dergachev consumers, bugReports);
32862f169e7cSArtem Dergachev
328770ec1dd1SGeorge Karpenkov // Generate the full path sensitive diagnostic, using the generation scheme
3288fa92f0f2SJordan Rose // specified by the PathDiagnosticConsumer. Note that we have to generate
3289fa92f0f2SJordan Rose // path diagnostics even for consumers which do not support paths, because
3290fa92f0f2SJordan Rose // the BugReporterVisitors may mark this bug as a false positive.
3291b1991c5fSArtem Dergachev assert(!bugReports.empty());
3292704b4fbbSCraig Topper MaxBugClassSize.updateMax(bugReports.size());
32932f169e7cSArtem Dergachev
32942f169e7cSArtem Dergachev // Avoid copying the whole array because there may be a lot of reports.
32952f169e7cSArtem Dergachev ArrayRef<PathSensitiveBugReport *> convertedArrayOfReports(
32962f169e7cSArtem Dergachev reinterpret_cast<PathSensitiveBugReport *const *>(&*bugReports.begin()),
32972f169e7cSArtem Dergachev reinterpret_cast<PathSensitiveBugReport *const *>(&*bugReports.end()));
32982f169e7cSArtem Dergachev std::unique_ptr<DiagnosticForConsumerMapTy> Out = generatePathDiagnostics(
32992f169e7cSArtem Dergachev consumers, convertedArrayOfReports);
3300b1991c5fSArtem Dergachev
330170ec1dd1SGeorge Karpenkov if (Out->empty())
330270ec1dd1SGeorge Karpenkov return Out;
33039bf9af92STed Kremenek
3304704b4fbbSCraig Topper MaxValidBugClassSize.updateMax(bugReports.size());
3305a45fc811SJordan Rose
3306c5e2eca0SAnna Zaks // Examine the report and see if the last piece is in a header. Reset the
3307c5e2eca0SAnna Zaks // report location to the last piece in the main source file.
3308fc76d855SKristof Umann const AnalyzerOptions &Opts = getAnalyzerOptions();
330970ec1dd1SGeorge Karpenkov for (auto const &P : *Out)
3310549f9cd4SKristof Umann if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
33112bce23a4SArtem Dergachev resetDiagnosticLocationToMainFile(*P.second);
3312c5e2eca0SAnna Zaks
331370ec1dd1SGeorge Karpenkov return Out;
3314fa0734ecSArgyrios Kyrtzidis }
3315fa0734ecSArgyrios Kyrtzidis
EmitBasicReport(const Decl * DeclWithIssue,const CheckerBase * Checker,StringRef Name,StringRef Category,StringRef Str,PathDiagnosticLocation Loc,ArrayRef<SourceRange> Ranges,ArrayRef<FixItHint> Fixits)33165a10f08bSTed Kremenek void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
33176cee434eSArtem Dergachev const CheckerBase *Checker, StringRef Name,
33186cee434eSArtem Dergachev StringRef Category, StringRef Str,
33196cee434eSArtem Dergachev PathDiagnosticLocation Loc,
33206cee434eSArtem Dergachev ArrayRef<SourceRange> Ranges,
33216cee434eSArtem Dergachev ArrayRef<FixItHint> Fixits) {
332272649423SKristof Umann EmitBasicReport(DeclWithIssue, Checker->getCheckerName(), Name, Category, Str,
33236cee434eSArtem Dergachev Loc, Ranges, Fixits);
33244aca9b1cSAlexander Kornienko }
33256a58efdfSEugene Zelenko
EmitBasicReport(const Decl * DeclWithIssue,CheckerNameRef CheckName,StringRef name,StringRef category,StringRef str,PathDiagnosticLocation Loc,ArrayRef<SourceRange> Ranges,ArrayRef<FixItHint> Fixits)33264aca9b1cSAlexander Kornienko void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
332772649423SKristof Umann CheckerNameRef CheckName,
33284aca9b1cSAlexander Kornienko StringRef name, StringRef category,
3329c29bed39SAnna Zaks StringRef str, PathDiagnosticLocation Loc,
33306cee434eSArtem Dergachev ArrayRef<SourceRange> Ranges,
33316cee434eSArtem Dergachev ArrayRef<FixItHint> Fixits) {
3332a1540db6SArgyrios Kyrtzidis // 'BT' is owned by BugReporter.
33334aca9b1cSAlexander Kornienko BugType *BT = getBugTypeForName(CheckName, name, category);
33342f169e7cSArtem Dergachev auto R = std::make_unique<BasicBugReport>(*BT, str, Loc);
33355a10f08bSTed Kremenek R->setDeclWithIssue(DeclWithIssue);
33366cee434eSArtem Dergachev for (const auto &SR : Ranges)
33376cee434eSArtem Dergachev R->addRange(SR);
33386cee434eSArtem Dergachev for (const auto &FH : Fixits)
33396cee434eSArtem Dergachev R->addFixItHint(FH);
33408d3a7a56SAaron Ballman emitReport(std::move(R));
3341fa0734ecSArgyrios Kyrtzidis }
3342a1540db6SArgyrios Kyrtzidis
getBugTypeForName(CheckerNameRef CheckName,StringRef name,StringRef category)334372649423SKristof Umann BugType *BugReporter::getBugTypeForName(CheckerNameRef CheckName,
334472649423SKristof Umann StringRef name, StringRef category) {
33452c1dd271SDylan Noblesmith SmallString<136> fullDesc;
33464aca9b1cSAlexander Kornienko llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
33474aca9b1cSAlexander Kornienko << ":" << category;
3348cbae0d82SDavid Blaikie std::unique_ptr<BugType> &BT = StrBugTypes[fullDesc];
334913156b68SDavid Blaikie if (!BT)
3350cbae0d82SDavid Blaikie BT = std::make_unique<BugType>(CheckName, name, category);
3351cbae0d82SDavid Blaikie return BT.get();
3352a1540db6SArgyrios Kyrtzidis }
3353