1 //===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines BugReporter, a utility class for generating
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
15 #include "clang/AST/ASTTypeTraits.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/ParentMapContext.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Analysis/AnalysisDeclContext.h"
28 #include "clang/Analysis/CFG.h"
29 #include "clang/Analysis/CFGStmtMap.h"
30 #include "clang/Analysis/PathDiagnostic.h"
31 #include "clang/Analysis/ProgramPoint.h"
32 #include "clang/Basic/LLVM.h"
33 #include "clang/Basic/SourceLocation.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
36 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
37 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
38 #include "clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h"
39 #include "clang/StaticAnalyzer/Core/Checker.h"
40 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
41 #include "clang/StaticAnalyzer/Core/CheckerRegistryData.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/DenseSet.h"
52 #include "llvm/ADT/FoldingSet.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallString.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/iterator_range.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MemoryBuffer.h"
65 #include "llvm/Support/raw_ostream.h"
78 using namespace clang
;
82 #define DEBUG_TYPE "BugReporter"
84 STATISTIC(MaxBugClassSize
,
85 "The maximum number of bug reports in the same equivalence class");
86 STATISTIC(MaxValidBugClassSize
,
87 "The maximum number of bug reports in the same equivalence class "
88 "where at least one report is valid (not suppressed)");
90 STATISTIC(NumTimesReportPassesZ3
, "Number of reports passed Z3");
91 STATISTIC(NumTimesReportRefuted
, "Number of reports refuted by Z3");
92 STATISTIC(NumTimesReportEQClassAborted
,
93 "Number of times a report equivalence class was aborted by the Z3 "
95 STATISTIC(NumTimesReportEQClassWasExhausted
,
96 "Number of times all reports of an equivalence class was refuted");
98 BugReporterVisitor::~BugReporterVisitor() = default;
100 void BugReporterContext::anchor() {}
102 //===----------------------------------------------------------------------===//
103 // PathDiagnosticBuilder and its associated routines and helper objects.
104 //===----------------------------------------------------------------------===//
108 /// A (CallPiece, node assiciated with its CallEnter) pair.
109 using CallWithEntry
=
110 std::pair
<PathDiagnosticCallPiece
*, const ExplodedNode
*>;
111 using CallWithEntryStack
= SmallVector
<CallWithEntry
, 6>;
113 /// Map from each node to the diagnostic pieces visitors emit for them.
114 using VisitorsDiagnosticsTy
=
115 llvm::DenseMap
<const ExplodedNode
*, std::vector
<PathDiagnosticPieceRef
>>;
117 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
118 /// function call it represents.
119 using LocationContextMap
=
120 llvm::DenseMap
<const PathPieces
*, const LocationContext
*>;
122 /// A helper class that contains everything needed to construct a
123 /// PathDiagnostic object. It does no much more then providing convenient
124 /// getters and some well placed asserts for extra security.
125 class PathDiagnosticConstruct
{
126 /// The consumer we're constructing the bug report for.
127 const PathDiagnosticConsumer
*Consumer
;
128 /// Our current position in the bug path, which is owned by
129 /// PathDiagnosticBuilder.
130 const ExplodedNode
*CurrentNode
;
131 /// A mapping from parts of the bug path (for example, a function call, which
132 /// would span backwards from a CallExit to a CallEnter with the nodes in
133 /// between them) with the location contexts it is associated with.
134 LocationContextMap LCM
;
135 const SourceManager
&SM
;
138 /// We keep stack of calls to functions as we're ascending the bug path.
139 /// TODO: PathDiagnostic has a stack doing the same thing, shouldn't we use
141 CallWithEntryStack CallStack
;
142 /// The bug report we're constructing. For ease of use, this field is kept
143 /// public, though some "shortcut" getters are provided for commonly used
144 /// methods of PathDiagnostic.
145 std::unique_ptr
<PathDiagnostic
> PD
;
148 PathDiagnosticConstruct(const PathDiagnosticConsumer
*PDC
,
149 const ExplodedNode
*ErrorNode
,
150 const PathSensitiveBugReport
*R
,
151 const Decl
*AnalysisEntryPoint
);
153 /// \returns the location context associated with the current position in the
155 const LocationContext
*getCurrLocationContext() const {
156 assert(CurrentNode
&& "Already reached the root!");
157 return CurrentNode
->getLocationContext();
160 /// Same as getCurrLocationContext (they should always return the same
161 /// location context), but works after reaching the root of the bug path as
163 const LocationContext
*getLocationContextForActivePath() const {
164 return LCM
.find(&PD
->getActivePath())->getSecond();
167 const ExplodedNode
*getCurrentNode() const { return CurrentNode
; }
169 /// Steps the current node to its predecessor.
170 /// \returns whether we reached the root of the bug path.
171 bool ascendToPrevNode() {
172 CurrentNode
= CurrentNode
->getFirstPred();
173 return static_cast<bool>(CurrentNode
);
176 const ParentMap
&getParentMap() const {
177 return getCurrLocationContext()->getParentMap();
180 const SourceManager
&getSourceManager() const { return SM
; }
182 const Stmt
*getParent(const Stmt
*S
) const {
183 return getParentMap().getParent(S
);
186 void updateLocCtxMap(const PathPieces
*Path
, const LocationContext
*LC
) {
191 const LocationContext
*getLocationContextFor(const PathPieces
*Path
) const {
192 assert(LCM
.count(Path
) &&
193 "Failed to find the context associated with these pieces!");
194 return LCM
.find(Path
)->getSecond();
197 bool isInLocCtxMap(const PathPieces
*Path
) const { return LCM
.count(Path
); }
199 PathPieces
&getActivePath() { return PD
->getActivePath(); }
200 PathPieces
&getMutablePieces() { return PD
->getMutablePieces(); }
202 bool shouldAddPathEdges() const { return Consumer
->shouldAddPathEdges(); }
203 bool shouldAddControlNotes() const {
204 return Consumer
->shouldAddControlNotes();
206 bool shouldGenerateDiagnostics() const {
207 return Consumer
->shouldGenerateDiagnostics();
209 bool supportsLogicalOpControlFlow() const {
210 return Consumer
->supportsLogicalOpControlFlow();
214 /// Contains every contextual information needed for constructing a
215 /// PathDiagnostic object for a given bug report. This class and its fields are
216 /// immutable, and passes a BugReportConstruct object around during the
218 class PathDiagnosticBuilder
: public BugReporterContext
{
219 /// A linear path from the error node to the root.
220 std::unique_ptr
<const ExplodedGraph
> BugPath
;
221 /// The bug report we're describing. Visitors create their diagnostics with
222 /// them being the last entities being able to modify it (for example,
223 /// changing interestingness here would cause inconsistencies as to how this
224 /// file and visitors construct diagnostics), hence its const.
225 const PathSensitiveBugReport
*R
;
226 /// The leaf of the bug path. This isn't the same as the bug reports error
227 /// node, which refers to the *original* graph, not the bug path.
228 const ExplodedNode
*const ErrorNode
;
229 /// The diagnostic pieces visitors emitted, which is expected to be collected
230 /// by the time this builder is constructed.
231 std::unique_ptr
<const VisitorsDiagnosticsTy
> VisitorsDiagnostics
;
234 /// Find a non-invalidated report for a given equivalence class, and returns
235 /// a PathDiagnosticBuilder able to construct bug reports for different
236 /// consumers. Returns std::nullopt if no valid report is found.
237 static std::optional
<PathDiagnosticBuilder
>
238 findValidReport(ArrayRef
<PathSensitiveBugReport
*> &bugReports
,
239 PathSensitiveBugReporter
&Reporter
);
241 PathDiagnosticBuilder(
242 BugReporterContext BRC
, std::unique_ptr
<ExplodedGraph
> BugPath
,
243 PathSensitiveBugReport
*r
, const ExplodedNode
*ErrorNode
,
244 std::unique_ptr
<VisitorsDiagnosticsTy
> VisitorsDiagnostics
);
246 /// This function is responsible for generating diagnostic pieces that are
247 /// *not* provided by bug report visitors.
248 /// These diagnostics may differ depending on the consumer's settings,
249 /// and are therefore constructed separately for each consumer.
251 /// There are two path diagnostics generation modes: with adding edges (used
252 /// for plists) and without (used for HTML and text). When edges are added,
253 /// the path is modified to insert artificially generated edges.
254 /// Otherwise, more detailed diagnostics is emitted for block edges,
255 /// explaining the transitions in words.
256 std::unique_ptr
<PathDiagnostic
>
257 generate(const PathDiagnosticConsumer
*PDC
) const;
260 void updateStackPiecesWithMessage(PathDiagnosticPieceRef P
,
261 const CallWithEntryStack
&CallStack
) const;
262 void generatePathDiagnosticsForNode(PathDiagnosticConstruct
&C
,
263 PathDiagnosticLocation
&PrevLoc
) const;
265 void generateMinimalDiagForBlockEdge(PathDiagnosticConstruct
&C
,
268 PathDiagnosticPieceRef
269 generateDiagForGotoOP(const PathDiagnosticConstruct
&C
, const Stmt
*S
,
270 PathDiagnosticLocation
&Start
) const;
272 PathDiagnosticPieceRef
273 generateDiagForSwitchOP(const PathDiagnosticConstruct
&C
, const CFGBlock
*Dst
,
274 PathDiagnosticLocation
&Start
) const;
276 PathDiagnosticPieceRef
277 generateDiagForBinaryOP(const PathDiagnosticConstruct
&C
, const Stmt
*T
,
278 const CFGBlock
*Src
, const CFGBlock
*DstC
) const;
280 PathDiagnosticLocation
281 ExecutionContinues(const PathDiagnosticConstruct
&C
) const;
283 PathDiagnosticLocation
284 ExecutionContinues(llvm::raw_string_ostream
&os
,
285 const PathDiagnosticConstruct
&C
) const;
287 const PathSensitiveBugReport
*getBugReport() const { return R
; }
292 //===----------------------------------------------------------------------===//
293 // Base implementation of stack hint generators.
294 //===----------------------------------------------------------------------===//
296 StackHintGenerator::~StackHintGenerator() = default;
298 std::string
StackHintGeneratorForSymbol::getMessage(const ExplodedNode
*N
){
300 return getMessageForSymbolNotFound();
302 ProgramPoint P
= N
->getLocation();
303 CallExitEnd CExit
= P
.castAs
<CallExitEnd
>();
305 // FIXME: Use CallEvent to abstract this over all calls.
306 const Stmt
*CallSite
= CExit
.getCalleeContext()->getCallSite();
307 const auto *CE
= dyn_cast_or_null
<CallExpr
>(CallSite
);
311 // Check if one of the parameters are set to the interesting symbol.
312 for (auto [Idx
, ArgExpr
] : llvm::enumerate(CE
->arguments())) {
313 SVal SV
= N
->getSVal(ArgExpr
);
315 // Check if the variable corresponding to the symbol is passed by value.
316 SymbolRef AS
= SV
.getAsLocSymbol();
318 return getMessageForArg(ArgExpr
, Idx
);
321 // Check if the parameter is a pointer to the symbol.
322 if (std::optional
<loc::MemRegionVal
> Reg
= SV
.getAs
<loc::MemRegionVal
>()) {
323 // Do not attempt to dereference void*.
324 if (ArgExpr
->getType()->isVoidPointerType())
326 SVal PSV
= N
->getState()->getSVal(Reg
->getRegion());
327 SymbolRef AS
= PSV
.getAsLocSymbol();
329 return getMessageForArg(ArgExpr
, Idx
);
334 // Check if we are returning the interesting symbol.
335 SVal SV
= N
->getSVal(CE
);
336 SymbolRef RetSym
= SV
.getAsLocSymbol();
338 return getMessageForReturn(CE
);
341 return getMessageForSymbolNotFound();
344 std::string
StackHintGeneratorForSymbol::getMessageForArg(const Expr
*ArgE
,
346 // Printed parameters start at 1, not 0.
349 return (llvm::Twine(Msg
) + " via " + std::to_string(ArgIndex
) +
350 llvm::getOrdinalSuffix(ArgIndex
) + " parameter").str();
353 //===----------------------------------------------------------------------===//
354 // Diagnostic cleanup.
355 //===----------------------------------------------------------------------===//
357 static PathDiagnosticEventPiece
*
358 eventsDescribeSameCondition(PathDiagnosticEventPiece
*X
,
359 PathDiagnosticEventPiece
*Y
) {
360 // Prefer diagnostics that come from ConditionBRVisitor over
361 // those that came from TrackConstraintBRVisitor,
362 // unless the one from ConditionBRVisitor is
363 // its generic fallback diagnostic.
364 const void *tagPreferred
= ConditionBRVisitor::getTag();
365 const void *tagLesser
= TrackConstraintBRVisitor::getTag();
367 if (X
->getLocation() != Y
->getLocation())
370 if (X
->getTag() == tagPreferred
&& Y
->getTag() == tagLesser
)
371 return ConditionBRVisitor::isPieceMessageGeneric(X
) ? Y
: X
;
373 if (Y
->getTag() == tagPreferred
&& X
->getTag() == tagLesser
)
374 return ConditionBRVisitor::isPieceMessageGeneric(Y
) ? X
: Y
;
379 /// An optimization pass over PathPieces that removes redundant diagnostics
380 /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
381 /// BugReporterVisitors use different methods to generate diagnostics, with
382 /// one capable of emitting diagnostics in some cases but not in others. This
383 /// can lead to redundant diagnostic pieces at the same point in a path.
384 static void removeRedundantMsgs(PathPieces
&path
) {
385 unsigned N
= path
.size();
388 // NOTE: this loop intentionally is not using an iterator. Instead, we
389 // are streaming the path and modifying it in place. This is done by
390 // grabbing the front, processing it, and if we decide to keep it append
391 // it to the end of the path. The entire path is processed in this way.
392 for (unsigned i
= 0; i
< N
; ++i
) {
393 auto piece
= std::move(path
.front());
396 switch (piece
->getKind()) {
397 case PathDiagnosticPiece::Call
:
398 removeRedundantMsgs(cast
<PathDiagnosticCallPiece
>(*piece
).path
);
400 case PathDiagnosticPiece::Macro
:
401 removeRedundantMsgs(cast
<PathDiagnosticMacroPiece
>(*piece
).subPieces
);
403 case PathDiagnosticPiece::Event
: {
407 if (auto *nextEvent
=
408 dyn_cast
<PathDiagnosticEventPiece
>(path
.front().get())) {
409 auto *event
= cast
<PathDiagnosticEventPiece
>(piece
.get());
410 // Check to see if we should keep one of the two pieces. If we
411 // come up with a preference, record which piece to keep, and consume
412 // another piece from the path.
413 if (auto *pieceToKeep
=
414 eventsDescribeSameCondition(event
, nextEvent
)) {
415 piece
= std::move(pieceToKeep
== event
? piece
: path
.front());
422 case PathDiagnosticPiece::ControlFlow
:
423 case PathDiagnosticPiece::Note
:
424 case PathDiagnosticPiece::PopUp
:
427 path
.push_back(std::move(piece
));
431 /// Recursively scan through a path and prune out calls and macros pieces
432 /// that aren't needed. Return true if afterwards the path contains
433 /// "interesting stuff" which means it shouldn't be pruned from the parent path.
434 static bool removeUnneededCalls(const PathDiagnosticConstruct
&C
,
436 const PathSensitiveBugReport
*R
,
437 bool IsInteresting
= false) {
438 bool containsSomethingInteresting
= IsInteresting
;
439 const unsigned N
= pieces
.size();
441 for (unsigned i
= 0 ; i
< N
; ++i
) {
442 // Remove the front piece from the path. If it is still something we
443 // want to keep once we are done, we will push it back on the end.
444 auto piece
= std::move(pieces
.front());
447 switch (piece
->getKind()) {
448 case PathDiagnosticPiece::Call
: {
449 auto &call
= cast
<PathDiagnosticCallPiece
>(*piece
);
450 // Check if the location context is interesting.
451 if (!removeUnneededCalls(
453 R
->isInteresting(C
.getLocationContextFor(&call
.path
))))
456 containsSomethingInteresting
= true;
459 case PathDiagnosticPiece::Macro
: {
460 auto ¯o
= cast
<PathDiagnosticMacroPiece
>(*piece
);
461 if (!removeUnneededCalls(C
, macro
.subPieces
, R
, IsInteresting
))
463 containsSomethingInteresting
= true;
466 case PathDiagnosticPiece::Event
: {
467 auto &event
= cast
<PathDiagnosticEventPiece
>(*piece
);
469 // We never throw away an event, but we do throw it away wholesale
470 // as part of a path if we throw the entire path away.
471 containsSomethingInteresting
|= !event
.isPrunable();
474 case PathDiagnosticPiece::ControlFlow
:
475 case PathDiagnosticPiece::Note
:
476 case PathDiagnosticPiece::PopUp
:
480 pieces
.push_back(std::move(piece
));
483 return containsSomethingInteresting
;
486 /// Same logic as above to remove extra pieces.
487 static void removePopUpNotes(PathPieces
&Path
) {
488 for (unsigned int i
= 0; i
< Path
.size(); ++i
) {
489 auto Piece
= std::move(Path
.front());
491 if (!isa
<PathDiagnosticPopUpPiece
>(*Piece
))
492 Path
.push_back(std::move(Piece
));
496 /// Returns true if the given decl has been implicitly given a body, either by
497 /// the analyzer or by the compiler proper.
498 static bool hasImplicitBody(const Decl
*D
) {
500 return D
->isImplicit() || !D
->hasBody();
503 /// Recursively scan through a path and make sure that all call pieces have
506 adjustCallLocations(PathPieces
&Pieces
,
507 PathDiagnosticLocation
*LastCallLocation
= nullptr) {
508 for (const auto &I
: Pieces
) {
509 auto *Call
= dyn_cast
<PathDiagnosticCallPiece
>(I
.get());
514 if (LastCallLocation
) {
515 bool CallerIsImplicit
= hasImplicitBody(Call
->getCaller());
516 if (CallerIsImplicit
|| !Call
->callEnter
.asLocation().isValid())
517 Call
->callEnter
= *LastCallLocation
;
518 if (CallerIsImplicit
|| !Call
->callReturn
.asLocation().isValid())
519 Call
->callReturn
= *LastCallLocation
;
522 // Recursively clean out the subclass. Keep this call around if
523 // it contains any informative diagnostics.
524 PathDiagnosticLocation
*ThisCallLocation
;
525 if (Call
->callEnterWithin
.asLocation().isValid() &&
526 !hasImplicitBody(Call
->getCallee()))
527 ThisCallLocation
= &Call
->callEnterWithin
;
529 ThisCallLocation
= &Call
->callEnter
;
531 assert(ThisCallLocation
&& "Outermost call has an invalid location");
532 adjustCallLocations(Call
->path
, ThisCallLocation
);
536 /// Remove edges in and out of C++ default initializer expressions. These are
537 /// for fields that have in-class initializers, as opposed to being initialized
538 /// explicitly in a constructor or braced list.
539 static void removeEdgesToDefaultInitializers(PathPieces
&Pieces
) {
540 for (PathPieces::iterator I
= Pieces
.begin(), E
= Pieces
.end(); I
!= E
;) {
541 if (auto *C
= dyn_cast
<PathDiagnosticCallPiece
>(I
->get()))
542 removeEdgesToDefaultInitializers(C
->path
);
544 if (auto *M
= dyn_cast
<PathDiagnosticMacroPiece
>(I
->get()))
545 removeEdgesToDefaultInitializers(M
->subPieces
);
547 if (auto *CF
= dyn_cast
<PathDiagnosticControlFlowPiece
>(I
->get())) {
548 const Stmt
*Start
= CF
->getStartLocation().asStmt();
549 const Stmt
*End
= CF
->getEndLocation().asStmt();
550 if (isa_and_nonnull
<CXXDefaultInitExpr
>(Start
)) {
553 } else if (isa_and_nonnull
<CXXDefaultInitExpr
>(End
)) {
554 PathPieces::iterator Next
= std::next(I
);
557 dyn_cast
<PathDiagnosticControlFlowPiece
>(Next
->get())) {
558 NextCF
->setStartLocation(CF
->getStartLocation());
570 /// Remove all pieces with invalid locations as these cannot be serialized.
571 /// We might have pieces with invalid locations as a result of inlining Body
572 /// Farm generated functions.
573 static void removePiecesWithInvalidLocations(PathPieces
&Pieces
) {
574 for (PathPieces::iterator I
= Pieces
.begin(), E
= Pieces
.end(); I
!= E
;) {
575 if (auto *C
= dyn_cast
<PathDiagnosticCallPiece
>(I
->get()))
576 removePiecesWithInvalidLocations(C
->path
);
578 if (auto *M
= dyn_cast
<PathDiagnosticMacroPiece
>(I
->get()))
579 removePiecesWithInvalidLocations(M
->subPieces
);
581 if (!(*I
)->getLocation().isValid() ||
582 !(*I
)->getLocation().asLocation().isValid()) {
590 PathDiagnosticLocation
PathDiagnosticBuilder::ExecutionContinues(
591 const PathDiagnosticConstruct
&C
) const {
592 if (const Stmt
*S
= C
.getCurrentNode()->getNextStmtForDiagnostics())
593 return PathDiagnosticLocation(S
, getSourceManager(),
594 C
.getCurrLocationContext());
596 return PathDiagnosticLocation::createDeclEnd(C
.getCurrLocationContext(),
600 PathDiagnosticLocation
PathDiagnosticBuilder::ExecutionContinues(
601 llvm::raw_string_ostream
&os
, const PathDiagnosticConstruct
&C
) const {
602 // Slow, but probably doesn't matter.
603 if (os
.str().empty())
606 const PathDiagnosticLocation
&Loc
= ExecutionContinues(C
);
609 os
<< "Execution continues on line "
610 << getSourceManager().getExpansionLineNumber(Loc
.asLocation())
613 os
<< "Execution jumps to the end of the ";
614 const Decl
*D
= C
.getCurrLocationContext()->getDecl();
615 if (isa
<ObjCMethodDecl
>(D
))
617 else if (isa
<FunctionDecl
>(D
))
620 assert(isa
<BlockDecl
>(D
));
621 os
<< "anonymous block";
629 static const Stmt
*getEnclosingParent(const Stmt
*S
, const ParentMap
&PM
) {
630 if (isa
<Expr
>(S
) && PM
.isConsumedExpr(cast
<Expr
>(S
)))
631 return PM
.getParentIgnoreParens(S
);
633 const Stmt
*Parent
= PM
.getParentIgnoreParens(S
);
637 switch (Parent
->getStmtClass()) {
638 case Stmt::ForStmtClass
:
639 case Stmt::DoStmtClass
:
640 case Stmt::WhileStmtClass
:
641 case Stmt::ObjCForCollectionStmtClass
:
642 case Stmt::CXXForRangeStmtClass
:
651 static PathDiagnosticLocation
652 getEnclosingStmtLocation(const Stmt
*S
, const LocationContext
*LC
,
653 bool allowNestedContexts
= false) {
657 const SourceManager
&SMgr
= LC
->getDecl()->getASTContext().getSourceManager();
659 while (const Stmt
*Parent
= getEnclosingParent(S
, LC
->getParentMap())) {
660 switch (Parent
->getStmtClass()) {
661 case Stmt::BinaryOperatorClass
: {
662 const auto *B
= cast
<BinaryOperator
>(Parent
);
663 if (B
->isLogicalOp())
664 return PathDiagnosticLocation(allowNestedContexts
? B
: S
, SMgr
, LC
);
667 case Stmt::CompoundStmtClass
:
668 case Stmt::StmtExprClass
:
669 return PathDiagnosticLocation(S
, SMgr
, LC
);
670 case Stmt::ChooseExprClass
:
671 // Similar to '?' if we are referring to condition, just have the edge
672 // point to the entire choose expression.
673 if (allowNestedContexts
|| cast
<ChooseExpr
>(Parent
)->getCond() == S
)
674 return PathDiagnosticLocation(Parent
, SMgr
, LC
);
676 return PathDiagnosticLocation(S
, SMgr
, LC
);
677 case Stmt::BinaryConditionalOperatorClass
:
678 case Stmt::ConditionalOperatorClass
:
679 // For '?', if we are referring to condition, just have the edge point
680 // to the entire '?' expression.
681 if (allowNestedContexts
||
682 cast
<AbstractConditionalOperator
>(Parent
)->getCond() == S
)
683 return PathDiagnosticLocation(Parent
, SMgr
, LC
);
685 return PathDiagnosticLocation(S
, SMgr
, LC
);
686 case Stmt::CXXForRangeStmtClass
:
687 if (cast
<CXXForRangeStmt
>(Parent
)->getBody() == S
)
688 return PathDiagnosticLocation(S
, SMgr
, LC
);
690 case Stmt::DoStmtClass
:
691 return PathDiagnosticLocation(S
, SMgr
, LC
);
692 case Stmt::ForStmtClass
:
693 if (cast
<ForStmt
>(Parent
)->getBody() == S
)
694 return PathDiagnosticLocation(S
, SMgr
, LC
);
696 case Stmt::IfStmtClass
:
697 if (cast
<IfStmt
>(Parent
)->getCond() != S
)
698 return PathDiagnosticLocation(S
, SMgr
, LC
);
700 case Stmt::ObjCForCollectionStmtClass
:
701 if (cast
<ObjCForCollectionStmt
>(Parent
)->getBody() == S
)
702 return PathDiagnosticLocation(S
, SMgr
, LC
);
704 case Stmt::WhileStmtClass
:
705 if (cast
<WhileStmt
>(Parent
)->getCond() != S
)
706 return PathDiagnosticLocation(S
, SMgr
, LC
);
715 assert(S
&& "Cannot have null Stmt for PathDiagnosticLocation");
717 return PathDiagnosticLocation(S
, SMgr
, LC
);
720 //===----------------------------------------------------------------------===//
721 // "Minimal" path diagnostic generation algorithm.
722 //===----------------------------------------------------------------------===//
724 /// If the piece contains a special message, add it to all the call pieces on
725 /// the active stack. For example, my_malloc allocated memory, so MallocChecker
726 /// will construct an event at the call to malloc(), and add a stack hint that
727 /// an allocated memory was returned. We'll use this hint to construct a message
728 /// when returning from the call to my_malloc
730 /// void *my_malloc() { return malloc(sizeof(int)); }
732 /// void *ptr = my_malloc(); // returned allocated memory
734 void PathDiagnosticBuilder::updateStackPiecesWithMessage(
735 PathDiagnosticPieceRef P
, const CallWithEntryStack
&CallStack
) const {
736 if (R
->hasCallStackHint(P
))
737 for (const auto &I
: CallStack
) {
738 PathDiagnosticCallPiece
*CP
= I
.first
;
739 const ExplodedNode
*N
= I
.second
;
740 std::string stackMsg
= R
->getCallStackMessage(P
, N
);
742 // The last message on the path to final bug is the most important
743 // one. Since we traverse the path backwards, do not add the message
744 // if one has been previously added.
745 if (!CP
->hasCallStackMessage())
746 CP
->setCallStackMessage(stackMsg
);
750 static void CompactMacroExpandedPieces(PathPieces
&path
,
751 const SourceManager
& SM
);
753 PathDiagnosticPieceRef
PathDiagnosticBuilder::generateDiagForSwitchOP(
754 const PathDiagnosticConstruct
&C
, const CFGBlock
*Dst
,
755 PathDiagnosticLocation
&Start
) const {
757 const SourceManager
&SM
= getSourceManager();
758 // Figure out what case arm we took.
760 llvm::raw_string_ostream
os(sbuf
);
761 PathDiagnosticLocation End
;
763 if (const Stmt
*S
= Dst
->getLabel()) {
764 End
= PathDiagnosticLocation(S
, SM
, C
.getCurrLocationContext());
766 switch (S
->getStmtClass()) {
768 os
<< "No cases match in the switch statement. "
769 "Control jumps to line "
770 << End
.asLocation().getExpansionLineNumber();
772 case Stmt::DefaultStmtClass
:
773 os
<< "Control jumps to the 'default' case at line "
774 << End
.asLocation().getExpansionLineNumber();
777 case Stmt::CaseStmtClass
: {
778 os
<< "Control jumps to 'case ";
779 const auto *Case
= cast
<CaseStmt
>(S
);
780 const Expr
*LHS
= Case
->getLHS()->IgnoreParenImpCasts();
782 // Determine if it is an enum.
783 bool GetRawInt
= true;
785 if (const auto *DR
= dyn_cast
<DeclRefExpr
>(LHS
)) {
786 // FIXME: Maybe this should be an assertion. Are there cases
787 // were it is not an EnumConstantDecl?
788 const auto *D
= dyn_cast
<EnumConstantDecl
>(DR
->getDecl());
797 os
<< LHS
->EvaluateKnownConstInt(getASTContext());
799 os
<< ":' at line " << End
.asLocation().getExpansionLineNumber();
804 os
<< "'Default' branch taken. ";
805 End
= ExecutionContinues(os
, C
);
807 return std::make_shared
<PathDiagnosticControlFlowPiece
>(Start
, End
, sbuf
);
810 PathDiagnosticPieceRef
PathDiagnosticBuilder::generateDiagForGotoOP(
811 const PathDiagnosticConstruct
&C
, const Stmt
*S
,
812 PathDiagnosticLocation
&Start
) const {
814 llvm::raw_string_ostream
os(sbuf
);
815 const PathDiagnosticLocation
&End
=
816 getEnclosingStmtLocation(S
, C
.getCurrLocationContext());
817 os
<< "Control jumps to line " << End
.asLocation().getExpansionLineNumber();
818 return std::make_shared
<PathDiagnosticControlFlowPiece
>(Start
, End
, sbuf
);
821 PathDiagnosticPieceRef
PathDiagnosticBuilder::generateDiagForBinaryOP(
822 const PathDiagnosticConstruct
&C
, const Stmt
*T
, const CFGBlock
*Src
,
823 const CFGBlock
*Dst
) const {
825 const SourceManager
&SM
= getSourceManager();
827 const auto *B
= cast
<BinaryOperator
>(T
);
829 llvm::raw_string_ostream
os(sbuf
);
830 os
<< "Left side of '";
831 PathDiagnosticLocation Start
, End
;
833 if (B
->getOpcode() == BO_LAnd
) {
837 if (*(Src
->succ_begin() + 1) == Dst
) {
839 End
= PathDiagnosticLocation(B
->getLHS(), SM
, C
.getCurrLocationContext());
841 PathDiagnosticLocation::createOperatorLoc(B
, SM
);
845 PathDiagnosticLocation(B
->getLHS(), SM
, C
.getCurrLocationContext());
846 End
= ExecutionContinues(C
);
849 assert(B
->getOpcode() == BO_LOr
);
853 if (*(Src
->succ_begin() + 1) == Dst
) {
856 PathDiagnosticLocation(B
->getLHS(), SM
, C
.getCurrLocationContext());
857 End
= ExecutionContinues(C
);
860 End
= PathDiagnosticLocation(B
->getLHS(), SM
, C
.getCurrLocationContext());
862 PathDiagnosticLocation::createOperatorLoc(B
, SM
);
865 return std::make_shared
<PathDiagnosticControlFlowPiece
>(Start
, End
, sbuf
);
868 void PathDiagnosticBuilder::generateMinimalDiagForBlockEdge(
869 PathDiagnosticConstruct
&C
, BlockEdge BE
) const {
870 const SourceManager
&SM
= getSourceManager();
871 const LocationContext
*LC
= C
.getCurrLocationContext();
872 const CFGBlock
*Src
= BE
.getSrc();
873 const CFGBlock
*Dst
= BE
.getDst();
874 const Stmt
*T
= Src
->getTerminatorStmt();
878 auto Start
= PathDiagnosticLocation::createBegin(T
, SM
, LC
);
879 switch (T
->getStmtClass()) {
883 case Stmt::GotoStmtClass
:
884 case Stmt::IndirectGotoStmtClass
: {
885 if (const Stmt
*S
= C
.getCurrentNode()->getNextStmtForDiagnostics())
886 C
.getActivePath().push_front(generateDiagForGotoOP(C
, S
, Start
));
890 case Stmt::SwitchStmtClass
: {
891 C
.getActivePath().push_front(generateDiagForSwitchOP(C
, Dst
, Start
));
895 case Stmt::BreakStmtClass
:
896 case Stmt::ContinueStmtClass
: {
898 llvm::raw_string_ostream
os(sbuf
);
899 PathDiagnosticLocation End
= ExecutionContinues(os
, C
);
900 C
.getActivePath().push_front(
901 std::make_shared
<PathDiagnosticControlFlowPiece
>(Start
, End
, sbuf
));
905 // Determine control-flow for ternary '?'.
906 case Stmt::BinaryConditionalOperatorClass
:
907 case Stmt::ConditionalOperatorClass
: {
909 llvm::raw_string_ostream
os(sbuf
);
910 os
<< "'?' condition is ";
912 if (*(Src
->succ_begin() + 1) == Dst
)
917 PathDiagnosticLocation End
= ExecutionContinues(C
);
919 if (const Stmt
*S
= End
.asStmt())
920 End
= getEnclosingStmtLocation(S
, C
.getCurrLocationContext());
922 C
.getActivePath().push_front(
923 std::make_shared
<PathDiagnosticControlFlowPiece
>(Start
, End
, sbuf
));
927 // Determine control-flow for short-circuited '&&' and '||'.
928 case Stmt::BinaryOperatorClass
: {
929 if (!C
.supportsLogicalOpControlFlow())
932 C
.getActivePath().push_front(generateDiagForBinaryOP(C
, T
, Src
, Dst
));
936 case Stmt::DoStmtClass
:
937 if (*(Src
->succ_begin()) == Dst
) {
939 llvm::raw_string_ostream
os(sbuf
);
941 os
<< "Loop condition is true. ";
942 PathDiagnosticLocation End
= ExecutionContinues(os
, C
);
944 if (const Stmt
*S
= End
.asStmt())
945 End
= getEnclosingStmtLocation(S
, C
.getCurrLocationContext());
947 C
.getActivePath().push_front(
948 std::make_shared
<PathDiagnosticControlFlowPiece
>(Start
, End
, sbuf
));
950 PathDiagnosticLocation End
= ExecutionContinues(C
);
952 if (const Stmt
*S
= End
.asStmt())
953 End
= getEnclosingStmtLocation(S
, C
.getCurrLocationContext());
955 C
.getActivePath().push_front(
956 std::make_shared
<PathDiagnosticControlFlowPiece
>(
957 Start
, End
, "Loop condition is false. Exiting loop"));
961 case Stmt::WhileStmtClass
:
962 case Stmt::ForStmtClass
:
963 if (*(Src
->succ_begin() + 1) == Dst
) {
965 llvm::raw_string_ostream
os(sbuf
);
967 os
<< "Loop condition is false. ";
968 PathDiagnosticLocation End
= ExecutionContinues(os
, C
);
969 if (const Stmt
*S
= End
.asStmt())
970 End
= getEnclosingStmtLocation(S
, C
.getCurrLocationContext());
972 C
.getActivePath().push_front(
973 std::make_shared
<PathDiagnosticControlFlowPiece
>(Start
, End
, sbuf
));
975 PathDiagnosticLocation End
= ExecutionContinues(C
);
976 if (const Stmt
*S
= End
.asStmt())
977 End
= getEnclosingStmtLocation(S
, C
.getCurrLocationContext());
979 C
.getActivePath().push_front(
980 std::make_shared
<PathDiagnosticControlFlowPiece
>(
981 Start
, End
, "Loop condition is true. Entering loop body"));
986 case Stmt::IfStmtClass
: {
987 PathDiagnosticLocation End
= ExecutionContinues(C
);
989 if (const Stmt
*S
= End
.asStmt())
990 End
= getEnclosingStmtLocation(S
, C
.getCurrLocationContext());
992 if (*(Src
->succ_begin() + 1) == Dst
)
993 C
.getActivePath().push_front(
994 std::make_shared
<PathDiagnosticControlFlowPiece
>(
995 Start
, End
, "Taking false branch"));
997 C
.getActivePath().push_front(
998 std::make_shared
<PathDiagnosticControlFlowPiece
>(
999 Start
, End
, "Taking true branch"));
1006 //===----------------------------------------------------------------------===//
1007 // Functions for determining if a loop was executed 0 times.
1008 //===----------------------------------------------------------------------===//
1010 static bool isLoop(const Stmt
*Term
) {
1011 switch (Term
->getStmtClass()) {
1012 case Stmt::ForStmtClass
:
1013 case Stmt::WhileStmtClass
:
1014 case Stmt::ObjCForCollectionStmtClass
:
1015 case Stmt::CXXForRangeStmtClass
:
1018 // Note that we intentionally do not include do..while here.
1023 static bool isJumpToFalseBranch(const BlockEdge
*BE
) {
1024 const CFGBlock
*Src
= BE
->getSrc();
1025 assert(Src
->succ_size() == 2);
1026 return (*(Src
->succ_begin()+1) == BE
->getDst());
1029 static bool isContainedByStmt(const ParentMap
&PM
, const Stmt
*S
,
1034 SubS
= PM
.getParent(SubS
);
1039 static const Stmt
*getStmtBeforeCond(const ParentMap
&PM
, const Stmt
*Term
,
1040 const ExplodedNode
*N
) {
1042 std::optional
<StmtPoint
> SP
= N
->getLocation().getAs
<StmtPoint
>();
1044 const Stmt
*S
= SP
->getStmt();
1045 if (!isContainedByStmt(PM
, Term
, S
))
1048 N
= N
->getFirstPred();
1053 static bool isInLoopBody(const ParentMap
&PM
, const Stmt
*S
, const Stmt
*Term
) {
1054 const Stmt
*LoopBody
= nullptr;
1055 switch (Term
->getStmtClass()) {
1056 case Stmt::CXXForRangeStmtClass
: {
1057 const auto *FR
= cast
<CXXForRangeStmt
>(Term
);
1058 if (isContainedByStmt(PM
, FR
->getInc(), S
))
1060 if (isContainedByStmt(PM
, FR
->getLoopVarStmt(), S
))
1062 LoopBody
= FR
->getBody();
1065 case Stmt::ForStmtClass
: {
1066 const auto *FS
= cast
<ForStmt
>(Term
);
1067 if (isContainedByStmt(PM
, FS
->getInc(), S
))
1069 LoopBody
= FS
->getBody();
1072 case Stmt::ObjCForCollectionStmtClass
: {
1073 const auto *FC
= cast
<ObjCForCollectionStmt
>(Term
);
1074 LoopBody
= FC
->getBody();
1077 case Stmt::WhileStmtClass
:
1078 LoopBody
= cast
<WhileStmt
>(Term
)->getBody();
1083 return isContainedByStmt(PM
, LoopBody
, S
);
1086 /// Adds a sanitized control-flow diagnostic edge to a path.
1087 static void addEdgeToPath(PathPieces
&path
,
1088 PathDiagnosticLocation
&PrevLoc
,
1089 PathDiagnosticLocation NewLoc
) {
1090 if (!NewLoc
.isValid())
1093 SourceLocation NewLocL
= NewLoc
.asLocation();
1094 if (NewLocL
.isInvalid())
1097 if (!PrevLoc
.isValid() || !PrevLoc
.asLocation().isValid()) {
1102 // Ignore self-edges, which occur when there are multiple nodes at the same
1104 if (NewLoc
.asStmt() && NewLoc
.asStmt() == PrevLoc
.asStmt())
1108 std::make_shared
<PathDiagnosticControlFlowPiece
>(NewLoc
, PrevLoc
));
1112 /// A customized wrapper for CFGBlock::getTerminatorCondition()
1113 /// which returns the element for ObjCForCollectionStmts.
1114 static const Stmt
*getTerminatorCondition(const CFGBlock
*B
) {
1115 const Stmt
*S
= B
->getTerminatorCondition();
1116 if (const auto *FS
= dyn_cast_or_null
<ObjCForCollectionStmt
>(S
))
1117 return FS
->getElement();
1121 constexpr llvm::StringLiteral StrEnteringLoop
= "Entering loop body";
1122 constexpr llvm::StringLiteral StrLoopBodyZero
= "Loop body executed 0 times";
1123 constexpr llvm::StringLiteral StrLoopRangeEmpty
=
1124 "Loop body skipped when range is empty";
1125 constexpr llvm::StringLiteral StrLoopCollectionEmpty
=
1126 "Loop body skipped when collection is empty";
1128 static std::unique_ptr
<FilesToLineNumsMap
>
1129 findExecutedLines(const SourceManager
&SM
, const ExplodedNode
*N
);
1131 void PathDiagnosticBuilder::generatePathDiagnosticsForNode(
1132 PathDiagnosticConstruct
&C
, PathDiagnosticLocation
&PrevLoc
) const {
1133 ProgramPoint P
= C
.getCurrentNode()->getLocation();
1134 const SourceManager
&SM
= getSourceManager();
1136 // Have we encountered an entrance to a call? It may be
1137 // the case that we have not encountered a matching
1138 // call exit before this point. This means that the path
1139 // terminated within the call itself.
1140 if (auto CE
= P
.getAs
<CallEnter
>()) {
1142 if (C
.shouldAddPathEdges()) {
1143 // Add an edge to the start of the function.
1144 const StackFrameContext
*CalleeLC
= CE
->getCalleeContext();
1145 const Decl
*D
= CalleeLC
->getDecl();
1146 // Add the edge only when the callee has body. We jump to the beginning
1147 // of the *declaration*, however we expect it to be followed by the
1148 // body. This isn't the case for autosynthesized property accessors in
1149 // Objective-C. No need for a similar extra check for CallExit points
1150 // because the exit edge comes from a statement (i.e. return),
1151 // not from declaration.
1153 addEdgeToPath(C
.getActivePath(), PrevLoc
,
1154 PathDiagnosticLocation::createBegin(D
, SM
));
1157 // Did we visit an entire call?
1158 bool VisitedEntireCall
= C
.PD
->isWithinCall();
1159 C
.PD
->popActivePath();
1161 PathDiagnosticCallPiece
*Call
;
1162 if (VisitedEntireCall
) {
1163 Call
= cast
<PathDiagnosticCallPiece
>(C
.getActivePath().front().get());
1165 // The path terminated within a nested location context, create a new
1166 // call piece to encapsulate the rest of the path pieces.
1167 const Decl
*Caller
= CE
->getLocationContext()->getDecl();
1168 Call
= PathDiagnosticCallPiece::construct(C
.getActivePath(), Caller
);
1169 assert(C
.getActivePath().size() == 1 &&
1170 C
.getActivePath().front().get() == Call
);
1172 // Since we just transferred the path over to the call piece, reset the
1173 // mapping of the active path to the current location context.
1174 assert(C
.isInLocCtxMap(&C
.getActivePath()) &&
1175 "When we ascend to a previously unvisited call, the active path's "
1176 "address shouldn't change, but rather should be compacted into "
1177 "a single CallEvent!");
1178 C
.updateLocCtxMap(&C
.getActivePath(), C
.getCurrLocationContext());
1180 // Record the location context mapping for the path within the call.
1181 assert(!C
.isInLocCtxMap(&Call
->path
) &&
1182 "When we ascend to a previously unvisited call, this must be the "
1183 "first time we encounter the caller context!");
1184 C
.updateLocCtxMap(&Call
->path
, CE
->getCalleeContext());
1186 Call
->setCallee(*CE
, SM
);
1188 // Update the previous location in the active path.
1189 PrevLoc
= Call
->getLocation();
1191 if (!C
.CallStack
.empty()) {
1192 assert(C
.CallStack
.back().first
== Call
);
1193 C
.CallStack
.pop_back();
1198 assert(C
.getCurrLocationContext() == C
.getLocationContextForActivePath() &&
1199 "The current position in the bug path is out of sync with the "
1200 "location context associated with the active path!");
1202 // Have we encountered an exit from a function call?
1203 if (std::optional
<CallExitEnd
> CE
= P
.getAs
<CallExitEnd
>()) {
1205 // We are descending into a call (backwards). Construct
1206 // a new call piece to contain the path pieces for that call.
1207 auto Call
= PathDiagnosticCallPiece::construct(*CE
, SM
);
1208 // Record the mapping from call piece to LocationContext.
1209 assert(!C
.isInLocCtxMap(&Call
->path
) &&
1210 "We just entered a call, this must've been the first time we "
1211 "encounter its context!");
1212 C
.updateLocCtxMap(&Call
->path
, CE
->getCalleeContext());
1214 if (C
.shouldAddPathEdges()) {
1215 // Add the edge to the return site.
1216 addEdgeToPath(C
.getActivePath(), PrevLoc
, Call
->callReturn
);
1217 PrevLoc
.invalidate();
1220 auto *P
= Call
.get();
1221 C
.getActivePath().push_front(std::move(Call
));
1223 // Make the contents of the call the active path for now.
1224 C
.PD
->pushActivePath(&P
->path
);
1225 C
.CallStack
.push_back(CallWithEntry(P
, C
.getCurrentNode()));
1229 if (auto PS
= P
.getAs
<PostStmt
>()) {
1230 if (!C
.shouldAddPathEdges())
1233 // Add an edge. If this is an ObjCForCollectionStmt do
1234 // not add an edge here as it appears in the CFG both
1235 // as a terminator and as a terminator condition.
1236 if (!isa
<ObjCForCollectionStmt
>(PS
->getStmt())) {
1237 PathDiagnosticLocation L
=
1238 PathDiagnosticLocation(PS
->getStmt(), SM
, C
.getCurrLocationContext());
1239 addEdgeToPath(C
.getActivePath(), PrevLoc
, L
);
1242 } else if (auto BE
= P
.getAs
<BlockEdge
>()) {
1244 if (C
.shouldAddControlNotes()) {
1245 generateMinimalDiagForBlockEdge(C
, *BE
);
1248 if (!C
.shouldAddPathEdges()) {
1252 // Are we jumping to the head of a loop? Add a special diagnostic.
1253 if (const Stmt
*Loop
= BE
->getSrc()->getLoopTarget()) {
1254 PathDiagnosticLocation
L(Loop
, SM
, C
.getCurrLocationContext());
1255 const Stmt
*Body
= nullptr;
1257 if (const auto *FS
= dyn_cast
<ForStmt
>(Loop
))
1258 Body
= FS
->getBody();
1259 else if (const auto *WS
= dyn_cast
<WhileStmt
>(Loop
))
1260 Body
= WS
->getBody();
1261 else if (const auto *OFS
= dyn_cast
<ObjCForCollectionStmt
>(Loop
)) {
1262 Body
= OFS
->getBody();
1263 } else if (const auto *FRS
= dyn_cast
<CXXForRangeStmt
>(Loop
)) {
1264 Body
= FRS
->getBody();
1266 // do-while statements are explicitly excluded here
1268 auto p
= std::make_shared
<PathDiagnosticEventPiece
>(
1269 L
, "Looping back to the head of the loop");
1270 p
->setPrunable(true);
1272 addEdgeToPath(C
.getActivePath(), PrevLoc
, p
->getLocation());
1273 // We might've added a very similar control node already
1274 if (!C
.shouldAddControlNotes()) {
1275 C
.getActivePath().push_front(std::move(p
));
1278 if (const auto *CS
= dyn_cast_or_null
<CompoundStmt
>(Body
)) {
1279 addEdgeToPath(C
.getActivePath(), PrevLoc
,
1280 PathDiagnosticLocation::createEndBrace(CS
, SM
));
1284 const CFGBlock
*BSrc
= BE
->getSrc();
1285 const ParentMap
&PM
= C
.getParentMap();
1287 if (const Stmt
*Term
= BSrc
->getTerminatorStmt()) {
1288 // Are we jumping past the loop body without ever executing the
1289 // loop (because the condition was false)?
1291 const Stmt
*TermCond
= getTerminatorCondition(BSrc
);
1292 bool IsInLoopBody
= isInLoopBody(
1293 PM
, getStmtBeforeCond(PM
, TermCond
, C
.getCurrentNode()), Term
);
1297 if (isJumpToFalseBranch(&*BE
)) {
1298 if (!IsInLoopBody
) {
1299 if (isa
<ObjCForCollectionStmt
>(Term
)) {
1300 str
= StrLoopCollectionEmpty
;
1301 } else if (isa
<CXXForRangeStmt
>(Term
)) {
1302 str
= StrLoopRangeEmpty
;
1304 str
= StrLoopBodyZero
;
1308 str
= StrEnteringLoop
;
1312 PathDiagnosticLocation
L(TermCond
? TermCond
: Term
, SM
,
1313 C
.getCurrLocationContext());
1314 auto PE
= std::make_shared
<PathDiagnosticEventPiece
>(L
, str
);
1315 PE
->setPrunable(true);
1316 addEdgeToPath(C
.getActivePath(), PrevLoc
, PE
->getLocation());
1318 // We might've added a very similar control node already
1319 if (!C
.shouldAddControlNotes()) {
1320 C
.getActivePath().push_front(std::move(PE
));
1323 } else if (isa
<BreakStmt
, ContinueStmt
, GotoStmt
>(Term
)) {
1324 PathDiagnosticLocation
L(Term
, SM
, C
.getCurrLocationContext());
1325 addEdgeToPath(C
.getActivePath(), PrevLoc
, L
);
1331 static std::unique_ptr
<PathDiagnostic
>
1332 generateDiagnosticForBasicReport(const BasicBugReport
*R
,
1333 const Decl
*AnalysisEntryPoint
) {
1334 const BugType
&BT
= R
->getBugType();
1335 return std::make_unique
<PathDiagnostic
>(
1336 BT
.getCheckerName(), R
->getDeclWithIssue(), BT
.getDescription(),
1337 R
->getDescription(), R
->getShortDescription(/*UseFallback=*/false),
1338 BT
.getCategory(), R
->getUniqueingLocation(), R
->getUniqueingDecl(),
1339 AnalysisEntryPoint
, std::make_unique
<FilesToLineNumsMap
>());
1342 static std::unique_ptr
<PathDiagnostic
>
1343 generateEmptyDiagnosticForReport(const PathSensitiveBugReport
*R
,
1344 const SourceManager
&SM
,
1345 const Decl
*AnalysisEntryPoint
) {
1346 const BugType
&BT
= R
->getBugType();
1347 return std::make_unique
<PathDiagnostic
>(
1348 BT
.getCheckerName(), R
->getDeclWithIssue(), BT
.getDescription(),
1349 R
->getDescription(), R
->getShortDescription(/*UseFallback=*/false),
1350 BT
.getCategory(), R
->getUniqueingLocation(), R
->getUniqueingDecl(),
1351 AnalysisEntryPoint
, findExecutedLines(SM
, R
->getErrorNode()));
1354 static const Stmt
*getStmtParent(const Stmt
*S
, const ParentMap
&PM
) {
1359 S
= PM
.getParentIgnoreParens(S
);
1364 if (isa
<FullExpr
, CXXBindTemporaryExpr
, SubstNonTypeTemplateParmExpr
>(S
))
1373 static bool isConditionForTerminator(const Stmt
*S
, const Stmt
*Cond
) {
1374 switch (S
->getStmtClass()) {
1375 case Stmt::BinaryOperatorClass
: {
1376 const auto *BO
= cast
<BinaryOperator
>(S
);
1377 if (!BO
->isLogicalOp())
1379 return BO
->getLHS() == Cond
|| BO
->getRHS() == Cond
;
1381 case Stmt::IfStmtClass
:
1382 return cast
<IfStmt
>(S
)->getCond() == Cond
;
1383 case Stmt::ForStmtClass
:
1384 return cast
<ForStmt
>(S
)->getCond() == Cond
;
1385 case Stmt::WhileStmtClass
:
1386 return cast
<WhileStmt
>(S
)->getCond() == Cond
;
1387 case Stmt::DoStmtClass
:
1388 return cast
<DoStmt
>(S
)->getCond() == Cond
;
1389 case Stmt::ChooseExprClass
:
1390 return cast
<ChooseExpr
>(S
)->getCond() == Cond
;
1391 case Stmt::IndirectGotoStmtClass
:
1392 return cast
<IndirectGotoStmt
>(S
)->getTarget() == Cond
;
1393 case Stmt::SwitchStmtClass
:
1394 return cast
<SwitchStmt
>(S
)->getCond() == Cond
;
1395 case Stmt::BinaryConditionalOperatorClass
:
1396 return cast
<BinaryConditionalOperator
>(S
)->getCond() == Cond
;
1397 case Stmt::ConditionalOperatorClass
: {
1398 const auto *CO
= cast
<ConditionalOperator
>(S
);
1399 return CO
->getCond() == Cond
||
1400 CO
->getLHS() == Cond
||
1401 CO
->getRHS() == Cond
;
1403 case Stmt::ObjCForCollectionStmtClass
:
1404 return cast
<ObjCForCollectionStmt
>(S
)->getElement() == Cond
;
1405 case Stmt::CXXForRangeStmtClass
: {
1406 const auto *FRS
= cast
<CXXForRangeStmt
>(S
);
1407 return FRS
->getCond() == Cond
|| FRS
->getRangeInit() == Cond
;
1414 static bool isIncrementOrInitInForLoop(const Stmt
*S
, const Stmt
*FL
) {
1415 if (const auto *FS
= dyn_cast
<ForStmt
>(FL
))
1416 return FS
->getInc() == S
|| FS
->getInit() == S
;
1417 if (const auto *FRS
= dyn_cast
<CXXForRangeStmt
>(FL
))
1418 return FRS
->getInc() == S
|| FRS
->getRangeStmt() == S
||
1419 FRS
->getLoopVarStmt() || FRS
->getRangeInit() == S
;
1423 using OptimizedCallsSet
= llvm::DenseSet
<const PathDiagnosticCallPiece
*>;
1425 /// Adds synthetic edges from top-level statements to their subexpressions.
1427 /// This avoids a "swoosh" effect, where an edge from a top-level statement A
1428 /// points to a sub-expression B.1 that's not at the start of B. In these cases,
1429 /// we'd like to see an edge from A to B, then another one from B to B.1.
1430 static void addContextEdges(PathPieces
&pieces
, const LocationContext
*LC
) {
1431 const ParentMap
&PM
= LC
->getParentMap();
1432 PathPieces::iterator Prev
= pieces
.end();
1433 for (PathPieces::iterator I
= pieces
.begin(), E
= Prev
; I
!= E
;
1435 auto *Piece
= dyn_cast
<PathDiagnosticControlFlowPiece
>(I
->get());
1440 PathDiagnosticLocation SrcLoc
= Piece
->getStartLocation();
1441 SmallVector
<PathDiagnosticLocation
, 4> SrcContexts
;
1443 PathDiagnosticLocation NextSrcContext
= SrcLoc
;
1444 const Stmt
*InnerStmt
= nullptr;
1445 while (NextSrcContext
.isValid() && NextSrcContext
.asStmt() != InnerStmt
) {
1446 SrcContexts
.push_back(NextSrcContext
);
1447 InnerStmt
= NextSrcContext
.asStmt();
1448 NextSrcContext
= getEnclosingStmtLocation(InnerStmt
, LC
,
1449 /*allowNested=*/true);
1452 // Repeatedly split the edge as necessary.
1453 // This is important for nested logical expressions (||, &&, ?:) where we
1454 // want to show all the levels of context.
1456 const Stmt
*Dst
= Piece
->getEndLocation().getStmtOrNull();
1458 // We are looking at an edge. Is the destination within a larger
1460 PathDiagnosticLocation DstContext
=
1461 getEnclosingStmtLocation(Dst
, LC
, /*allowNested=*/true);
1462 if (!DstContext
.isValid() || DstContext
.asStmt() == Dst
)
1465 // If the source is in the same context, we're already good.
1466 if (llvm::is_contained(SrcContexts
, DstContext
))
1469 // Update the subexpression node to point to the context edge.
1470 Piece
->setStartLocation(DstContext
);
1472 // Try to extend the previous edge if it's at the same level as the source
1475 auto *PrevPiece
= dyn_cast
<PathDiagnosticControlFlowPiece
>(Prev
->get());
1478 if (const Stmt
*PrevSrc
=
1479 PrevPiece
->getStartLocation().getStmtOrNull()) {
1480 const Stmt
*PrevSrcParent
= getStmtParent(PrevSrc
, PM
);
1481 if (PrevSrcParent
==
1482 getStmtParent(DstContext
.getStmtOrNull(), PM
)) {
1483 PrevPiece
->setEndLocation(DstContext
);
1490 // Otherwise, split the current edge into a context edge and a
1491 // subexpression edge. Note that the context statement may itself have
1494 std::make_shared
<PathDiagnosticControlFlowPiece
>(SrcLoc
, DstContext
);
1496 I
= pieces
.insert(I
, std::move(P
));
1501 /// Move edges from a branch condition to a branch target
1502 /// when the condition is simple.
1504 /// This restructures some of the work of addContextEdges. That function
1505 /// creates edges this may destroy, but they work together to create a more
1506 /// aesthetically set of edges around branches. After the call to
1507 /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
1508 /// the branch to the branch condition, and (3) an edge from the branch
1509 /// condition to the branch target. We keep (1), but may wish to remove (2)
1510 /// and move the source of (3) to the branch if the branch condition is simple.
1511 static void simplifySimpleBranches(PathPieces
&pieces
) {
1512 for (PathPieces::iterator I
= pieces
.begin(), E
= pieces
.end(); I
!= E
; ++I
) {
1513 const auto *PieceI
= dyn_cast
<PathDiagnosticControlFlowPiece
>(I
->get());
1518 const Stmt
*s1Start
= PieceI
->getStartLocation().getStmtOrNull();
1519 const Stmt
*s1End
= PieceI
->getEndLocation().getStmtOrNull();
1521 if (!s1Start
|| !s1End
)
1524 PathPieces::iterator NextI
= I
; ++NextI
;
1528 PathDiagnosticControlFlowPiece
*PieceNextI
= nullptr;
1534 const auto *EV
= dyn_cast
<PathDiagnosticEventPiece
>(NextI
->get());
1536 StringRef S
= EV
->getString();
1537 if (S
== StrEnteringLoop
|| S
== StrLoopBodyZero
||
1538 S
== StrLoopCollectionEmpty
|| S
== StrLoopRangeEmpty
) {
1545 PieceNextI
= dyn_cast
<PathDiagnosticControlFlowPiece
>(NextI
->get());
1552 const Stmt
*s2Start
= PieceNextI
->getStartLocation().getStmtOrNull();
1553 const Stmt
*s2End
= PieceNextI
->getEndLocation().getStmtOrNull();
1555 if (!s2Start
|| !s2End
|| s1End
!= s2Start
)
1558 // We only perform this transformation for specific branch kinds.
1559 // We don't want to do this for do..while, for example.
1560 if (!isa
<ForStmt
, WhileStmt
, IfStmt
, ObjCForCollectionStmt
,
1561 CXXForRangeStmt
>(s1Start
))
1564 // Is s1End the branch condition?
1565 if (!isConditionForTerminator(s1Start
, s1End
))
1568 // Perform the hoisting by eliminating (2) and changing the start
1570 PieceNextI
->setStartLocation(PieceI
->getStartLocation());
1571 I
= pieces
.erase(I
);
1575 /// Returns the number of bytes in the given (character-based) SourceRange.
1577 /// If the locations in the range are not on the same line, returns
1580 /// Note that this does not do a precise user-visible character or column count.
1581 static std::optional
<size_t> getLengthOnSingleLine(const SourceManager
&SM
,
1582 SourceRange Range
) {
1583 SourceRange
ExpansionRange(SM
.getExpansionLoc(Range
.getBegin()),
1584 SM
.getExpansionRange(Range
.getEnd()).getEnd());
1586 FileID FID
= SM
.getFileID(ExpansionRange
.getBegin());
1587 if (FID
!= SM
.getFileID(ExpansionRange
.getEnd()))
1588 return std::nullopt
;
1590 std::optional
<MemoryBufferRef
> Buffer
= SM
.getBufferOrNone(FID
);
1592 return std::nullopt
;
1594 unsigned BeginOffset
= SM
.getFileOffset(ExpansionRange
.getBegin());
1595 unsigned EndOffset
= SM
.getFileOffset(ExpansionRange
.getEnd());
1596 StringRef Snippet
= Buffer
->getBuffer().slice(BeginOffset
, EndOffset
);
1598 // We're searching the raw bytes of the buffer here, which might include
1599 // escaped newlines and such. That's okay; we're trying to decide whether the
1600 // SourceRange is covering a large or small amount of space in the user's
1602 if (Snippet
.find_first_of("\r\n") != StringRef::npos
)
1603 return std::nullopt
;
1605 // This isn't Unicode-aware, but it doesn't need to be.
1606 return Snippet
.size();
1609 /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
1610 static std::optional
<size_t> getLengthOnSingleLine(const SourceManager
&SM
,
1612 return getLengthOnSingleLine(SM
, S
->getSourceRange());
1615 /// Eliminate two-edge cycles created by addContextEdges().
1617 /// Once all the context edges are in place, there are plenty of cases where
1618 /// there's a single edge from a top-level statement to a subexpression,
1619 /// followed by a single path note, and then a reverse edge to get back out to
1620 /// the top level. If the statement is simple enough, the subexpression edges
1621 /// just add noise and make it harder to understand what's going on.
1623 /// This function only removes edges in pairs, because removing only one edge
1624 /// might leave other edges dangling.
1626 /// This will not remove edges in more complicated situations:
1627 /// - if there is more than one "hop" leading to or from a subexpression.
1628 /// - if there is an inlined call between the edges instead of a single event.
1629 /// - if the whole statement is large enough that having subexpression arrows
1630 /// might be helpful.
1631 static void removeContextCycles(PathPieces
&Path
, const SourceManager
&SM
) {
1632 for (PathPieces::iterator I
= Path
.begin(), E
= Path
.end(); I
!= E
; ) {
1633 // Pattern match the current piece and its successor.
1634 const auto *PieceI
= dyn_cast
<PathDiagnosticControlFlowPiece
>(I
->get());
1641 const Stmt
*s1Start
= PieceI
->getStartLocation().getStmtOrNull();
1642 const Stmt
*s1End
= PieceI
->getEndLocation().getStmtOrNull();
1644 PathPieces::iterator NextI
= I
; ++NextI
;
1648 const auto *PieceNextI
=
1649 dyn_cast
<PathDiagnosticControlFlowPiece
>(NextI
->get());
1652 if (isa
<PathDiagnosticEventPiece
>(NextI
->get())) {
1656 PieceNextI
= dyn_cast
<PathDiagnosticControlFlowPiece
>(NextI
->get());
1665 const Stmt
*s2Start
= PieceNextI
->getStartLocation().getStmtOrNull();
1666 const Stmt
*s2End
= PieceNextI
->getEndLocation().getStmtOrNull();
1668 if (s1Start
&& s2Start
&& s1Start
== s2End
&& s2Start
== s1End
) {
1669 const size_t MAX_SHORT_LINE_LENGTH
= 80;
1670 std::optional
<size_t> s1Length
= getLengthOnSingleLine(SM
, s1Start
);
1671 if (s1Length
&& *s1Length
<= MAX_SHORT_LINE_LENGTH
) {
1672 std::optional
<size_t> s2Length
= getLengthOnSingleLine(SM
, s2Start
);
1673 if (s2Length
&& *s2Length
<= MAX_SHORT_LINE_LENGTH
) {
1675 I
= Path
.erase(NextI
);
1685 /// Return true if X is contained by Y.
1686 static bool lexicalContains(const ParentMap
&PM
, const Stmt
*X
, const Stmt
*Y
) {
1690 X
= PM
.getParent(X
);
1695 // Remove short edges on the same line less than 3 columns in difference.
1696 static void removePunyEdges(PathPieces
&path
, const SourceManager
&SM
,
1697 const ParentMap
&PM
) {
1698 bool erased
= false;
1700 for (PathPieces::iterator I
= path
.begin(), E
= path
.end(); I
!= E
;
1704 const auto *PieceI
= dyn_cast
<PathDiagnosticControlFlowPiece
>(I
->get());
1709 const Stmt
*start
= PieceI
->getStartLocation().getStmtOrNull();
1710 const Stmt
*end
= PieceI
->getEndLocation().getStmtOrNull();
1715 const Stmt
*endParent
= PM
.getParent(end
);
1719 if (isConditionForTerminator(end
, endParent
))
1722 SourceLocation FirstLoc
= start
->getBeginLoc();
1723 SourceLocation SecondLoc
= end
->getBeginLoc();
1725 if (!SM
.isWrittenInSameFile(FirstLoc
, SecondLoc
))
1727 if (SM
.isBeforeInTranslationUnit(SecondLoc
, FirstLoc
))
1728 std::swap(SecondLoc
, FirstLoc
);
1730 SourceRange
EdgeRange(FirstLoc
, SecondLoc
);
1731 std::optional
<size_t> ByteWidth
= getLengthOnSingleLine(SM
, EdgeRange
);
1733 // If the statements are on different lines, continue.
1737 const size_t MAX_PUNY_EDGE_LENGTH
= 2;
1738 if (*ByteWidth
<= MAX_PUNY_EDGE_LENGTH
) {
1739 // FIXME: There are enough /bytes/ between the endpoints of the edge, but
1740 // there might not be enough /columns/. A proper user-visible column count
1741 // is probably too expensive, though.
1749 static void removeIdenticalEvents(PathPieces
&path
) {
1750 for (PathPieces::iterator I
= path
.begin(), E
= path
.end(); I
!= E
; ++I
) {
1751 const auto *PieceI
= dyn_cast
<PathDiagnosticEventPiece
>(I
->get());
1756 PathPieces::iterator NextI
= I
; ++NextI
;
1760 const auto *PieceNextI
= dyn_cast
<PathDiagnosticEventPiece
>(NextI
->get());
1765 // Erase the second piece if it has the same exact message text.
1766 if (PieceI
->getString() == PieceNextI
->getString()) {
1772 static bool optimizeEdges(const PathDiagnosticConstruct
&C
, PathPieces
&path
,
1773 OptimizedCallsSet
&OCS
) {
1774 bool hasChanges
= false;
1775 const LocationContext
*LC
= C
.getLocationContextFor(&path
);
1777 const ParentMap
&PM
= LC
->getParentMap();
1778 const SourceManager
&SM
= C
.getSourceManager();
1780 for (PathPieces::iterator I
= path
.begin(), E
= path
.end(); I
!= E
; ) {
1781 // Optimize subpaths.
1782 if (auto *CallI
= dyn_cast
<PathDiagnosticCallPiece
>(I
->get())) {
1783 // Record the fact that a call has been optimized so we only do the
1785 if (!OCS
.count(CallI
)) {
1786 while (optimizeEdges(C
, CallI
->path
, OCS
)) {
1794 // Pattern match the current piece and its successor.
1795 auto *PieceI
= dyn_cast
<PathDiagnosticControlFlowPiece
>(I
->get());
1802 const Stmt
*s1Start
= PieceI
->getStartLocation().getStmtOrNull();
1803 const Stmt
*s1End
= PieceI
->getEndLocation().getStmtOrNull();
1804 const Stmt
*level1
= getStmtParent(s1Start
, PM
);
1805 const Stmt
*level2
= getStmtParent(s1End
, PM
);
1807 PathPieces::iterator NextI
= I
; ++NextI
;
1811 const auto *PieceNextI
= dyn_cast
<PathDiagnosticControlFlowPiece
>(NextI
->get());
1818 const Stmt
*s2Start
= PieceNextI
->getStartLocation().getStmtOrNull();
1819 const Stmt
*s2End
= PieceNextI
->getEndLocation().getStmtOrNull();
1820 const Stmt
*level3
= getStmtParent(s2Start
, PM
);
1821 const Stmt
*level4
= getStmtParent(s2End
, PM
);
1825 // If we have two consecutive control edges whose end/begin locations
1826 // are at the same level (e.g. statements or top-level expressions within
1827 // a compound statement, or siblings share a single ancestor expression),
1828 // then merge them if they have no interesting intermediate event.
1832 // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
1833 // parent is '1'. Here 'x.y.z' represents the hierarchy of statements.
1835 // NOTE: this will be limited later in cases where we add barriers
1836 // to prevent this optimization.
1837 if (level1
&& level1
== level2
&& level1
== level3
&& level1
== level4
) {
1838 PieceI
->setEndLocation(PieceNextI
->getEndLocation());
1846 // Eliminate edges between subexpressions and parent expressions
1847 // when the subexpression is consumed.
1849 // NOTE: this will be limited later in cases where we add barriers
1850 // to prevent this optimization.
1851 if (s1End
&& s1End
== s2Start
&& level2
) {
1852 bool removeEdge
= false;
1853 // Remove edges into the increment or initialization of a
1854 // loop that have no interleaving event. This means that
1855 // they aren't interesting.
1856 if (isIncrementOrInitInForLoop(s1End
, level2
))
1858 // Next only consider edges that are not anchored on
1859 // the condition of a terminator. This are intermediate edges
1860 // that we might want to trim.
1861 else if (!isConditionForTerminator(level2
, s1End
)) {
1862 // Trim edges on expressions that are consumed by
1863 // the parent expression.
1864 if (isa
<Expr
>(s1End
) && PM
.isConsumedExpr(cast
<Expr
>(s1End
))) {
1867 // Trim edges where a lexical containment doesn't exist.
1872 // If 'Z' lexically contains Y (it is an ancestor) and
1873 // 'X' does not lexically contain Y (it is a descendant OR
1874 // it has no lexical relationship at all) then trim.
1876 // This can eliminate edges where we dive into a subexpression
1877 // and then pop back out, etc.
1878 else if (s1Start
&& s2End
&&
1879 lexicalContains(PM
, s2Start
, s2End
) &&
1880 !lexicalContains(PM
, s1End
, s1Start
)) {
1883 // Trim edges from a subexpression back to the top level if the
1884 // subexpression is on a different line.
1890 // These edges just look ugly and don't usually add anything.
1891 else if (s1Start
&& s2End
&&
1892 lexicalContains(PM
, s1Start
, s1End
)) {
1893 SourceRange
EdgeRange(PieceI
->getEndLocation().asLocation(),
1894 PieceI
->getStartLocation().asLocation());
1895 if (!getLengthOnSingleLine(SM
, EdgeRange
))
1901 PieceI
->setEndLocation(PieceNextI
->getEndLocation());
1908 // Optimize edges for ObjC fast-enumeration loops.
1910 // (X -> collection) -> (collection -> element)
1915 if (s1End
== s2Start
) {
1916 const auto *FS
= dyn_cast_or_null
<ObjCForCollectionStmt
>(level3
);
1917 if (FS
&& FS
->getCollection()->IgnoreParens() == s2Start
&&
1918 s2End
== FS
->getElement()) {
1919 PieceI
->setEndLocation(PieceNextI
->getEndLocation());
1926 // No changes at this index? Move to the next one.
1931 // Adjust edges into subexpressions to make them more uniform
1932 // and aesthetically pleasing.
1933 addContextEdges(path
, LC
);
1934 // Remove "cyclical" edges that include one or more context edges.
1935 removeContextCycles(path
, SM
);
1936 // Hoist edges originating from branch conditions to branches
1937 // for simple branches.
1938 simplifySimpleBranches(path
);
1939 // Remove any puny edges left over after primary optimization pass.
1940 removePunyEdges(path
, SM
, PM
);
1941 // Remove identical events.
1942 removeIdenticalEvents(path
);
1948 /// Drop the very first edge in a path, which should be a function entry edge.
1950 /// If the first edge is not a function entry edge (say, because the first
1951 /// statement had an invalid source location), this function does nothing.
1952 // FIXME: We should just generate invalid edges anyway and have the optimizer
1954 static void dropFunctionEntryEdge(const PathDiagnosticConstruct
&C
,
1956 const auto *FirstEdge
=
1957 dyn_cast
<PathDiagnosticControlFlowPiece
>(Path
.front().get());
1961 const Decl
*D
= C
.getLocationContextFor(&Path
)->getDecl();
1962 PathDiagnosticLocation EntryLoc
=
1963 PathDiagnosticLocation::createBegin(D
, C
.getSourceManager());
1964 if (FirstEdge
->getStartLocation() != EntryLoc
)
1970 /// Populate executes lines with lines containing at least one diagnostics.
1971 static void updateExecutedLinesWithDiagnosticPieces(PathDiagnostic
&PD
) {
1973 PathPieces path
= PD
.path
.flatten(/*ShouldFlattenMacros=*/true);
1974 FilesToLineNumsMap
&ExecutedLines
= PD
.getExecutedLines();
1976 for (const auto &P
: path
) {
1977 FullSourceLoc Loc
= P
->getLocation().asLocation().getExpansionLoc();
1978 FileID FID
= Loc
.getFileID();
1979 unsigned LineNo
= Loc
.getLineNumber();
1980 assert(FID
.isValid());
1981 ExecutedLines
[FID
].insert(LineNo
);
1985 PathDiagnosticConstruct::PathDiagnosticConstruct(
1986 const PathDiagnosticConsumer
*PDC
, const ExplodedNode
*ErrorNode
,
1987 const PathSensitiveBugReport
*R
, const Decl
*AnalysisEntryPoint
)
1988 : Consumer(PDC
), CurrentNode(ErrorNode
),
1989 SM(CurrentNode
->getCodeDecl().getASTContext().getSourceManager()),
1990 PD(generateEmptyDiagnosticForReport(R
, getSourceManager(),
1991 AnalysisEntryPoint
)) {
1992 LCM
[&PD
->getActivePath()] = ErrorNode
->getLocationContext();
1995 PathDiagnosticBuilder::PathDiagnosticBuilder(
1996 BugReporterContext BRC
, std::unique_ptr
<ExplodedGraph
> BugPath
,
1997 PathSensitiveBugReport
*r
, const ExplodedNode
*ErrorNode
,
1998 std::unique_ptr
<VisitorsDiagnosticsTy
> VisitorsDiagnostics
)
1999 : BugReporterContext(BRC
), BugPath(std::move(BugPath
)), R(r
),
2000 ErrorNode(ErrorNode
),
2001 VisitorsDiagnostics(std::move(VisitorsDiagnostics
)) {}
2003 std::unique_ptr
<PathDiagnostic
>
2004 PathDiagnosticBuilder::generate(const PathDiagnosticConsumer
*PDC
) const {
2005 const Decl
*EntryPoint
= getBugReporter().getAnalysisEntryPoint();
2006 PathDiagnosticConstruct
Construct(PDC
, ErrorNode
, R
, EntryPoint
);
2008 const SourceManager
&SM
= getSourceManager();
2009 const AnalyzerOptions
&Opts
= getAnalyzerOptions();
2011 if (!PDC
->shouldGenerateDiagnostics())
2012 return generateEmptyDiagnosticForReport(R
, getSourceManager(), EntryPoint
);
2014 // Construct the final (warning) event for the bug report.
2015 auto EndNotes
= VisitorsDiagnostics
->find(ErrorNode
);
2016 PathDiagnosticPieceRef LastPiece
;
2017 if (EndNotes
!= VisitorsDiagnostics
->end()) {
2018 assert(!EndNotes
->second
.empty());
2019 LastPiece
= EndNotes
->second
[0];
2021 LastPiece
= BugReporterVisitor::getDefaultEndPath(*this, ErrorNode
,
2024 Construct
.PD
->setEndOfPath(LastPiece
);
2026 PathDiagnosticLocation PrevLoc
= Construct
.PD
->getLocation();
2027 // From the error node to the root, ascend the bug path and construct the bug
2029 while (Construct
.ascendToPrevNode()) {
2030 generatePathDiagnosticsForNode(Construct
, PrevLoc
);
2032 auto VisitorNotes
= VisitorsDiagnostics
->find(Construct
.getCurrentNode());
2033 if (VisitorNotes
== VisitorsDiagnostics
->end())
2036 // This is a workaround due to inability to put shared PathDiagnosticPiece
2037 // into a FoldingSet.
2038 std::set
<llvm::FoldingSetNodeID
> DeduplicationSet
;
2040 // Add pieces from custom visitors.
2041 for (const PathDiagnosticPieceRef
&Note
: VisitorNotes
->second
) {
2042 llvm::FoldingSetNodeID ID
;
2044 if (!DeduplicationSet
.insert(ID
).second
)
2047 if (PDC
->shouldAddPathEdges())
2048 addEdgeToPath(Construct
.getActivePath(), PrevLoc
, Note
->getLocation());
2049 updateStackPiecesWithMessage(Note
, Construct
.CallStack
);
2050 Construct
.getActivePath().push_front(Note
);
2054 if (PDC
->shouldAddPathEdges()) {
2055 // Add an edge to the start of the function.
2056 // We'll prune it out later, but it helps make diagnostics more uniform.
2057 const StackFrameContext
*CalleeLC
=
2058 Construct
.getLocationContextForActivePath()->getStackFrame();
2059 const Decl
*D
= CalleeLC
->getDecl();
2060 addEdgeToPath(Construct
.getActivePath(), PrevLoc
,
2061 PathDiagnosticLocation::createBegin(D
, SM
));
2065 // Finally, prune the diagnostic path of uninteresting stuff.
2066 if (!Construct
.PD
->path
.empty()) {
2067 if (R
->shouldPrunePath() && Opts
.ShouldPrunePaths
) {
2068 bool stillHasNotes
=
2069 removeUnneededCalls(Construct
, Construct
.getMutablePieces(), R
);
2070 assert(stillHasNotes
);
2071 (void)stillHasNotes
;
2074 // Remove pop-up notes if needed.
2075 if (!Opts
.ShouldAddPopUpNotes
)
2076 removePopUpNotes(Construct
.getMutablePieces());
2078 // Redirect all call pieces to have valid locations.
2079 adjustCallLocations(Construct
.getMutablePieces());
2080 removePiecesWithInvalidLocations(Construct
.getMutablePieces());
2082 if (PDC
->shouldAddPathEdges()) {
2084 // Reduce the number of edges from a very conservative set
2085 // to an aesthetically pleasing subset that conveys the
2086 // necessary information.
2087 OptimizedCallsSet OCS
;
2088 while (optimizeEdges(Construct
, Construct
.getMutablePieces(), OCS
)) {
2091 // Drop the very first function-entry edge. It's not really necessary
2092 // for top-level functions.
2093 dropFunctionEntryEdge(Construct
, Construct
.getMutablePieces());
2096 // Remove messages that are basically the same, and edges that may not
2098 // We have to do this after edge optimization in the Extensive mode.
2099 removeRedundantMsgs(Construct
.getMutablePieces());
2100 removeEdgesToDefaultInitializers(Construct
.getMutablePieces());
2103 if (Opts
.ShouldDisplayMacroExpansions
)
2104 CompactMacroExpandedPieces(Construct
.getMutablePieces(), SM
);
2106 return std::move(Construct
.PD
);
2109 //===----------------------------------------------------------------------===//
2110 // Methods for BugType and subclasses.
2111 //===----------------------------------------------------------------------===//
2113 void BugType::anchor() {}
2115 //===----------------------------------------------------------------------===//
2116 // Methods for BugReport and subclasses.
2117 //===----------------------------------------------------------------------===//
2119 LLVM_ATTRIBUTE_USED
static bool
2120 isDependency(const CheckerRegistryData
&Registry
, StringRef CheckerName
) {
2121 for (const std::pair
<StringRef
, StringRef
> &Pair
: Registry
.Dependencies
) {
2122 if (Pair
.second
== CheckerName
)
2128 LLVM_ATTRIBUTE_USED
static bool isHidden(const CheckerRegistryData
&Registry
,
2129 StringRef CheckerName
) {
2130 for (const CheckerInfo
&Checker
: Registry
.Checkers
) {
2131 if (Checker
.FullName
== CheckerName
)
2132 return Checker
.IsHidden
;
2135 "Checker name not found in CheckerRegistry -- did you retrieve it "
2136 "correctly from CheckerManager::getCurrentCheckerName?");
2139 PathSensitiveBugReport::PathSensitiveBugReport(
2140 const BugType
&bt
, StringRef shortDesc
, StringRef desc
,
2141 const ExplodedNode
*errorNode
, PathDiagnosticLocation LocationToUnique
,
2142 const Decl
*DeclToUnique
)
2143 : BugReport(Kind::PathSensitive
, bt
, shortDesc
, desc
), ErrorNode(errorNode
),
2144 ErrorNodeRange(getStmt() ? getStmt()->getSourceRange() : SourceRange()),
2145 UniqueingLocation(LocationToUnique
), UniqueingDecl(DeclToUnique
) {
2146 assert(!isDependency(ErrorNode
->getState()
2147 ->getAnalysisManager()
2148 .getCheckerManager()
2149 ->getCheckerRegistryData(),
2150 bt
.getCheckerName()) &&
2151 "Some checkers depend on this one! We don't allow dependency "
2152 "checkers to emit warnings, because checkers should depend on "
2153 "*modeling*, not *diagnostics*.");
2155 assert((bt
.getCheckerName().starts_with("debug") ||
2156 !isHidden(ErrorNode
->getState()
2157 ->getAnalysisManager()
2158 .getCheckerManager()
2159 ->getCheckerRegistryData(),
2160 bt
.getCheckerName())) &&
2161 "Hidden checkers musn't emit diagnostics as they are by definition "
2162 "non-user facing!");
2165 void PathSensitiveBugReport::addVisitor(
2166 std::unique_ptr
<BugReporterVisitor
> visitor
) {
2170 llvm::FoldingSetNodeID ID
;
2171 visitor
->Profile(ID
);
2173 void *InsertPos
= nullptr;
2174 if (CallbacksSet
.FindNodeOrInsertPos(ID
, InsertPos
)) {
2178 Callbacks
.push_back(std::move(visitor
));
2181 void PathSensitiveBugReport::clearVisitors() {
2185 const Decl
*PathSensitiveBugReport::getDeclWithIssue() const {
2186 const ExplodedNode
*N
= getErrorNode();
2190 const LocationContext
*LC
= N
->getLocationContext();
2191 return LC
->getStackFrame()->getDecl();
2194 void BasicBugReport::Profile(llvm::FoldingSetNodeID
& hash
) const {
2195 hash
.AddInteger(static_cast<int>(getKind()));
2196 hash
.AddPointer(&BT
);
2197 hash
.AddString(getShortDescription());
2198 assert(Location
.isValid());
2199 Location
.Profile(hash
);
2201 for (SourceRange range
: Ranges
) {
2202 if (!range
.isValid())
2204 hash
.Add(range
.getBegin());
2205 hash
.Add(range
.getEnd());
2209 void PathSensitiveBugReport::Profile(llvm::FoldingSetNodeID
&hash
) const {
2210 hash
.AddInteger(static_cast<int>(getKind()));
2211 hash
.AddPointer(&BT
);
2212 hash
.AddString(getShortDescription());
2213 PathDiagnosticLocation UL
= getUniqueingLocation();
2217 // TODO: The statement may be null if the report was emitted before any
2218 // statements were executed. In particular, some checkers by design
2219 // occasionally emit their reports in empty functions (that have no
2220 // statements in their body). Do we profile correctly in this case?
2221 hash
.AddPointer(ErrorNode
->getCurrentOrPreviousStmtForDiagnostics());
2224 for (SourceRange range
: Ranges
) {
2225 if (!range
.isValid())
2227 hash
.Add(range
.getBegin());
2228 hash
.Add(range
.getEnd());
2233 static void insertToInterestingnessMap(
2234 llvm::DenseMap
<T
, bugreporter::TrackingKind
> &InterestingnessMap
, T Val
,
2235 bugreporter::TrackingKind TKind
) {
2236 auto Result
= InterestingnessMap
.insert({Val
, TKind
});
2241 // Even if this symbol/region was already marked as interesting as a
2242 // condition, if we later mark it as interesting again but with
2243 // thorough tracking, overwrite it. Entities marked with thorough
2244 // interestiness are the most important (or most interesting, if you will),
2245 // and we wouldn't like to downplay their importance.
2248 case bugreporter::TrackingKind::Thorough
:
2249 Result
.first
->getSecond() = bugreporter::TrackingKind::Thorough
;
2251 case bugreporter::TrackingKind::Condition
:
2256 "BugReport::markInteresting currently can only handle 2 different "
2257 "tracking kinds! Please define what tracking kind should this entitiy"
2258 "have, if it was already marked as interesting with a different kind!");
2261 void PathSensitiveBugReport::markInteresting(SymbolRef sym
,
2262 bugreporter::TrackingKind TKind
) {
2266 insertToInterestingnessMap(InterestingSymbols
, sym
, TKind
);
2268 // FIXME: No tests exist for this code and it is questionable:
2269 // How to handle multiple metadata for the same region?
2270 if (const auto *meta
= dyn_cast
<SymbolMetadata
>(sym
))
2271 markInteresting(meta
->getRegion(), TKind
);
2274 void PathSensitiveBugReport::markNotInteresting(SymbolRef sym
) {
2277 InterestingSymbols
.erase(sym
);
2279 // The metadata part of markInteresting is not reversed here.
2280 // Just making the same region not interesting is incorrect
2281 // in specific cases.
2282 if (const auto *meta
= dyn_cast
<SymbolMetadata
>(sym
))
2283 markNotInteresting(meta
->getRegion());
2286 void PathSensitiveBugReport::markInteresting(const MemRegion
*R
,
2287 bugreporter::TrackingKind TKind
) {
2291 R
= R
->getBaseRegion();
2292 insertToInterestingnessMap(InterestingRegions
, R
, TKind
);
2294 if (const auto *SR
= dyn_cast
<SymbolicRegion
>(R
))
2295 markInteresting(SR
->getSymbol(), TKind
);
2298 void PathSensitiveBugReport::markNotInteresting(const MemRegion
*R
) {
2302 R
= R
->getBaseRegion();
2303 InterestingRegions
.erase(R
);
2305 if (const auto *SR
= dyn_cast
<SymbolicRegion
>(R
))
2306 markNotInteresting(SR
->getSymbol());
2309 void PathSensitiveBugReport::markInteresting(SVal V
,
2310 bugreporter::TrackingKind TKind
) {
2311 markInteresting(V
.getAsRegion(), TKind
);
2312 markInteresting(V
.getAsSymbol(), TKind
);
2315 void PathSensitiveBugReport::markInteresting(const LocationContext
*LC
) {
2318 InterestingLocationContexts
.insert(LC
);
2321 std::optional
<bugreporter::TrackingKind
>
2322 PathSensitiveBugReport::getInterestingnessKind(SVal V
) const {
2323 auto RKind
= getInterestingnessKind(V
.getAsRegion());
2324 auto SKind
= getInterestingnessKind(V
.getAsSymbol());
2330 // If either is marked with throrough tracking, return that, we wouldn't like
2331 // to downplay a note's importance by 'only' mentioning it as a condition.
2333 case bugreporter::TrackingKind::Thorough
:
2335 case bugreporter::TrackingKind::Condition
:
2340 "BugReport::getInterestingnessKind currently can only handle 2 different "
2341 "tracking kinds! Please define what tracking kind should we return here "
2342 "when the kind of getAsRegion() and getAsSymbol() is different!");
2343 return std::nullopt
;
2346 std::optional
<bugreporter::TrackingKind
>
2347 PathSensitiveBugReport::getInterestingnessKind(SymbolRef sym
) const {
2349 return std::nullopt
;
2350 // We don't currently consider metadata symbols to be interesting
2351 // even if we know their region is interesting. Is that correct behavior?
2352 auto It
= InterestingSymbols
.find(sym
);
2353 if (It
== InterestingSymbols
.end())
2354 return std::nullopt
;
2355 return It
->getSecond();
2358 std::optional
<bugreporter::TrackingKind
>
2359 PathSensitiveBugReport::getInterestingnessKind(const MemRegion
*R
) const {
2361 return std::nullopt
;
2363 R
= R
->getBaseRegion();
2364 auto It
= InterestingRegions
.find(R
);
2365 if (It
!= InterestingRegions
.end())
2366 return It
->getSecond();
2368 if (const auto *SR
= dyn_cast
<SymbolicRegion
>(R
))
2369 return getInterestingnessKind(SR
->getSymbol());
2370 return std::nullopt
;
2373 bool PathSensitiveBugReport::isInteresting(SVal V
) const {
2374 return getInterestingnessKind(V
).has_value();
2377 bool PathSensitiveBugReport::isInteresting(SymbolRef sym
) const {
2378 return getInterestingnessKind(sym
).has_value();
2381 bool PathSensitiveBugReport::isInteresting(const MemRegion
*R
) const {
2382 return getInterestingnessKind(R
).has_value();
2385 bool PathSensitiveBugReport::isInteresting(const LocationContext
*LC
) const {
2388 return InterestingLocationContexts
.count(LC
);
2391 const Stmt
*PathSensitiveBugReport::getStmt() const {
2395 ProgramPoint ProgP
= ErrorNode
->getLocation();
2396 const Stmt
*S
= nullptr;
2398 if (std::optional
<BlockEntrance
> BE
= ProgP
.getAs
<BlockEntrance
>()) {
2399 CFGBlock
&Exit
= ProgP
.getLocationContext()->getCFG()->getExit();
2400 if (BE
->getBlock() == &Exit
)
2401 S
= ErrorNode
->getPreviousStmtForDiagnostics();
2404 S
= ErrorNode
->getStmtForDiagnostics();
2409 ArrayRef
<SourceRange
>
2410 PathSensitiveBugReport::getRanges() const {
2411 // If no custom ranges, add the range of the statement corresponding to
2413 if (Ranges
.empty() && isa_and_nonnull
<Expr
>(getStmt()))
2414 return ErrorNodeRange
;
2419 static bool exitingDestructor(const ExplodedNode
*N
) {
2420 // Need to loop here, as some times the Error node is already outside of the
2421 // destructor context, and the previous node is an edge that is also outside.
2422 while (N
&& !N
->getLocation().getAs
<StmtPoint
>()) {
2423 N
= N
->getFirstPred();
2425 return N
&& isa
<CXXDestructorDecl
>(N
->getLocationContext()->getDecl());
2429 findReasonableStmtCloseToFunctionExit(const ExplodedNode
*N
) {
2430 if (exitingDestructor(N
)) {
2431 // If we are exiting a destructor call, it is more useful to point to
2432 // the next stmt which is usually the temporary declaration.
2433 if (const Stmt
*S
= N
->getNextStmtForDiagnostics())
2435 // If next stmt is not found, it is likely the end of a top-level
2436 // function analysis. find the last execution statement then.
2438 return N
->getPreviousStmtForDiagnostics();
2441 PathDiagnosticLocation
2442 PathSensitiveBugReport::getLocation() const {
2443 assert(ErrorNode
&& "Cannot create a location with a null node.");
2444 const Stmt
*S
= ErrorNode
->getStmtForDiagnostics();
2445 ProgramPoint P
= ErrorNode
->getLocation();
2446 const LocationContext
*LC
= P
.getLocationContext();
2448 ErrorNode
->getState()->getStateManager().getContext().getSourceManager();
2451 // If this is an implicit call, return the implicit call point location.
2452 if (std::optional
<PreImplicitCall
> PIE
= P
.getAs
<PreImplicitCall
>())
2453 return PathDiagnosticLocation(PIE
->getLocation(), SM
);
2454 if (auto FE
= P
.getAs
<FunctionExitPoint
>()) {
2455 if (const ReturnStmt
*RS
= FE
->getStmt())
2456 return PathDiagnosticLocation::createBegin(RS
, SM
, LC
);
2458 S
= findReasonableStmtCloseToFunctionExit(ErrorNode
);
2461 S
= ErrorNode
->getNextStmtForDiagnostics();
2465 // Attributed statements usually have corrupted begin locations,
2466 // it's OK to ignore attributes for our purposes and deal with
2467 // the actual annotated statement.
2468 if (const auto *AS
= dyn_cast
<AttributedStmt
>(S
))
2469 S
= AS
->getSubStmt();
2471 // For member expressions, return the location of the '.' or '->'.
2472 if (const auto *ME
= dyn_cast
<MemberExpr
>(S
))
2473 return PathDiagnosticLocation::createMemberLoc(ME
, SM
);
2475 // For binary operators, return the location of the operator.
2476 if (const auto *B
= dyn_cast
<BinaryOperator
>(S
))
2477 return PathDiagnosticLocation::createOperatorLoc(B
, SM
);
2479 if (P
.getAs
<PostStmtPurgeDeadSymbols
>())
2480 return PathDiagnosticLocation::createEnd(S
, SM
, LC
);
2482 if (S
->getBeginLoc().isValid())
2483 return PathDiagnosticLocation(S
, SM
, LC
);
2485 return PathDiagnosticLocation(
2486 PathDiagnosticLocation::getValidSourceLocation(S
, LC
), SM
);
2489 return PathDiagnosticLocation::createDeclEnd(ErrorNode
->getLocationContext(),
2493 //===----------------------------------------------------------------------===//
2494 // Methods for BugReporter and subclasses.
2495 //===----------------------------------------------------------------------===//
2497 const ExplodedGraph
&PathSensitiveBugReporter::getGraph() const {
2498 return Eng
.getGraph();
2501 ProgramStateManager
&PathSensitiveBugReporter::getStateManager() const {
2502 return Eng
.getStateManager();
2505 BugReporter::BugReporter(BugReporterData
&D
)
2506 : D(D
), UserSuppressions(D
.getASTContext()) {}
2508 BugReporter::~BugReporter() {
2509 // Make sure reports are flushed.
2510 assert(StrBugTypes
.empty() &&
2511 "Destroying BugReporter before diagnostics are emitted!");
2513 // Free the bug reports we are tracking.
2514 for (const auto I
: EQClassesVector
)
2518 void BugReporter::FlushReports() {
2519 // We need to flush reports in deterministic order to ensure the order
2520 // of the reports is consistent between runs.
2521 for (const auto EQ
: EQClassesVector
)
2524 // BugReporter owns and deletes only BugTypes created implicitly through
2526 // FIXME: There are leaks from checkers that assume that the BugTypes they
2527 // create will be destroyed by the BugReporter.
2528 StrBugTypes
.clear();
2531 //===----------------------------------------------------------------------===//
2532 // PathDiagnostics generation.
2533 //===----------------------------------------------------------------------===//
2537 /// A wrapper around an ExplodedGraph that contains a single path from the root
2538 /// to the error node.
2541 std::unique_ptr
<ExplodedGraph
> BugPath
;
2542 PathSensitiveBugReport
*Report
;
2543 const ExplodedNode
*ErrorNode
;
2546 /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
2547 /// conveniently retrieve bug paths from a single error node to the root.
2548 class BugPathGetter
{
2549 std::unique_ptr
<ExplodedGraph
> TrimmedGraph
;
2551 using PriorityMapTy
= llvm::DenseMap
<const ExplodedNode
*, unsigned>;
2553 /// Assign each node with its distance from the root.
2554 PriorityMapTy PriorityMap
;
2556 /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
2557 /// we need to pair it to the error node of the constructed trimmed graph.
2558 using ReportNewNodePair
=
2559 std::pair
<PathSensitiveBugReport
*, const ExplodedNode
*>;
2560 SmallVector
<ReportNewNodePair
, 32> ReportNodes
;
2562 BugPathInfo CurrentBugPath
;
2564 /// A helper class for sorting ExplodedNodes by priority.
2565 template <bool Descending
>
2566 class PriorityCompare
{
2567 const PriorityMapTy
&PriorityMap
;
2570 PriorityCompare(const PriorityMapTy
&M
) : PriorityMap(M
) {}
2572 bool operator()(const ExplodedNode
*LHS
, const ExplodedNode
*RHS
) const {
2573 PriorityMapTy::const_iterator LI
= PriorityMap
.find(LHS
);
2574 PriorityMapTy::const_iterator RI
= PriorityMap
.find(RHS
);
2575 PriorityMapTy::const_iterator E
= PriorityMap
.end();
2582 return Descending
? LI
->second
> RI
->second
2583 : LI
->second
< RI
->second
;
2586 bool operator()(const ReportNewNodePair
&LHS
,
2587 const ReportNewNodePair
&RHS
) const {
2588 return (*this)(LHS
.second
, RHS
.second
);
2593 BugPathGetter(const ExplodedGraph
*OriginalGraph
,
2594 ArrayRef
<PathSensitiveBugReport
*> &bugReports
);
2596 BugPathInfo
*getNextBugPath();
2601 BugPathGetter::BugPathGetter(const ExplodedGraph
*OriginalGraph
,
2602 ArrayRef
<PathSensitiveBugReport
*> &bugReports
) {
2603 SmallVector
<const ExplodedNode
*, 32> Nodes
;
2604 for (const auto I
: bugReports
) {
2605 assert(I
->isValid() &&
2606 "We only allow BugReporterVisitors and BugReporter itself to "
2607 "invalidate reports!");
2608 Nodes
.emplace_back(I
->getErrorNode());
2611 // The trimmed graph is created in the body of the constructor to ensure
2612 // that the DenseMaps have been initialized already.
2613 InterExplodedGraphMap ForwardMap
;
2614 TrimmedGraph
= OriginalGraph
->trim(Nodes
, &ForwardMap
);
2616 // Find the (first) error node in the trimmed graph. We just need to consult
2617 // the node map which maps from nodes in the original graph to nodes
2618 // in the new graph.
2619 llvm::SmallPtrSet
<const ExplodedNode
*, 32> RemainingNodes
;
2621 for (PathSensitiveBugReport
*Report
: bugReports
) {
2622 const ExplodedNode
*NewNode
= ForwardMap
.lookup(Report
->getErrorNode());
2624 "Failed to construct a trimmed graph that contains this error "
2626 ReportNodes
.emplace_back(Report
, NewNode
);
2627 RemainingNodes
.insert(NewNode
);
2630 assert(!RemainingNodes
.empty() && "No error node found in the trimmed graph");
2632 // Perform a forward BFS to find all the shortest paths.
2633 std::queue
<const ExplodedNode
*> WS
;
2635 assert(TrimmedGraph
->num_roots() == 1);
2636 WS
.push(*TrimmedGraph
->roots_begin());
2637 unsigned Priority
= 0;
2639 while (!WS
.empty()) {
2640 const ExplodedNode
*Node
= WS
.front();
2643 PriorityMapTy::iterator PriorityEntry
;
2645 std::tie(PriorityEntry
, IsNew
) = PriorityMap
.insert({Node
, Priority
});
2649 assert(PriorityEntry
->second
<= Priority
);
2653 if (RemainingNodes
.erase(Node
))
2654 if (RemainingNodes
.empty())
2657 for (const ExplodedNode
*Succ
: Node
->succs())
2661 // Sort the error paths from longest to shortest.
2662 llvm::sort(ReportNodes
, PriorityCompare
<true>(PriorityMap
));
2665 BugPathInfo
*BugPathGetter::getNextBugPath() {
2666 if (ReportNodes
.empty())
2669 const ExplodedNode
*OrigN
;
2670 std::tie(CurrentBugPath
.Report
, OrigN
) = ReportNodes
.pop_back_val();
2671 assert(PriorityMap
.contains(OrigN
) && "error node not accessible from root");
2673 // Create a new graph with a single path. This is the graph that will be
2674 // returned to the caller.
2675 auto GNew
= std::make_unique
<ExplodedGraph
>();
2677 // Now walk from the error node up the BFS path, always taking the
2678 // predeccessor with the lowest number.
2679 ExplodedNode
*Succ
= nullptr;
2681 // Create the equivalent node in the new graph with the same state
2683 ExplodedNode
*NewN
= GNew
->createUncachedNode(
2684 OrigN
->getLocation(), OrigN
->getState(),
2685 OrigN
->getID(), OrigN
->isSink());
2687 // Link up the new node with the previous node.
2689 Succ
->addPredecessor(NewN
, *GNew
);
2691 CurrentBugPath
.ErrorNode
= NewN
;
2695 // Are we at the final node?
2696 if (OrigN
->pred_empty()) {
2697 GNew
->addRoot(NewN
);
2701 // Find the next predeccessor node. We choose the node that is marked
2702 // with the lowest BFS number.
2703 OrigN
= *std::min_element(OrigN
->pred_begin(), OrigN
->pred_end(),
2704 PriorityCompare
<false>(PriorityMap
));
2707 CurrentBugPath
.BugPath
= std::move(GNew
);
2709 return &CurrentBugPath
;
2712 /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
2713 /// object and collapses PathDiagosticPieces that are expanded by macros.
2714 static void CompactMacroExpandedPieces(PathPieces
&path
,
2715 const SourceManager
& SM
) {
2716 using MacroStackTy
= std::vector
<
2717 std::pair
<std::shared_ptr
<PathDiagnosticMacroPiece
>, SourceLocation
>>;
2719 using PiecesTy
= std::vector
<PathDiagnosticPieceRef
>;
2721 MacroStackTy MacroStack
;
2724 for (PathPieces::const_iterator I
= path
.begin(), E
= path
.end();
2726 const auto &piece
= *I
;
2728 // Recursively compact calls.
2729 if (auto *call
= dyn_cast
<PathDiagnosticCallPiece
>(&*piece
)) {
2730 CompactMacroExpandedPieces(call
->path
, SM
);
2733 // Get the location of the PathDiagnosticPiece.
2734 const FullSourceLoc Loc
= piece
->getLocation().asLocation();
2736 // Determine the instantiation location, which is the location we group
2737 // related PathDiagnosticPieces.
2738 SourceLocation InstantiationLoc
= Loc
.isMacroID() ?
2739 SM
.getExpansionLoc(Loc
) :
2742 if (Loc
.isFileID()) {
2744 Pieces
.push_back(piece
);
2748 assert(Loc
.isMacroID());
2750 // Is the PathDiagnosticPiece within the same macro group?
2751 if (!MacroStack
.empty() && InstantiationLoc
== MacroStack
.back().second
) {
2752 MacroStack
.back().first
->subPieces
.push_back(piece
);
2756 // We aren't in the same group. Are we descending into a new macro
2757 // or are part of an old one?
2758 std::shared_ptr
<PathDiagnosticMacroPiece
> MacroGroup
;
2760 SourceLocation ParentInstantiationLoc
= InstantiationLoc
.isMacroID() ?
2761 SM
.getExpansionLoc(Loc
) :
2764 // Walk the entire macro stack.
2765 while (!MacroStack
.empty()) {
2766 if (InstantiationLoc
== MacroStack
.back().second
) {
2767 MacroGroup
= MacroStack
.back().first
;
2771 if (ParentInstantiationLoc
== MacroStack
.back().second
) {
2772 MacroGroup
= MacroStack
.back().first
;
2776 MacroStack
.pop_back();
2779 if (!MacroGroup
|| ParentInstantiationLoc
== MacroStack
.back().second
) {
2780 // Create a new macro group and add it to the stack.
2781 auto NewGroup
= std::make_shared
<PathDiagnosticMacroPiece
>(
2782 PathDiagnosticLocation::createSingleLocation(piece
->getLocation()));
2785 MacroGroup
->subPieces
.push_back(NewGroup
);
2787 assert(InstantiationLoc
.isFileID());
2788 Pieces
.push_back(NewGroup
);
2791 MacroGroup
= NewGroup
;
2792 MacroStack
.push_back(std::make_pair(MacroGroup
, InstantiationLoc
));
2795 // Finally, add the PathDiagnosticPiece to the group.
2796 MacroGroup
->subPieces
.push_back(piece
);
2799 // Now take the pieces and construct a new PathDiagnostic.
2802 path
.insert(path
.end(), Pieces
.begin(), Pieces
.end());
2805 /// Generate notes from all visitors.
2806 /// Notes associated with @c ErrorNode are generated using
2807 /// @c getEndPath, and the rest are generated with @c VisitNode.
2808 static std::unique_ptr
<VisitorsDiagnosticsTy
>
2809 generateVisitorsDiagnostics(PathSensitiveBugReport
*R
,
2810 const ExplodedNode
*ErrorNode
,
2811 BugReporterContext
&BRC
) {
2812 std::unique_ptr
<VisitorsDiagnosticsTy
> Notes
=
2813 std::make_unique
<VisitorsDiagnosticsTy
>();
2814 PathSensitiveBugReport::VisitorList visitors
;
2816 // Run visitors on all nodes starting from the node *before* the last one.
2817 // The last node is reserved for notes generated with @c getEndPath.
2818 const ExplodedNode
*NextNode
= ErrorNode
->getFirstPred();
2821 // At each iteration, move all visitors from report to visitor list. This is
2822 // important, because the Profile() functions of the visitors make sure that
2823 // a visitor isn't added multiple times for the same node, but it's fine
2824 // to add the a visitor with Profile() for different nodes (e.g. tracking
2825 // a region at different points of the symbolic execution).
2826 for (std::unique_ptr
<BugReporterVisitor
> &Visitor
: R
->visitors())
2827 visitors
.push_back(std::move(Visitor
));
2831 const ExplodedNode
*Pred
= NextNode
->getFirstPred();
2833 PathDiagnosticPieceRef LastPiece
;
2834 for (auto &V
: visitors
) {
2835 V
->finalizeVisitor(BRC
, ErrorNode
, *R
);
2837 if (auto Piece
= V
->getEndPath(BRC
, ErrorNode
, *R
)) {
2838 assert(!LastPiece
&&
2839 "There can only be one final piece in a diagnostic.");
2840 assert(Piece
->getKind() == PathDiagnosticPiece::Kind::Event
&&
2841 "The final piece must contain a message!");
2842 LastPiece
= std::move(Piece
);
2843 (*Notes
)[ErrorNode
].push_back(LastPiece
);
2849 for (auto &V
: visitors
) {
2850 auto P
= V
->VisitNode(NextNode
, BRC
, *R
);
2852 (*Notes
)[NextNode
].push_back(std::move(P
));
2864 std::optional
<PathDiagnosticBuilder
> PathDiagnosticBuilder::findValidReport(
2865 ArrayRef
<PathSensitiveBugReport
*> &bugReports
,
2866 PathSensitiveBugReporter
&Reporter
) {
2867 Z3CrosscheckOracle
Z3Oracle(Reporter
.getAnalyzerOptions());
2869 BugPathGetter
BugGraph(&Reporter
.getGraph(), bugReports
);
2871 while (BugPathInfo
*BugPath
= BugGraph
.getNextBugPath()) {
2872 // Find the BugReport with the original location.
2873 PathSensitiveBugReport
*R
= BugPath
->Report
;
2874 assert(R
&& "No original report found for sliced graph.");
2875 assert(R
->isValid() && "Report selected by trimmed graph marked invalid.");
2876 const ExplodedNode
*ErrorNode
= BugPath
->ErrorNode
;
2878 // Register refutation visitors first, if they mark the bug invalid no
2879 // further analysis is required
2880 R
->addVisitor
<LikelyFalsePositiveSuppressionBRVisitor
>();
2882 // Register additional node visitors.
2883 R
->addVisitor
<NilReceiverBRVisitor
>();
2884 R
->addVisitor
<ConditionBRVisitor
>();
2885 R
->addVisitor
<TagVisitor
>();
2887 BugReporterContext
BRC(Reporter
);
2889 // Run all visitors on a given graph, once.
2890 std::unique_ptr
<VisitorsDiagnosticsTy
> visitorNotes
=
2891 generateVisitorsDiagnostics(R
, ErrorNode
, BRC
);
2894 if (Reporter
.getAnalyzerOptions().ShouldCrosscheckWithZ3
) {
2895 // If crosscheck is enabled, remove all visitors, add the refutation
2896 // visitor and check again
2898 Z3CrosscheckVisitor::Z3Result CrosscheckResult
;
2899 R
->addVisitor
<Z3CrosscheckVisitor
>(CrosscheckResult
,
2900 Reporter
.getAnalyzerOptions());
2902 // We don't overwrite the notes inserted by other visitors because the
2903 // refutation manager does not add any new note to the path
2904 generateVisitorsDiagnostics(R
, BugPath
->ErrorNode
, BRC
);
2905 switch (Z3Oracle
.interpretQueryResult(CrosscheckResult
)) {
2906 case Z3CrosscheckOracle::RejectReport
:
2907 ++NumTimesReportRefuted
;
2908 R
->markInvalid("Infeasible constraints", /*Data=*/nullptr);
2910 case Z3CrosscheckOracle::RejectEQClass
:
2911 ++NumTimesReportEQClassAborted
;
2913 case Z3CrosscheckOracle::AcceptReport
:
2914 ++NumTimesReportPassesZ3
;
2919 assert(R
->isValid());
2920 return PathDiagnosticBuilder(std::move(BRC
), std::move(BugPath
->BugPath
),
2921 BugPath
->Report
, BugPath
->ErrorNode
,
2922 std::move(visitorNotes
));
2926 ++NumTimesReportEQClassWasExhausted
;
2930 std::unique_ptr
<DiagnosticForConsumerMapTy
>
2931 PathSensitiveBugReporter::generatePathDiagnostics(
2932 ArrayRef
<PathDiagnosticConsumer
*> consumers
,
2933 ArrayRef
<PathSensitiveBugReport
*> &bugReports
) {
2934 assert(!bugReports
.empty());
2936 auto Out
= std::make_unique
<DiagnosticForConsumerMapTy
>();
2938 std::optional
<PathDiagnosticBuilder
> PDB
=
2939 PathDiagnosticBuilder::findValidReport(bugReports
, *this);
2942 for (PathDiagnosticConsumer
*PC
: consumers
) {
2943 if (std::unique_ptr
<PathDiagnostic
> PD
= PDB
->generate(PC
)) {
2944 (*Out
)[PC
] = std::move(PD
);
2952 void BugReporter::emitReport(std::unique_ptr
<BugReport
> R
) {
2953 bool ValidSourceLoc
= R
->getLocation().isValid();
2954 assert(ValidSourceLoc
);
2955 // If we mess up in a release build, we'd still prefer to just drop the bug
2956 // instead of trying to go on.
2957 if (!ValidSourceLoc
)
2960 // If the user asked to suppress this report, we should skip it.
2961 if (UserSuppressions
.isSuppressed(*R
))
2964 // Compute the bug report's hash to determine its equivalence class.
2965 llvm::FoldingSetNodeID ID
;
2968 // Lookup the equivance class. If there isn't one, create it.
2970 BugReportEquivClass
* EQ
= EQClasses
.FindNodeOrInsertPos(ID
, InsertPos
);
2973 EQ
= new BugReportEquivClass(std::move(R
));
2974 EQClasses
.InsertNode(EQ
, InsertPos
);
2975 EQClassesVector
.push_back(EQ
);
2977 EQ
->AddReport(std::move(R
));
2980 void PathSensitiveBugReporter::emitReport(std::unique_ptr
<BugReport
> R
) {
2981 if (auto PR
= dyn_cast
<PathSensitiveBugReport
>(R
.get()))
2982 if (const ExplodedNode
*E
= PR
->getErrorNode()) {
2983 // An error node must either be a sink or have a tag, otherwise
2984 // it could get reclaimed before the path diagnostic is created.
2985 assert((E
->isSink() || E
->getLocation().getTag()) &&
2986 "Error node must either be a sink or have a tag");
2988 const AnalysisDeclContext
*DeclCtx
=
2989 E
->getLocationContext()->getAnalysisDeclContext();
2990 // The source of autosynthesized body can be handcrafted AST or a model
2991 // file. The locations from handcrafted ASTs have no valid source
2992 // locations and have to be discarded. Locations from model files should
2993 // be preserved for processing and reporting.
2994 if (DeclCtx
->isBodyAutosynthesized() &&
2995 !DeclCtx
->isBodyAutosynthesizedFromModelFile())
2999 BugReporter::emitReport(std::move(R
));
3002 //===----------------------------------------------------------------------===//
3003 // Emitting reports in equivalence classes.
3004 //===----------------------------------------------------------------------===//
3008 struct FRIEC_WLItem
{
3009 const ExplodedNode
*N
;
3010 ExplodedNode::const_succ_iterator I
, E
;
3012 FRIEC_WLItem(const ExplodedNode
*n
)
3013 : N(n
), I(N
->succ_begin()), E(N
->succ_end()) {}
3018 BugReport
*PathSensitiveBugReporter::findReportInEquivalenceClass(
3019 BugReportEquivClass
&EQ
, SmallVectorImpl
<BugReport
*> &bugReports
) {
3020 // If we don't need to suppress any of the nodes because they are
3021 // post-dominated by a sink, simply add all the nodes in the equivalence class
3022 // to 'Nodes'. Any of the reports will serve as a "representative" report.
3023 assert(EQ
.getReports().size() > 0);
3024 const BugType
& BT
= EQ
.getReports()[0]->getBugType();
3025 if (!BT
.isSuppressOnSink()) {
3026 BugReport
*R
= EQ
.getReports()[0].get();
3027 for (auto &J
: EQ
.getReports()) {
3028 if (auto *PR
= dyn_cast
<PathSensitiveBugReport
>(J
.get())) {
3030 bugReports
.push_back(PR
);
3036 // For bug reports that should be suppressed when all paths are post-dominated
3037 // by a sink node, iterate through the reports in the equivalence class
3038 // until we find one that isn't post-dominated (if one exists). We use a
3039 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
3040 // this as a recursive function, but we don't want to risk blowing out the
3041 // stack for very long paths.
3042 BugReport
*exampleReport
= nullptr;
3044 for (const auto &I
: EQ
.getReports()) {
3045 auto *R
= dyn_cast
<PathSensitiveBugReport
>(I
.get());
3049 const ExplodedNode
*errorNode
= R
->getErrorNode();
3050 if (errorNode
->isSink()) {
3052 "BugType::isSuppressSink() should not be 'true' for sink end nodes");
3054 // No successors? By definition this nodes isn't post-dominated by a sink.
3055 if (errorNode
->succ_empty()) {
3056 bugReports
.push_back(R
);
3062 // See if we are in a no-return CFG block. If so, treat this similarly
3063 // to being post-dominated by a sink. This works better when the analysis
3064 // is incomplete and we have never reached the no-return function call(s)
3065 // that we'd inevitably bump into on this path.
3066 if (const CFGBlock
*ErrorB
= errorNode
->getCFGBlock())
3067 if (ErrorB
->isInevitablySinking())
3070 // At this point we know that 'N' is not a sink and it has at least one
3071 // successor. Use a DFS worklist to find a non-sink end-of-path node.
3072 using WLItem
= FRIEC_WLItem
;
3073 using DFSWorkList
= SmallVector
<WLItem
, 10>;
3075 llvm::DenseMap
<const ExplodedNode
*, unsigned> Visited
;
3078 WL
.push_back(errorNode
);
3079 Visited
[errorNode
] = 1;
3081 while (!WL
.empty()) {
3082 WLItem
&WI
= WL
.back();
3083 assert(!WI
.N
->succ_empty());
3085 for (; WI
.I
!= WI
.E
; ++WI
.I
) {
3086 const ExplodedNode
*Succ
= *WI
.I
;
3087 // End-of-path node?
3088 if (Succ
->succ_empty()) {
3089 // If we found an end-of-path node that is not a sink.
3090 if (!Succ
->isSink()) {
3091 bugReports
.push_back(R
);
3097 // Found a sink? Continue on to the next successor.
3100 // Mark the successor as visited. If it hasn't been explored,
3101 // enqueue it to the DFS worklist.
3102 unsigned &mark
= Visited
[Succ
];
3110 // The worklist may have been cleared at this point. First
3111 // check if it is empty before checking the last item.
3112 if (!WL
.empty() && &WL
.back() == &WI
)
3117 // ExampleReport will be NULL if all the nodes in the equivalence class
3118 // were post-dominated by sinks.
3119 return exampleReport
;
3122 void BugReporter::FlushReport(BugReportEquivClass
& EQ
) {
3123 SmallVector
<BugReport
*, 10> bugReports
;
3124 BugReport
*report
= findReportInEquivalenceClass(EQ
, bugReports
);
3128 // See whether we need to silence the checker/package.
3129 for (const std::string
&CheckerOrPackage
:
3130 getAnalyzerOptions().SilencedCheckersAndPackages
) {
3131 if (report
->getBugType().getCheckerName().starts_with(CheckerOrPackage
))
3135 ArrayRef
<PathDiagnosticConsumer
*> Consumers
= getPathDiagnosticConsumers();
3136 std::unique_ptr
<DiagnosticForConsumerMapTy
> Diagnostics
=
3137 generateDiagnosticForConsumerMap(report
, Consumers
, bugReports
);
3139 for (auto &P
: *Diagnostics
) {
3140 PathDiagnosticConsumer
*Consumer
= P
.first
;
3141 std::unique_ptr
<PathDiagnostic
> &PD
= P
.second
;
3143 // If the path is empty, generate a single step path with the location
3145 if (PD
->path
.empty()) {
3146 PathDiagnosticLocation L
= report
->getLocation();
3147 auto piece
= std::make_unique
<PathDiagnosticEventPiece
>(
3148 L
, report
->getDescription());
3149 for (SourceRange Range
: report
->getRanges())
3150 piece
->addRange(Range
);
3151 PD
->setEndOfPath(std::move(piece
));
3154 PathPieces
&Pieces
= PD
->getMutablePieces();
3155 if (getAnalyzerOptions().ShouldDisplayNotesAsEvents
) {
3156 // For path diagnostic consumers that don't support extra notes,
3157 // we may optionally convert those to path notes.
3158 for (const auto &I
: llvm::reverse(report
->getNotes())) {
3159 PathDiagnosticNotePiece
*Piece
= I
.get();
3160 auto ConvertedPiece
= std::make_shared
<PathDiagnosticEventPiece
>(
3161 Piece
->getLocation(), Piece
->getString());
3162 for (const auto &R
: Piece
->getRanges())
3163 ConvertedPiece
->addRange(R
);
3165 Pieces
.push_front(std::move(ConvertedPiece
));
3168 for (const auto &I
: llvm::reverse(report
->getNotes()))
3169 Pieces
.push_front(I
);
3172 for (const auto &I
: report
->getFixits())
3173 Pieces
.back()->addFixit(I
);
3175 updateExecutedLinesWithDiagnosticPieces(*PD
);
3177 // If we are debugging, let's have the entry point as the first note.
3178 if (getAnalyzerOptions().AnalyzerDisplayProgress
||
3179 getAnalyzerOptions().AnalyzerNoteAnalysisEntryPoints
) {
3180 const Decl
*EntryPoint
= getAnalysisEntryPoint();
3181 Pieces
.push_front(std::make_shared
<PathDiagnosticEventPiece
>(
3182 PathDiagnosticLocation
{EntryPoint
->getLocation(), getSourceManager()},
3183 "[debug] analyzing from " +
3184 AnalysisDeclContext::getFunctionName(EntryPoint
)));
3186 Consumer
->HandlePathDiagnostic(std::move(PD
));
3190 /// Insert all lines participating in the function signature \p Signature
3191 /// into \p ExecutedLines.
3192 static void populateExecutedLinesWithFunctionSignature(
3193 const Decl
*Signature
, const SourceManager
&SM
,
3194 FilesToLineNumsMap
&ExecutedLines
) {
3195 SourceRange SignatureSourceRange
;
3196 const Stmt
* Body
= Signature
->getBody();
3197 if (const auto FD
= dyn_cast
<FunctionDecl
>(Signature
)) {
3198 SignatureSourceRange
= FD
->getSourceRange();
3199 } else if (const auto OD
= dyn_cast
<ObjCMethodDecl
>(Signature
)) {
3200 SignatureSourceRange
= OD
->getSourceRange();
3204 SourceLocation Start
= SignatureSourceRange
.getBegin();
3205 SourceLocation End
= Body
? Body
->getSourceRange().getBegin()
3206 : SignatureSourceRange
.getEnd();
3207 if (!Start
.isValid() || !End
.isValid())
3209 unsigned StartLine
= SM
.getExpansionLineNumber(Start
);
3210 unsigned EndLine
= SM
.getExpansionLineNumber(End
);
3212 FileID FID
= SM
.getFileID(SM
.getExpansionLoc(Start
));
3213 for (unsigned Line
= StartLine
; Line
<= EndLine
; Line
++)
3214 ExecutedLines
[FID
].insert(Line
);
3217 static void populateExecutedLinesWithStmt(
3218 const Stmt
*S
, const SourceManager
&SM
,
3219 FilesToLineNumsMap
&ExecutedLines
) {
3220 SourceLocation Loc
= S
->getSourceRange().getBegin();
3223 SourceLocation ExpansionLoc
= SM
.getExpansionLoc(Loc
);
3224 FileID FID
= SM
.getFileID(ExpansionLoc
);
3225 unsigned LineNo
= SM
.getExpansionLineNumber(ExpansionLoc
);
3226 ExecutedLines
[FID
].insert(LineNo
);
3229 /// \return all executed lines including function signatures on the path
3230 /// starting from \p N.
3231 static std::unique_ptr
<FilesToLineNumsMap
>
3232 findExecutedLines(const SourceManager
&SM
, const ExplodedNode
*N
) {
3233 auto ExecutedLines
= std::make_unique
<FilesToLineNumsMap
>();
3236 if (N
->getFirstPred() == nullptr) {
3237 // First node: show signature of the entrance point.
3238 const Decl
*D
= N
->getLocationContext()->getDecl();
3239 populateExecutedLinesWithFunctionSignature(D
, SM
, *ExecutedLines
);
3240 } else if (auto CE
= N
->getLocationAs
<CallEnter
>()) {
3241 // Inlined function: show signature.
3242 const Decl
* D
= CE
->getCalleeContext()->getDecl();
3243 populateExecutedLinesWithFunctionSignature(D
, SM
, *ExecutedLines
);
3244 } else if (const Stmt
*S
= N
->getStmtForDiagnostics()) {
3245 populateExecutedLinesWithStmt(S
, SM
, *ExecutedLines
);
3247 // Show extra context for some parent kinds.
3248 const Stmt
*P
= N
->getParentMap().getParent(S
);
3250 // The path exploration can die before the node with the associated
3251 // return statement is generated, but we do want to show the whole
3253 if (const auto *RS
= dyn_cast_or_null
<ReturnStmt
>(P
)) {
3254 populateExecutedLinesWithStmt(RS
, SM
, *ExecutedLines
);
3255 P
= N
->getParentMap().getParent(RS
);
3258 if (isa_and_nonnull
<SwitchCase
, LabelStmt
>(P
))
3259 populateExecutedLinesWithStmt(P
, SM
, *ExecutedLines
);
3262 N
= N
->getFirstPred();
3264 return ExecutedLines
;
3267 std::unique_ptr
<DiagnosticForConsumerMapTy
>
3268 BugReporter::generateDiagnosticForConsumerMap(
3269 BugReport
*exampleReport
, ArrayRef
<PathDiagnosticConsumer
*> consumers
,
3270 ArrayRef
<BugReport
*> bugReports
) {
3271 auto *basicReport
= cast
<BasicBugReport
>(exampleReport
);
3272 auto Out
= std::make_unique
<DiagnosticForConsumerMapTy
>();
3273 for (auto *Consumer
: consumers
)
3275 generateDiagnosticForBasicReport(basicReport
, AnalysisEntryPoint
);
3279 static PathDiagnosticCallPiece
*
3280 getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece
*CP
,
3281 const SourceManager
&SMgr
) {
3282 SourceLocation CallLoc
= CP
->callEnter
.asLocation();
3284 // If the call is within a macro, don't do anything (for now).
3285 if (CallLoc
.isMacroID())
3288 assert(AnalysisManager::isInCodeFile(CallLoc
, SMgr
) &&
3289 "The call piece should not be in a header file.");
3291 // Check if CP represents a path through a function outside of the main file.
3292 if (!AnalysisManager::isInCodeFile(CP
->callEnterWithin
.asLocation(), SMgr
))
3295 const PathPieces
&Path
= CP
->path
;
3299 // Check if the last piece in the callee path is a call to a function outside
3300 // of the main file.
3301 if (auto *CPInner
= dyn_cast
<PathDiagnosticCallPiece
>(Path
.back().get()))
3302 return getFirstStackedCallToHeaderFile(CPInner
, SMgr
);
3304 // Otherwise, the last piece is in the main file.
3308 static void resetDiagnosticLocationToMainFile(PathDiagnostic
&PD
) {
3309 if (PD
.path
.empty())
3312 PathDiagnosticPiece
*LastP
= PD
.path
.back().get();
3314 const SourceManager
&SMgr
= LastP
->getLocation().getManager();
3316 // We only need to check if the report ends inside headers, if the last piece
3318 if (auto *CP
= dyn_cast
<PathDiagnosticCallPiece
>(LastP
)) {
3319 CP
= getFirstStackedCallToHeaderFile(CP
, SMgr
);
3322 CP
->setAsLastInMainSourceFile();
3324 // Update the path diagnostic message.
3325 const auto *ND
= dyn_cast
<NamedDecl
>(CP
->getCallee());
3327 SmallString
<200> buf
;
3328 llvm::raw_svector_ostream
os(buf
);
3329 os
<< " (within a call to '" << ND
->getDeclName() << "')";
3330 PD
.appendToDesc(os
.str());
3333 // Reset the report containing declaration and location.
3334 PD
.setDeclWithIssue(CP
->getCaller());
3335 PD
.setLocation(CP
->getLocation());
3344 std::unique_ptr
<DiagnosticForConsumerMapTy
>
3345 PathSensitiveBugReporter::generateDiagnosticForConsumerMap(
3346 BugReport
*exampleReport
, ArrayRef
<PathDiagnosticConsumer
*> consumers
,
3347 ArrayRef
<BugReport
*> bugReports
) {
3348 std::vector
<BasicBugReport
*> BasicBugReports
;
3349 std::vector
<PathSensitiveBugReport
*> PathSensitiveBugReports
;
3350 if (isa
<BasicBugReport
>(exampleReport
))
3351 return BugReporter::generateDiagnosticForConsumerMap(exampleReport
,
3352 consumers
, bugReports
);
3354 // Generate the full path sensitive diagnostic, using the generation scheme
3355 // specified by the PathDiagnosticConsumer. Note that we have to generate
3356 // path diagnostics even for consumers which do not support paths, because
3357 // the BugReporterVisitors may mark this bug as a false positive.
3358 assert(!bugReports
.empty());
3359 MaxBugClassSize
.updateMax(bugReports
.size());
3361 // Avoid copying the whole array because there may be a lot of reports.
3362 ArrayRef
<PathSensitiveBugReport
*> convertedArrayOfReports(
3363 reinterpret_cast<PathSensitiveBugReport
*const *>(&*bugReports
.begin()),
3364 reinterpret_cast<PathSensitiveBugReport
*const *>(&*bugReports
.end()));
3365 std::unique_ptr
<DiagnosticForConsumerMapTy
> Out
= generatePathDiagnostics(
3366 consumers
, convertedArrayOfReports
);
3371 MaxValidBugClassSize
.updateMax(bugReports
.size());
3373 // Examine the report and see if the last piece is in a header. Reset the
3374 // report location to the last piece in the main source file.
3375 const AnalyzerOptions
&Opts
= getAnalyzerOptions();
3376 for (auto const &P
: *Out
)
3377 if (Opts
.ShouldReportIssuesInMainSourceFile
&& !Opts
.AnalyzeAll
)
3378 resetDiagnosticLocationToMainFile(*P
.second
);
3383 void BugReporter::EmitBasicReport(const Decl
*DeclWithIssue
,
3384 const CheckerBase
*Checker
, StringRef Name
,
3385 StringRef Category
, StringRef Str
,
3386 PathDiagnosticLocation Loc
,
3387 ArrayRef
<SourceRange
> Ranges
,
3388 ArrayRef
<FixItHint
> Fixits
) {
3389 EmitBasicReport(DeclWithIssue
, Checker
->getCheckerName(), Name
, Category
, Str
,
3390 Loc
, Ranges
, Fixits
);
3393 void BugReporter::EmitBasicReport(const Decl
*DeclWithIssue
,
3394 CheckerNameRef CheckName
,
3395 StringRef name
, StringRef category
,
3396 StringRef str
, PathDiagnosticLocation Loc
,
3397 ArrayRef
<SourceRange
> Ranges
,
3398 ArrayRef
<FixItHint
> Fixits
) {
3399 // 'BT' is owned by BugReporter.
3400 BugType
*BT
= getBugTypeForName(CheckName
, name
, category
);
3401 auto R
= std::make_unique
<BasicBugReport
>(*BT
, str
, Loc
);
3402 R
->setDeclWithIssue(DeclWithIssue
);
3403 for (const auto &SR
: Ranges
)
3405 for (const auto &FH
: Fixits
)
3406 R
->addFixItHint(FH
);
3407 emitReport(std::move(R
));
3410 BugType
*BugReporter::getBugTypeForName(CheckerNameRef CheckName
,
3411 StringRef name
, StringRef category
) {
3412 SmallString
<136> fullDesc
;
3413 llvm::raw_svector_ostream(fullDesc
) << CheckName
.getName() << ":" << name
3415 std::unique_ptr
<BugType
> &BT
= StrBugTypes
[fullDesc
];
3417 BT
= std::make_unique
<BugType
>(CheckName
, name
, category
);