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