1 //===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the PathDiagnostic-related interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.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/StmtCXX.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
31 bool PathDiagnosticMacroPiece::containsEvent() const {
32 for (PathPieces::const_iterator I = subPieces.begin(), E = subPieces.end();
34 if (isa<PathDiagnosticEventPiece>(*I))
36 if (PathDiagnosticMacroPiece *MP = dyn_cast<PathDiagnosticMacroPiece>(*I))
37 if (MP->containsEvent())
43 static StringRef StripTrailingDots(StringRef s) {
44 for (StringRef::size_type i = s.size(); i != 0; --i)
46 return s.substr(0, i);
50 PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
51 Kind k, DisplayHint hint)
52 : str(StripTrailingDots(s)), kind(k), Hint(hint),
53 LastInMainSourceFile(false) {}
55 PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
56 : kind(k), Hint(hint), LastInMainSourceFile(false) {}
58 PathDiagnosticPiece::~PathDiagnosticPiece() {}
59 PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
60 PathDiagnosticCallPiece::~PathDiagnosticCallPiece() {}
61 PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
62 PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {}
65 PathPieces::~PathPieces() {}
67 void PathPieces::flattenTo(PathPieces &Primary, PathPieces &Current,
68 bool ShouldFlattenMacros) const {
69 for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
70 PathDiagnosticPiece *Piece = I->get();
72 switch (Piece->getKind()) {
73 case PathDiagnosticPiece::Call: {
74 PathDiagnosticCallPiece *Call = cast<PathDiagnosticCallPiece>(Piece);
75 IntrusiveRefCntPtr<PathDiagnosticEventPiece> CallEnter =
76 Call->getCallEnterEvent();
78 Current.push_back(CallEnter);
79 Call->path.flattenTo(Primary, Primary, ShouldFlattenMacros);
80 IntrusiveRefCntPtr<PathDiagnosticEventPiece> callExit =
81 Call->getCallExitEvent();
83 Current.push_back(callExit);
86 case PathDiagnosticPiece::Macro: {
87 PathDiagnosticMacroPiece *Macro = cast<PathDiagnosticMacroPiece>(Piece);
88 if (ShouldFlattenMacros) {
89 Macro->subPieces.flattenTo(Primary, Primary, ShouldFlattenMacros);
91 Current.push_back(Piece);
93 Macro->subPieces.flattenTo(Primary, NewPath, ShouldFlattenMacros);
94 // FIXME: This probably shouldn't mutate the original path piece.
95 Macro->subPieces = NewPath;
99 case PathDiagnosticPiece::Event:
100 case PathDiagnosticPiece::ControlFlow:
101 Current.push_back(Piece);
108 PathDiagnostic::~PathDiagnostic() {}
110 PathDiagnostic::PathDiagnostic(StringRef CheckName, const Decl *declWithIssue,
111 StringRef bugtype, StringRef verboseDesc,
112 StringRef shortDesc, StringRef category,
113 PathDiagnosticLocation LocationToUnique,
114 const Decl *DeclToUnique)
115 : CheckName(CheckName),
116 DeclWithIssue(declWithIssue),
117 BugType(StripTrailingDots(bugtype)),
118 VerboseDesc(StripTrailingDots(verboseDesc)),
119 ShortDesc(StripTrailingDots(shortDesc)),
120 Category(StripTrailingDots(category)),
121 UniqueingLoc(LocationToUnique),
122 UniqueingDecl(DeclToUnique),
125 static PathDiagnosticCallPiece *
126 getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
127 const SourceManager &SMgr) {
128 SourceLocation CallLoc = CP->callEnter.asLocation();
130 // If the call is within a macro, don't do anything (for now).
131 if (CallLoc.isMacroID())
134 assert(SMgr.isInMainFile(CallLoc) &&
135 "The call piece should be in the main file.");
137 // Check if CP represents a path through a function outside of the main file.
138 if (!SMgr.isInMainFile(CP->callEnterWithin.asLocation()))
141 const PathPieces &Path = CP->path;
145 // Check if the last piece in the callee path is a call to a function outside
147 if (PathDiagnosticCallPiece *CPInner =
148 dyn_cast<PathDiagnosticCallPiece>(Path.back())) {
149 return getFirstStackedCallToHeaderFile(CPInner, SMgr);
152 // Otherwise, the last piece is in the main file.
156 void PathDiagnostic::resetDiagnosticLocationToMainFile() {
160 PathDiagnosticPiece *LastP = path.back().get();
162 const SourceManager &SMgr = LastP->getLocation().getManager();
164 // We only need to check if the report ends inside headers, if the last piece
166 if (PathDiagnosticCallPiece *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
167 CP = getFirstStackedCallToHeaderFile(CP, SMgr);
170 CP->setAsLastInMainSourceFile();
172 // Update the path diagnostic message.
173 const NamedDecl *ND = dyn_cast<NamedDecl>(CP->getCallee());
175 SmallString<200> buf;
176 llvm::raw_svector_ostream os(buf);
177 os << " (within a call to '" << ND->getDeclName() << "')";
178 appendToDesc(os.str());
181 // Reset the report containing declaration and location.
182 DeclWithIssue = CP->getCaller();
183 Loc = CP->getLocation();
190 void PathDiagnosticConsumer::anchor() { }
192 PathDiagnosticConsumer::~PathDiagnosticConsumer() {
193 // Delete the contents of the FoldingSet if it isn't empty already.
194 for (llvm::FoldingSet<PathDiagnostic>::iterator it =
195 Diags.begin(), et = Diags.end() ; it != et ; ++it) {
200 void PathDiagnosticConsumer::HandlePathDiagnostic(
201 std::unique_ptr<PathDiagnostic> D) {
202 if (!D || D->path.empty())
205 // We need to flatten the locations (convert Stmt* to locations) because
206 // the referenced statements may be freed by the time the diagnostics
208 D->flattenLocations();
210 // If the PathDiagnosticConsumer does not support diagnostics that
211 // cross file boundaries, prune out such diagnostics now.
212 if (!supportsCrossFileDiagnostics()) {
213 // Verify that the entire path is from the same FileID.
215 const SourceManager &SMgr = D->path.front()->getLocation().getManager();
216 SmallVector<const PathPieces *, 5> WorkList;
217 WorkList.push_back(&D->path);
219 while (!WorkList.empty()) {
220 const PathPieces &path = *WorkList.pop_back_val();
222 for (PathPieces::const_iterator I = path.begin(), E = path.end(); I != E;
224 const PathDiagnosticPiece *piece = I->get();
225 FullSourceLoc L = piece->getLocation().asLocation().getExpansionLoc();
227 if (FID.isInvalid()) {
228 FID = SMgr.getFileID(L);
229 } else if (SMgr.getFileID(L) != FID)
230 return; // FIXME: Emit a warning?
232 // Check the source ranges.
233 ArrayRef<SourceRange> Ranges = piece->getRanges();
234 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
235 E = Ranges.end(); I != E; ++I) {
236 SourceLocation L = SMgr.getExpansionLoc(I->getBegin());
237 if (!L.isFileID() || SMgr.getFileID(L) != FID)
238 return; // FIXME: Emit a warning?
239 L = SMgr.getExpansionLoc(I->getEnd());
240 if (!L.isFileID() || SMgr.getFileID(L) != FID)
241 return; // FIXME: Emit a warning?
244 if (const PathDiagnosticCallPiece *call =
245 dyn_cast<PathDiagnosticCallPiece>(piece)) {
246 WorkList.push_back(&call->path);
248 else if (const PathDiagnosticMacroPiece *macro =
249 dyn_cast<PathDiagnosticMacroPiece>(piece)) {
250 WorkList.push_back(¯o->subPieces);
256 return; // FIXME: Emit a warning?
259 // Profile the node to see if we already have something matching it
260 llvm::FoldingSetNodeID profile;
262 void *InsertPos = nullptr;
264 if (PathDiagnostic *orig = Diags.FindNodeOrInsertPos(profile, InsertPos)) {
265 // Keep the PathDiagnostic with the shorter path.
266 // Note, the enclosing routine is called in deterministic order, so the
267 // results will be consistent between runs (no reason to break ties if the
268 // size is the same).
269 const unsigned orig_size = orig->full_size();
270 const unsigned new_size = D->full_size();
271 if (orig_size <= new_size)
274 assert(orig != D.get());
275 Diags.RemoveNode(orig);
279 Diags.InsertNode(D.release());
282 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y);
283 static Optional<bool>
284 compareControlFlow(const PathDiagnosticControlFlowPiece &X,
285 const PathDiagnosticControlFlowPiece &Y) {
286 FullSourceLoc XSL = X.getStartLocation().asLocation();
287 FullSourceLoc YSL = Y.getStartLocation().asLocation();
289 return XSL.isBeforeInTranslationUnitThan(YSL);
290 FullSourceLoc XEL = X.getEndLocation().asLocation();
291 FullSourceLoc YEL = Y.getEndLocation().asLocation();
293 return XEL.isBeforeInTranslationUnitThan(YEL);
297 static Optional<bool> compareMacro(const PathDiagnosticMacroPiece &X,
298 const PathDiagnosticMacroPiece &Y) {
299 return comparePath(X.subPieces, Y.subPieces);
302 static Optional<bool> compareCall(const PathDiagnosticCallPiece &X,
303 const PathDiagnosticCallPiece &Y) {
304 FullSourceLoc X_CEL = X.callEnter.asLocation();
305 FullSourceLoc Y_CEL = Y.callEnter.asLocation();
307 return X_CEL.isBeforeInTranslationUnitThan(Y_CEL);
308 FullSourceLoc X_CEWL = X.callEnterWithin.asLocation();
309 FullSourceLoc Y_CEWL = Y.callEnterWithin.asLocation();
310 if (X_CEWL != Y_CEWL)
311 return X_CEWL.isBeforeInTranslationUnitThan(Y_CEWL);
312 FullSourceLoc X_CRL = X.callReturn.asLocation();
313 FullSourceLoc Y_CRL = Y.callReturn.asLocation();
315 return X_CRL.isBeforeInTranslationUnitThan(Y_CRL);
316 return comparePath(X.path, Y.path);
319 static Optional<bool> comparePiece(const PathDiagnosticPiece &X,
320 const PathDiagnosticPiece &Y) {
321 if (X.getKind() != Y.getKind())
322 return X.getKind() < Y.getKind();
324 FullSourceLoc XL = X.getLocation().asLocation();
325 FullSourceLoc YL = Y.getLocation().asLocation();
327 return XL.isBeforeInTranslationUnitThan(YL);
329 if (X.getString() != Y.getString())
330 return X.getString() < Y.getString();
332 if (X.getRanges().size() != Y.getRanges().size())
333 return X.getRanges().size() < Y.getRanges().size();
335 const SourceManager &SM = XL.getManager();
337 for (unsigned i = 0, n = X.getRanges().size(); i < n; ++i) {
338 SourceRange XR = X.getRanges()[i];
339 SourceRange YR = Y.getRanges()[i];
341 if (XR.getBegin() != YR.getBegin())
342 return SM.isBeforeInTranslationUnit(XR.getBegin(), YR.getBegin());
343 return SM.isBeforeInTranslationUnit(XR.getEnd(), YR.getEnd());
347 switch (X.getKind()) {
348 case clang::ento::PathDiagnosticPiece::ControlFlow:
349 return compareControlFlow(cast<PathDiagnosticControlFlowPiece>(X),
350 cast<PathDiagnosticControlFlowPiece>(Y));
351 case clang::ento::PathDiagnosticPiece::Event:
353 case clang::ento::PathDiagnosticPiece::Macro:
354 return compareMacro(cast<PathDiagnosticMacroPiece>(X),
355 cast<PathDiagnosticMacroPiece>(Y));
356 case clang::ento::PathDiagnosticPiece::Call:
357 return compareCall(cast<PathDiagnosticCallPiece>(X),
358 cast<PathDiagnosticCallPiece>(Y));
360 llvm_unreachable("all cases handled");
363 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) {
364 if (X.size() != Y.size())
365 return X.size() < Y.size();
367 PathPieces::const_iterator X_I = X.begin(), X_end = X.end();
368 PathPieces::const_iterator Y_I = Y.begin(), Y_end = Y.end();
370 for ( ; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) {
371 Optional<bool> b = comparePiece(**X_I, **Y_I);
379 static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) {
380 FullSourceLoc XL = X.getLocation().asLocation();
381 FullSourceLoc YL = Y.getLocation().asLocation();
383 return XL.isBeforeInTranslationUnitThan(YL);
384 if (X.getBugType() != Y.getBugType())
385 return X.getBugType() < Y.getBugType();
386 if (X.getCategory() != Y.getCategory())
387 return X.getCategory() < Y.getCategory();
388 if (X.getVerboseDescription() != Y.getVerboseDescription())
389 return X.getVerboseDescription() < Y.getVerboseDescription();
390 if (X.getShortDescription() != Y.getShortDescription())
391 return X.getShortDescription() < Y.getShortDescription();
392 if (X.getDeclWithIssue() != Y.getDeclWithIssue()) {
393 const Decl *XD = X.getDeclWithIssue();
396 const Decl *YD = Y.getDeclWithIssue();
399 SourceLocation XDL = XD->getLocation();
400 SourceLocation YDL = YD->getLocation();
402 const SourceManager &SM = XL.getManager();
403 return SM.isBeforeInTranslationUnit(XDL, YDL);
406 PathDiagnostic::meta_iterator XI = X.meta_begin(), XE = X.meta_end();
407 PathDiagnostic::meta_iterator YI = Y.meta_begin(), YE = Y.meta_end();
408 if (XE - XI != YE - YI)
409 return (XE - XI) < (YE - YI);
410 for ( ; XI != XE ; ++XI, ++YI) {
412 return (*XI) < (*YI);
414 Optional<bool> b = comparePath(X.path, Y.path);
415 assert(b.hasValue());
419 void PathDiagnosticConsumer::FlushDiagnostics(
420 PathDiagnosticConsumer::FilesMade *Files) {
426 std::vector<const PathDiagnostic *> BatchDiags;
427 for (llvm::FoldingSet<PathDiagnostic>::iterator it = Diags.begin(),
428 et = Diags.end(); it != et; ++it) {
429 const PathDiagnostic *D = &*it;
430 BatchDiags.push_back(D);
433 // Sort the diagnostics so that they are always emitted in a deterministic
435 if (!BatchDiags.empty())
436 std::sort(BatchDiags.begin(), BatchDiags.end(),
437 [](const PathDiagnostic *X, const PathDiagnostic *Y) {
438 return X != Y && compare(*X, *Y);
441 FlushDiagnosticsImpl(BatchDiags, Files);
443 // Delete the flushed diagnostics.
444 for (std::vector<const PathDiagnostic *>::iterator it = BatchDiags.begin(),
445 et = BatchDiags.end(); it != et; ++it) {
446 const PathDiagnostic *D = *it;
450 // Clear out the FoldingSet.
454 PathDiagnosticConsumer::FilesMade::~FilesMade() {
455 for (PDFileEntry &Entry : *this)
456 Entry.~PDFileEntry();
459 void PathDiagnosticConsumer::FilesMade::addDiagnostic(const PathDiagnostic &PD,
460 StringRef ConsumerName,
461 StringRef FileName) {
462 llvm::FoldingSetNodeID NodeID;
465 PDFileEntry *Entry = FindNodeOrInsertPos(NodeID, InsertPos);
467 Entry = Alloc.Allocate<PDFileEntry>();
468 Entry = new (Entry) PDFileEntry(NodeID);
469 InsertNode(Entry, InsertPos);
472 // Allocate persistent storage for the file name.
473 char *FileName_cstr = (char*) Alloc.Allocate(FileName.size(), 1);
474 memcpy(FileName_cstr, FileName.data(), FileName.size());
476 Entry->files.push_back(std::make_pair(ConsumerName,
477 StringRef(FileName_cstr,
481 PathDiagnosticConsumer::PDFileEntry::ConsumerFiles *
482 PathDiagnosticConsumer::FilesMade::getFiles(const PathDiagnostic &PD) {
483 llvm::FoldingSetNodeID NodeID;
486 PDFileEntry *Entry = FindNodeOrInsertPos(NodeID, InsertPos);
489 return &Entry->files;
492 //===----------------------------------------------------------------------===//
493 // PathDiagnosticLocation methods.
494 //===----------------------------------------------------------------------===//
496 static SourceLocation getValidSourceLocation(const Stmt* S,
497 LocationOrAnalysisDeclContext LAC,
498 bool UseEnd = false) {
499 SourceLocation L = UseEnd ? S->getLocEnd() : S->getLocStart();
500 assert(!LAC.isNull() && "A valid LocationContext or AnalysisDeclContext should "
501 "be passed to PathDiagnosticLocation upon creation.");
503 // S might be a temporary statement that does not have a location in the
504 // source code, so find an enclosing statement and use its location.
507 AnalysisDeclContext *ADC;
508 if (LAC.is<const LocationContext*>())
509 ADC = LAC.get<const LocationContext*>()->getAnalysisDeclContext();
511 ADC = LAC.get<AnalysisDeclContext*>();
513 ParentMap &PM = ADC->getParentMap();
515 const Stmt *Parent = S;
517 Parent = PM.getParent(Parent);
519 // In rare cases, we have implicit top-level expressions,
520 // such as arguments for implicit member initializers.
521 // In this case, fall back to the start of the body (even if we were
522 // asked for the statement end location).
524 const Stmt *Body = ADC->getBody();
526 L = Body->getLocStart();
528 L = ADC->getDecl()->getLocEnd();
532 L = UseEnd ? Parent->getLocEnd() : Parent->getLocStart();
533 } while (!L.isValid());
539 static PathDiagnosticLocation
540 getLocationForCaller(const StackFrameContext *SFC,
541 const LocationContext *CallerCtx,
542 const SourceManager &SM) {
543 const CFGBlock &Block = *SFC->getCallSiteBlock();
544 CFGElement Source = Block[SFC->getIndex()];
546 switch (Source.getKind()) {
547 case CFGElement::Statement:
548 return PathDiagnosticLocation(Source.castAs<CFGStmt>().getStmt(),
550 case CFGElement::Initializer: {
551 const CFGInitializer &Init = Source.castAs<CFGInitializer>();
552 return PathDiagnosticLocation(Init.getInitializer()->getInit(),
555 case CFGElement::AutomaticObjectDtor: {
556 const CFGAutomaticObjDtor &Dtor = Source.castAs<CFGAutomaticObjDtor>();
557 return PathDiagnosticLocation::createEnd(Dtor.getTriggerStmt(),
560 case CFGElement::DeleteDtor: {
561 const CFGDeleteDtor &Dtor = Source.castAs<CFGDeleteDtor>();
562 return PathDiagnosticLocation(Dtor.getDeleteExpr(), SM, CallerCtx);
564 case CFGElement::BaseDtor:
565 case CFGElement::MemberDtor: {
566 const AnalysisDeclContext *CallerInfo = CallerCtx->getAnalysisDeclContext();
567 if (const Stmt *CallerBody = CallerInfo->getBody())
568 return PathDiagnosticLocation::createEnd(CallerBody, SM, CallerCtx);
569 return PathDiagnosticLocation::create(CallerInfo->getDecl(), SM);
571 case CFGElement::TemporaryDtor:
572 case CFGElement::NewAllocator:
573 llvm_unreachable("not yet implemented!");
576 llvm_unreachable("Unknown CFGElement kind");
580 PathDiagnosticLocation
581 PathDiagnosticLocation::createBegin(const Decl *D,
582 const SourceManager &SM) {
583 return PathDiagnosticLocation(D->getLocStart(), SM, SingleLocK);
586 PathDiagnosticLocation
587 PathDiagnosticLocation::createBegin(const Stmt *S,
588 const SourceManager &SM,
589 LocationOrAnalysisDeclContext LAC) {
590 return PathDiagnosticLocation(getValidSourceLocation(S, LAC),
595 PathDiagnosticLocation
596 PathDiagnosticLocation::createEnd(const Stmt *S,
597 const SourceManager &SM,
598 LocationOrAnalysisDeclContext LAC) {
599 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S))
600 return createEndBrace(CS, SM);
601 return PathDiagnosticLocation(getValidSourceLocation(S, LAC, /*End=*/true),
605 PathDiagnosticLocation
606 PathDiagnosticLocation::createOperatorLoc(const BinaryOperator *BO,
607 const SourceManager &SM) {
608 return PathDiagnosticLocation(BO->getOperatorLoc(), SM, SingleLocK);
611 PathDiagnosticLocation
612 PathDiagnosticLocation::createConditionalColonLoc(
613 const ConditionalOperator *CO,
614 const SourceManager &SM) {
615 return PathDiagnosticLocation(CO->getColonLoc(), SM, SingleLocK);
619 PathDiagnosticLocation
620 PathDiagnosticLocation::createMemberLoc(const MemberExpr *ME,
621 const SourceManager &SM) {
622 return PathDiagnosticLocation(ME->getMemberLoc(), SM, SingleLocK);
625 PathDiagnosticLocation
626 PathDiagnosticLocation::createBeginBrace(const CompoundStmt *CS,
627 const SourceManager &SM) {
628 SourceLocation L = CS->getLBracLoc();
629 return PathDiagnosticLocation(L, SM, SingleLocK);
632 PathDiagnosticLocation
633 PathDiagnosticLocation::createEndBrace(const CompoundStmt *CS,
634 const SourceManager &SM) {
635 SourceLocation L = CS->getRBracLoc();
636 return PathDiagnosticLocation(L, SM, SingleLocK);
639 PathDiagnosticLocation
640 PathDiagnosticLocation::createDeclBegin(const LocationContext *LC,
641 const SourceManager &SM) {
642 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
643 if (const CompoundStmt *CS =
644 dyn_cast_or_null<CompoundStmt>(LC->getDecl()->getBody()))
645 if (!CS->body_empty()) {
646 SourceLocation Loc = (*CS->body_begin())->getLocStart();
647 return PathDiagnosticLocation(Loc, SM, SingleLocK);
650 return PathDiagnosticLocation();
653 PathDiagnosticLocation
654 PathDiagnosticLocation::createDeclEnd(const LocationContext *LC,
655 const SourceManager &SM) {
656 SourceLocation L = LC->getDecl()->getBodyRBrace();
657 return PathDiagnosticLocation(L, SM, SingleLocK);
660 PathDiagnosticLocation
661 PathDiagnosticLocation::create(const ProgramPoint& P,
662 const SourceManager &SMng) {
664 const Stmt* S = nullptr;
665 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
666 const CFGBlock *BSrc = BE->getSrc();
667 S = BSrc->getTerminatorCondition();
668 } else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>()) {
670 if (P.getAs<PostStmtPurgeDeadSymbols>())
671 return PathDiagnosticLocation::createEnd(S, SMng, P.getLocationContext());
672 } else if (Optional<PostInitializer> PIP = P.getAs<PostInitializer>()) {
673 return PathDiagnosticLocation(PIP->getInitializer()->getSourceLocation(),
675 } else if (Optional<PostImplicitCall> PIE = P.getAs<PostImplicitCall>()) {
676 return PathDiagnosticLocation(PIE->getLocation(), SMng);
677 } else if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
678 return getLocationForCaller(CE->getCalleeContext(),
679 CE->getLocationContext(),
681 } else if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) {
682 return getLocationForCaller(CEE->getCalleeContext(),
683 CEE->getLocationContext(),
686 llvm_unreachable("Unexpected ProgramPoint");
689 return PathDiagnosticLocation(S, SMng, P.getLocationContext());
692 const Stmt *PathDiagnosticLocation::getStmt(const ExplodedNode *N) {
693 ProgramPoint P = N->getLocation();
694 if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
695 return SP->getStmt();
696 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>())
697 return BE->getSrc()->getTerminator();
698 if (Optional<CallEnter> CE = P.getAs<CallEnter>())
699 return CE->getCallExpr();
700 if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>())
701 return CEE->getCalleeContext()->getCallSite();
702 if (Optional<PostInitializer> PIPP = P.getAs<PostInitializer>())
703 return PIPP->getInitializer()->getInit();
708 const Stmt *PathDiagnosticLocation::getNextStmt(const ExplodedNode *N) {
709 for (N = N->getFirstSucc(); N; N = N->getFirstSucc()) {
710 if (const Stmt *S = getStmt(N)) {
711 // Check if the statement is '?' or '&&'/'||'. These are "merges",
712 // not actual statement points.
713 switch (S->getStmtClass()) {
714 case Stmt::ChooseExprClass:
715 case Stmt::BinaryConditionalOperatorClass:
716 case Stmt::ConditionalOperatorClass:
718 case Stmt::BinaryOperatorClass: {
719 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
720 if (Op == BO_LAnd || Op == BO_LOr)
727 // We found the statement, so return it.
735 PathDiagnosticLocation
736 PathDiagnosticLocation::createEndOfPath(const ExplodedNode *N,
737 const SourceManager &SM) {
738 assert(N && "Cannot create a location with a null node.");
739 const Stmt *S = getStmt(N);
742 // If this is an implicit call, return the implicit call point location.
743 if (Optional<PreImplicitCall> PIE = N->getLocationAs<PreImplicitCall>())
744 return PathDiagnosticLocation(PIE->getLocation(), SM);
749 ProgramPoint P = N->getLocation();
750 const LocationContext *LC = N->getLocationContext();
752 // For member expressions, return the location of the '.' or '->'.
753 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
754 return PathDiagnosticLocation::createMemberLoc(ME, SM);
756 // For binary operators, return the location of the operator.
757 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
758 return PathDiagnosticLocation::createOperatorLoc(B, SM);
760 if (P.getAs<PostStmtPurgeDeadSymbols>())
761 return PathDiagnosticLocation::createEnd(S, SM, LC);
763 if (S->getLocStart().isValid())
764 return PathDiagnosticLocation(S, SM, LC);
765 return PathDiagnosticLocation(getValidSourceLocation(S, LC), SM);
768 return createDeclEnd(N->getLocationContext(), SM);
771 PathDiagnosticLocation PathDiagnosticLocation::createSingleLocation(
772 const PathDiagnosticLocation &PDL) {
773 FullSourceLoc L = PDL.asLocation();
774 return PathDiagnosticLocation(L, L.getManager(), SingleLocK);
778 PathDiagnosticLocation::genLocation(SourceLocation L,
779 LocationOrAnalysisDeclContext LAC) const {
781 // Note that we want a 'switch' here so that the compiler can warn us in
782 // case we add more cases.
788 // Defensive checking.
791 return FullSourceLoc(getValidSourceLocation(S, LAC),
792 const_cast<SourceManager&>(*SM));
794 // Defensive checking.
797 return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
800 return FullSourceLoc(L, const_cast<SourceManager&>(*SM));
804 PathDiagnosticLocation::genRange(LocationOrAnalysisDeclContext LAC) const {
806 // Note that we want a 'switch' here so that the compiler can warn us in
807 // case we add more cases.
810 return PathDiagnosticRange(SourceRange(Loc,Loc), true);
814 const Stmt *S = asStmt();
815 switch (S->getStmtClass()) {
818 case Stmt::DeclStmtClass: {
819 const DeclStmt *DS = cast<DeclStmt>(S);
820 if (DS->isSingleDecl()) {
821 // Should always be the case, but we'll be defensive.
822 return SourceRange(DS->getLocStart(),
823 DS->getSingleDecl()->getLocation());
827 // FIXME: Provide better range information for different
829 case Stmt::IfStmtClass:
830 case Stmt::WhileStmtClass:
831 case Stmt::DoStmtClass:
832 case Stmt::ForStmtClass:
833 case Stmt::ChooseExprClass:
834 case Stmt::IndirectGotoStmtClass:
835 case Stmt::SwitchStmtClass:
836 case Stmt::BinaryConditionalOperatorClass:
837 case Stmt::ConditionalOperatorClass:
838 case Stmt::ObjCForCollectionStmtClass: {
839 SourceLocation L = getValidSourceLocation(S, LAC);
840 return SourceRange(L, L);
843 SourceRange R = S->getSourceRange();
849 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
850 return MD->getSourceRange();
851 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
852 if (Stmt *Body = FD->getBody())
853 return Body->getSourceRange();
856 SourceLocation L = D->getLocation();
857 return PathDiagnosticRange(SourceRange(L, L), true);
861 return SourceRange(Loc,Loc);
864 void PathDiagnosticLocation::flatten() {
870 else if (K == DeclK) {
877 //===----------------------------------------------------------------------===//
878 // Manipulation of PathDiagnosticCallPieces.
879 //===----------------------------------------------------------------------===//
881 PathDiagnosticCallPiece *
882 PathDiagnosticCallPiece::construct(const ExplodedNode *N,
883 const CallExitEnd &CE,
884 const SourceManager &SM) {
885 const Decl *caller = CE.getLocationContext()->getDecl();
886 PathDiagnosticLocation pos = getLocationForCaller(CE.getCalleeContext(),
887 CE.getLocationContext(),
889 return new PathDiagnosticCallPiece(caller, pos);
892 PathDiagnosticCallPiece *
893 PathDiagnosticCallPiece::construct(PathPieces &path,
894 const Decl *caller) {
895 PathDiagnosticCallPiece *C = new PathDiagnosticCallPiece(path, caller);
901 void PathDiagnosticCallPiece::setCallee(const CallEnter &CE,
902 const SourceManager &SM) {
903 const StackFrameContext *CalleeCtx = CE.getCalleeContext();
904 Callee = CalleeCtx->getDecl();
906 callEnterWithin = PathDiagnosticLocation::createBegin(Callee, SM);
907 callEnter = getLocationForCaller(CalleeCtx, CE.getLocationContext(), SM);
910 static inline void describeClass(raw_ostream &Out, const CXXRecordDecl *D,
911 StringRef Prefix = StringRef()) {
912 if (!D->getIdentifier())
914 Out << Prefix << '\'' << *D << '\'';
917 static bool describeCodeDecl(raw_ostream &Out, const Decl *D,
918 bool ExtendedDescription,
919 StringRef Prefix = StringRef()) {
923 if (isa<BlockDecl>(D)) {
924 if (ExtendedDescription)
925 Out << Prefix << "anonymous block";
926 return ExtendedDescription;
929 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
931 if (ExtendedDescription && !MD->isUserProvided()) {
932 if (MD->isExplicitlyDefaulted())
938 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD)) {
939 if (CD->isDefaultConstructor())
941 else if (CD->isCopyConstructor())
943 else if (CD->isMoveConstructor())
946 Out << "constructor";
947 describeClass(Out, MD->getParent(), " for ");
949 } else if (isa<CXXDestructorDecl>(MD)) {
950 if (!MD->isUserProvided()) {
952 describeClass(Out, MD->getParent(), " for ");
954 // Use ~Foo for explicitly-written destructors.
955 Out << "'" << *MD << "'";
958 } else if (MD->isCopyAssignmentOperator()) {
959 Out << "copy assignment operator";
960 describeClass(Out, MD->getParent(), " for ");
962 } else if (MD->isMoveAssignmentOperator()) {
963 Out << "move assignment operator";
964 describeClass(Out, MD->getParent(), " for ");
967 if (MD->getParent()->getIdentifier())
968 Out << "'" << *MD->getParent() << "::" << *MD << "'";
970 Out << "'" << *MD << "'";
976 Out << Prefix << '\'' << cast<NamedDecl>(*D) << '\'';
980 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
981 PathDiagnosticCallPiece::getCallEnterEvent() const {
985 SmallString<256> buf;
986 llvm::raw_svector_ostream Out(buf);
989 describeCodeDecl(Out, Callee, /*ExtendedDescription=*/true);
991 assert(callEnter.asLocation().isValid());
992 return new PathDiagnosticEventPiece(callEnter, Out.str());
995 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
996 PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
997 if (!callEnterWithin.asLocation().isValid())
999 if (Callee->isImplicit() || !Callee->hasBody())
1001 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee))
1002 if (MD->isDefaulted())
1005 SmallString<256> buf;
1006 llvm::raw_svector_ostream Out(buf);
1008 Out << "Entered call";
1009 describeCodeDecl(Out, Caller, /*ExtendedDescription=*/false, " from ");
1011 return new PathDiagnosticEventPiece(callEnterWithin, Out.str());
1014 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
1015 PathDiagnosticCallPiece::getCallExitEvent() const {
1019 SmallString<256> buf;
1020 llvm::raw_svector_ostream Out(buf);
1022 if (!CallStackMessage.empty()) {
1023 Out << CallStackMessage;
1025 bool DidDescribe = describeCodeDecl(Out, Callee,
1026 /*ExtendedDescription=*/false,
1029 Out << "Returning to caller";
1032 assert(callReturn.asLocation().isValid());
1033 return new PathDiagnosticEventPiece(callReturn, Out.str());
1036 static void compute_path_size(const PathPieces &pieces, unsigned &size) {
1037 for (PathPieces::const_iterator it = pieces.begin(),
1038 et = pieces.end(); it != et; ++it) {
1039 const PathDiagnosticPiece *piece = it->get();
1040 if (const PathDiagnosticCallPiece *cp =
1041 dyn_cast<PathDiagnosticCallPiece>(piece)) {
1042 compute_path_size(cp->path, size);
1049 unsigned PathDiagnostic::full_size() {
1051 compute_path_size(path, size);
1055 //===----------------------------------------------------------------------===//
1056 // FoldingSet profiling methods.
1057 //===----------------------------------------------------------------------===//
1059 void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
1060 ID.AddInteger(Range.getBegin().getRawEncoding());
1061 ID.AddInteger(Range.getEnd().getRawEncoding());
1062 ID.AddInteger(Loc.getRawEncoding());
1066 void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1067 ID.AddInteger((unsigned) getKind());
1069 // FIXME: Add profiling support for code hints.
1070 ID.AddInteger((unsigned) getDisplayHint());
1071 ArrayRef<SourceRange> Ranges = getRanges();
1072 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
1074 ID.AddInteger(I->getBegin().getRawEncoding());
1075 ID.AddInteger(I->getEnd().getRawEncoding());
1079 void PathDiagnosticCallPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1080 PathDiagnosticPiece::Profile(ID);
1081 for (PathPieces::const_iterator it = path.begin(),
1082 et = path.end(); it != et; ++it) {
1087 void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1088 PathDiagnosticPiece::Profile(ID);
1092 void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1093 PathDiagnosticPiece::Profile(ID);
1094 for (const_iterator I = begin(), E = end(); I != E; ++I)
1098 void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1099 PathDiagnosticSpotPiece::Profile(ID);
1100 for (PathPieces::const_iterator I = subPieces.begin(), E = subPieces.end();
1105 void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
1106 ID.Add(getLocation());
1107 ID.AddString(BugType);
1108 ID.AddString(VerboseDesc);
1109 ID.AddString(Category);
1112 void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID &ID) const {
1114 for (PathPieces::const_iterator I = path.begin(), E = path.end(); I != E; ++I)
1116 for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
1120 StackHintGenerator::~StackHintGenerator() {}
1122 std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
1123 ProgramPoint P = N->getLocation();
1124 CallExitEnd CExit = P.castAs<CallExitEnd>();
1126 // FIXME: Use CallEvent to abstract this over all calls.
1127 const Stmt *CallSite = CExit.getCalleeContext()->getCallSite();
1128 const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite);
1133 return getMessageForSymbolNotFound();
1135 // Check if one of the parameters are set to the interesting symbol.
1136 ProgramStateRef State = N->getState();
1137 const LocationContext *LCtx = N->getLocationContext();
1138 unsigned ArgIndex = 0;
1139 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1140 E = CE->arg_end(); I != E; ++I, ++ArgIndex){
1141 SVal SV = State->getSVal(*I, LCtx);
1143 // Check if the variable corresponding to the symbol is passed by value.
1144 SymbolRef AS = SV.getAsLocSymbol();
1146 return getMessageForArg(*I, ArgIndex);
1149 // Check if the parameter is a pointer to the symbol.
1150 if (Optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
1151 SVal PSV = State->getSVal(Reg->getRegion());
1152 SymbolRef AS = PSV.getAsLocSymbol();
1154 return getMessageForArg(*I, ArgIndex);
1159 // Check if we are returning the interesting symbol.
1160 SVal SV = State->getSVal(CE, LCtx);
1161 SymbolRef RetSym = SV.getAsLocSymbol();
1162 if (RetSym == Sym) {
1163 return getMessageForReturn(CE);
1166 return getMessageForSymbolNotFound();
1169 std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
1170 unsigned ArgIndex) {
1171 // Printed parameters start at 1, not 0.
1174 SmallString<200> buf;
1175 llvm::raw_svector_ostream os(buf);
1177 os << Msg << " via " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)