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/ParentMap.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
30 bool PathDiagnosticMacroPiece::containsEvent() const {
31 for (PathPieces::const_iterator I = subPieces.begin(), E = subPieces.end();
33 if (isa<PathDiagnosticEventPiece>(*I))
35 if (PathDiagnosticMacroPiece *MP = dyn_cast<PathDiagnosticMacroPiece>(*I))
36 if (MP->containsEvent())
42 static StringRef StripTrailingDots(StringRef s) {
43 for (StringRef::size_type i = s.size(); i != 0; --i)
45 return s.substr(0, i);
49 PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
50 Kind k, DisplayHint hint)
51 : str(StripTrailingDots(s)), kind(k), Hint(hint) {}
53 PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
54 : kind(k), Hint(hint) {}
56 PathDiagnosticPiece::~PathDiagnosticPiece() {}
57 PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
58 PathDiagnosticCallPiece::~PathDiagnosticCallPiece() {}
59 PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
60 PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {}
63 PathPieces::~PathPieces() {}
65 void PathPieces::flattenTo(PathPieces &Primary, PathPieces &Current,
66 bool ShouldFlattenMacros) const {
67 for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
68 PathDiagnosticPiece *Piece = I->getPtr();
70 switch (Piece->getKind()) {
71 case PathDiagnosticPiece::Call: {
72 PathDiagnosticCallPiece *Call = cast<PathDiagnosticCallPiece>(Piece);
73 IntrusiveRefCntPtr<PathDiagnosticEventPiece> CallEnter =
74 Call->getCallEnterEvent();
76 Current.push_back(CallEnter);
77 Call->path.flattenTo(Primary, Primary, ShouldFlattenMacros);
78 IntrusiveRefCntPtr<PathDiagnosticEventPiece> callExit =
79 Call->getCallExitEvent();
81 Current.push_back(callExit);
84 case PathDiagnosticPiece::Macro: {
85 PathDiagnosticMacroPiece *Macro = cast<PathDiagnosticMacroPiece>(Piece);
86 if (ShouldFlattenMacros) {
87 Macro->subPieces.flattenTo(Primary, Primary, ShouldFlattenMacros);
89 Current.push_back(Piece);
91 Macro->subPieces.flattenTo(Primary, NewPath, ShouldFlattenMacros);
92 // FIXME: This probably shouldn't mutate the original path piece.
93 Macro->subPieces = NewPath;
97 case PathDiagnosticPiece::Event:
98 case PathDiagnosticPiece::ControlFlow:
99 Current.push_back(Piece);
106 PathDiagnostic::~PathDiagnostic() {}
108 PathDiagnostic::PathDiagnostic(const Decl *declWithIssue,
109 StringRef bugtype, StringRef verboseDesc,
110 StringRef shortDesc, StringRef category,
111 PathDiagnosticLocation LocationToUnique,
112 const Decl *DeclToUnique)
113 : DeclWithIssue(declWithIssue),
114 BugType(StripTrailingDots(bugtype)),
115 VerboseDesc(StripTrailingDots(verboseDesc)),
116 ShortDesc(StripTrailingDots(shortDesc)),
117 Category(StripTrailingDots(category)),
118 UniqueingLoc(LocationToUnique),
119 UniqueingDecl(DeclToUnique),
122 void PathDiagnosticConsumer::anchor() { }
124 PathDiagnosticConsumer::~PathDiagnosticConsumer() {
125 // Delete the contents of the FoldingSet if it isn't empty already.
126 for (llvm::FoldingSet<PathDiagnostic>::iterator it =
127 Diags.begin(), et = Diags.end() ; it != et ; ++it) {
132 void PathDiagnosticConsumer::HandlePathDiagnostic(PathDiagnostic *D) {
133 OwningPtr<PathDiagnostic> OwningD(D);
135 if (!D || D->path.empty())
138 // We need to flatten the locations (convert Stmt* to locations) because
139 // the referenced statements may be freed by the time the diagnostics
141 D->flattenLocations();
143 // If the PathDiagnosticConsumer does not support diagnostics that
144 // cross file boundaries, prune out such diagnostics now.
145 if (!supportsCrossFileDiagnostics()) {
146 // Verify that the entire path is from the same FileID.
148 const SourceManager &SMgr = (*D->path.begin())->getLocation().getManager();
149 SmallVector<const PathPieces *, 5> WorkList;
150 WorkList.push_back(&D->path);
152 while (!WorkList.empty()) {
153 const PathPieces &path = *WorkList.back();
156 for (PathPieces::const_iterator I = path.begin(), E = path.end();
158 const PathDiagnosticPiece *piece = I->getPtr();
159 FullSourceLoc L = piece->getLocation().asLocation().getExpansionLoc();
161 if (FID.isInvalid()) {
162 FID = SMgr.getFileID(L);
163 } else if (SMgr.getFileID(L) != FID)
164 return; // FIXME: Emit a warning?
166 // Check the source ranges.
167 ArrayRef<SourceRange> Ranges = piece->getRanges();
168 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
169 E = Ranges.end(); I != E; ++I) {
170 SourceLocation L = SMgr.getExpansionLoc(I->getBegin());
171 if (!L.isFileID() || SMgr.getFileID(L) != FID)
172 return; // FIXME: Emit a warning?
173 L = SMgr.getExpansionLoc(I->getEnd());
174 if (!L.isFileID() || SMgr.getFileID(L) != FID)
175 return; // FIXME: Emit a warning?
178 if (const PathDiagnosticCallPiece *call =
179 dyn_cast<PathDiagnosticCallPiece>(piece)) {
180 WorkList.push_back(&call->path);
182 else if (const PathDiagnosticMacroPiece *macro =
183 dyn_cast<PathDiagnosticMacroPiece>(piece)) {
184 WorkList.push_back(¯o->subPieces);
190 return; // FIXME: Emit a warning?
193 // Profile the node to see if we already have something matching it
194 llvm::FoldingSetNodeID profile;
198 if (PathDiagnostic *orig = Diags.FindNodeOrInsertPos(profile, InsertPos)) {
199 // Keep the PathDiagnostic with the shorter path.
200 // Note, the enclosing routine is called in deterministic order, so the
201 // results will be consistent between runs (no reason to break ties if the
202 // size is the same).
203 const unsigned orig_size = orig->full_size();
204 const unsigned new_size = D->full_size();
205 if (orig_size <= new_size)
209 Diags.RemoveNode(orig);
213 Diags.InsertNode(OwningD.take());
216 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y);
217 static Optional<bool>
218 compareControlFlow(const PathDiagnosticControlFlowPiece &X,
219 const PathDiagnosticControlFlowPiece &Y) {
220 FullSourceLoc XSL = X.getStartLocation().asLocation();
221 FullSourceLoc YSL = Y.getStartLocation().asLocation();
223 return XSL.isBeforeInTranslationUnitThan(YSL);
224 FullSourceLoc XEL = X.getEndLocation().asLocation();
225 FullSourceLoc YEL = Y.getEndLocation().asLocation();
227 return XEL.isBeforeInTranslationUnitThan(YEL);
231 static Optional<bool> compareMacro(const PathDiagnosticMacroPiece &X,
232 const PathDiagnosticMacroPiece &Y) {
233 return comparePath(X.subPieces, Y.subPieces);
236 static Optional<bool> compareCall(const PathDiagnosticCallPiece &X,
237 const PathDiagnosticCallPiece &Y) {
238 FullSourceLoc X_CEL = X.callEnter.asLocation();
239 FullSourceLoc Y_CEL = Y.callEnter.asLocation();
241 return X_CEL.isBeforeInTranslationUnitThan(Y_CEL);
242 FullSourceLoc X_CEWL = X.callEnterWithin.asLocation();
243 FullSourceLoc Y_CEWL = Y.callEnterWithin.asLocation();
244 if (X_CEWL != Y_CEWL)
245 return X_CEWL.isBeforeInTranslationUnitThan(Y_CEWL);
246 FullSourceLoc X_CRL = X.callReturn.asLocation();
247 FullSourceLoc Y_CRL = Y.callReturn.asLocation();
249 return X_CRL.isBeforeInTranslationUnitThan(Y_CRL);
250 return comparePath(X.path, Y.path);
253 static Optional<bool> comparePiece(const PathDiagnosticPiece &X,
254 const PathDiagnosticPiece &Y) {
255 if (X.getKind() != Y.getKind())
256 return X.getKind() < Y.getKind();
258 FullSourceLoc XL = X.getLocation().asLocation();
259 FullSourceLoc YL = Y.getLocation().asLocation();
261 return XL.isBeforeInTranslationUnitThan(YL);
263 if (X.getString() != Y.getString())
264 return X.getString() < Y.getString();
266 if (X.getRanges().size() != Y.getRanges().size())
267 return X.getRanges().size() < Y.getRanges().size();
269 const SourceManager &SM = XL.getManager();
271 for (unsigned i = 0, n = X.getRanges().size(); i < n; ++i) {
272 SourceRange XR = X.getRanges()[i];
273 SourceRange YR = Y.getRanges()[i];
275 if (XR.getBegin() != YR.getBegin())
276 return SM.isBeforeInTranslationUnit(XR.getBegin(), YR.getBegin());
277 return SM.isBeforeInTranslationUnit(XR.getEnd(), YR.getEnd());
281 switch (X.getKind()) {
282 case clang::ento::PathDiagnosticPiece::ControlFlow:
283 return compareControlFlow(cast<PathDiagnosticControlFlowPiece>(X),
284 cast<PathDiagnosticControlFlowPiece>(Y));
285 case clang::ento::PathDiagnosticPiece::Event:
287 case clang::ento::PathDiagnosticPiece::Macro:
288 return compareMacro(cast<PathDiagnosticMacroPiece>(X),
289 cast<PathDiagnosticMacroPiece>(Y));
290 case clang::ento::PathDiagnosticPiece::Call:
291 return compareCall(cast<PathDiagnosticCallPiece>(X),
292 cast<PathDiagnosticCallPiece>(Y));
294 llvm_unreachable("all cases handled");
297 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) {
298 if (X.size() != Y.size())
299 return X.size() < Y.size();
300 for (unsigned i = 0, n = X.size(); i != n; ++i) {
301 Optional<bool> b = comparePiece(*X[i], *Y[i]);
308 static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) {
309 FullSourceLoc XL = X.getLocation().asLocation();
310 FullSourceLoc YL = Y.getLocation().asLocation();
312 return XL.isBeforeInTranslationUnitThan(YL);
313 if (X.getBugType() != Y.getBugType())
314 return X.getBugType() < Y.getBugType();
315 if (X.getCategory() != Y.getCategory())
316 return X.getCategory() < Y.getCategory();
317 if (X.getVerboseDescription() != Y.getVerboseDescription())
318 return X.getVerboseDescription() < Y.getVerboseDescription();
319 if (X.getShortDescription() != Y.getShortDescription())
320 return X.getShortDescription() < Y.getShortDescription();
321 if (X.getDeclWithIssue() != Y.getDeclWithIssue()) {
322 const Decl *XD = X.getDeclWithIssue();
325 const Decl *YD = Y.getDeclWithIssue();
328 SourceLocation XDL = XD->getLocation();
329 SourceLocation YDL = YD->getLocation();
331 const SourceManager &SM = XL.getManager();
332 return SM.isBeforeInTranslationUnit(XDL, YDL);
335 PathDiagnostic::meta_iterator XI = X.meta_begin(), XE = X.meta_end();
336 PathDiagnostic::meta_iterator YI = Y.meta_begin(), YE = Y.meta_end();
337 if (XE - XI != YE - YI)
338 return (XE - XI) < (YE - YI);
339 for ( ; XI != XE ; ++XI, ++YI) {
341 return (*XI) < (*YI);
343 Optional<bool> b = comparePath(X.path, Y.path);
344 assert(b.hasValue());
349 struct CompareDiagnostics {
350 // Compare if 'X' is "<" than 'Y'.
351 bool operator()(const PathDiagnostic *X, const PathDiagnostic *Y) const {
354 return compare(*X, *Y);
359 void PathDiagnosticConsumer::FlushDiagnostics(
360 PathDiagnosticConsumer::FilesMade *Files) {
366 std::vector<const PathDiagnostic *> BatchDiags;
367 for (llvm::FoldingSet<PathDiagnostic>::iterator it = Diags.begin(),
368 et = Diags.end(); it != et; ++it) {
369 const PathDiagnostic *D = &*it;
370 BatchDiags.push_back(D);
373 // Sort the diagnostics so that they are always emitted in a deterministic
375 if (!BatchDiags.empty())
376 std::sort(BatchDiags.begin(), BatchDiags.end(), CompareDiagnostics());
378 FlushDiagnosticsImpl(BatchDiags, Files);
380 // Delete the flushed diagnostics.
381 for (std::vector<const PathDiagnostic *>::iterator it = BatchDiags.begin(),
382 et = BatchDiags.end(); it != et; ++it) {
383 const PathDiagnostic *D = *it;
387 // Clear out the FoldingSet.
391 void PathDiagnosticConsumer::FilesMade::addDiagnostic(const PathDiagnostic &PD,
392 StringRef ConsumerName,
393 StringRef FileName) {
394 llvm::FoldingSetNodeID NodeID;
397 PDFileEntry *Entry = FindNodeOrInsertPos(NodeID, InsertPos);
399 Entry = Alloc.Allocate<PDFileEntry>();
400 Entry = new (Entry) PDFileEntry(NodeID);
401 InsertNode(Entry, InsertPos);
404 // Allocate persistent storage for the file name.
405 char *FileName_cstr = (char*) Alloc.Allocate(FileName.size(), 1);
406 memcpy(FileName_cstr, FileName.data(), FileName.size());
408 Entry->files.push_back(std::make_pair(ConsumerName,
409 StringRef(FileName_cstr,
413 PathDiagnosticConsumer::PDFileEntry::ConsumerFiles *
414 PathDiagnosticConsumer::FilesMade::getFiles(const PathDiagnostic &PD) {
415 llvm::FoldingSetNodeID NodeID;
418 PDFileEntry *Entry = FindNodeOrInsertPos(NodeID, InsertPos);
421 return &Entry->files;
424 //===----------------------------------------------------------------------===//
425 // PathDiagnosticLocation methods.
426 //===----------------------------------------------------------------------===//
428 static SourceLocation getValidSourceLocation(const Stmt* S,
429 LocationOrAnalysisDeclContext LAC,
430 bool UseEnd = false) {
431 SourceLocation L = UseEnd ? S->getLocEnd() : S->getLocStart();
432 assert(!LAC.isNull() && "A valid LocationContext or AnalysisDeclContext should "
433 "be passed to PathDiagnosticLocation upon creation.");
435 // S might be a temporary statement that does not have a location in the
436 // source code, so find an enclosing statement and use its location.
439 AnalysisDeclContext *ADC;
440 if (LAC.is<const LocationContext*>())
441 ADC = LAC.get<const LocationContext*>()->getAnalysisDeclContext();
443 ADC = LAC.get<AnalysisDeclContext*>();
445 ParentMap &PM = ADC->getParentMap();
447 const Stmt *Parent = S;
449 Parent = PM.getParent(Parent);
451 // In rare cases, we have implicit top-level expressions,
452 // such as arguments for implicit member initializers.
453 // In this case, fall back to the start of the body (even if we were
454 // asked for the statement end location).
456 const Stmt *Body = ADC->getBody();
458 L = Body->getLocStart();
460 L = ADC->getDecl()->getLocEnd();
464 L = UseEnd ? Parent->getLocEnd() : Parent->getLocStart();
465 } while (!L.isValid());
471 static PathDiagnosticLocation
472 getLocationForCaller(const StackFrameContext *SFC,
473 const LocationContext *CallerCtx,
474 const SourceManager &SM) {
475 const CFGBlock &Block = *SFC->getCallSiteBlock();
476 CFGElement Source = Block[SFC->getIndex()];
478 switch (Source.getKind()) {
479 case CFGElement::Statement:
480 return PathDiagnosticLocation(Source.castAs<CFGStmt>().getStmt(),
482 case CFGElement::Initializer: {
483 const CFGInitializer &Init = Source.castAs<CFGInitializer>();
484 return PathDiagnosticLocation(Init.getInitializer()->getInit(),
487 case CFGElement::AutomaticObjectDtor: {
488 const CFGAutomaticObjDtor &Dtor = Source.castAs<CFGAutomaticObjDtor>();
489 return PathDiagnosticLocation::createEnd(Dtor.getTriggerStmt(),
492 case CFGElement::BaseDtor:
493 case CFGElement::MemberDtor: {
494 const AnalysisDeclContext *CallerInfo = CallerCtx->getAnalysisDeclContext();
495 if (const Stmt *CallerBody = CallerInfo->getBody())
496 return PathDiagnosticLocation::createEnd(CallerBody, SM, CallerCtx);
497 return PathDiagnosticLocation::create(CallerInfo->getDecl(), SM);
499 case CFGElement::TemporaryDtor:
500 llvm_unreachable("not yet implemented!");
503 llvm_unreachable("Unknown CFGElement kind");
507 PathDiagnosticLocation
508 PathDiagnosticLocation::createBegin(const Decl *D,
509 const SourceManager &SM) {
510 return PathDiagnosticLocation(D->getLocStart(), SM, SingleLocK);
513 PathDiagnosticLocation
514 PathDiagnosticLocation::createBegin(const Stmt *S,
515 const SourceManager &SM,
516 LocationOrAnalysisDeclContext LAC) {
517 return PathDiagnosticLocation(getValidSourceLocation(S, LAC),
522 PathDiagnosticLocation
523 PathDiagnosticLocation::createEnd(const Stmt *S,
524 const SourceManager &SM,
525 LocationOrAnalysisDeclContext LAC) {
526 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S))
527 return createEndBrace(CS, SM);
528 return PathDiagnosticLocation(getValidSourceLocation(S, LAC, /*End=*/true),
532 PathDiagnosticLocation
533 PathDiagnosticLocation::createOperatorLoc(const BinaryOperator *BO,
534 const SourceManager &SM) {
535 return PathDiagnosticLocation(BO->getOperatorLoc(), SM, SingleLocK);
538 PathDiagnosticLocation
539 PathDiagnosticLocation::createMemberLoc(const MemberExpr *ME,
540 const SourceManager &SM) {
541 return PathDiagnosticLocation(ME->getMemberLoc(), SM, SingleLocK);
544 PathDiagnosticLocation
545 PathDiagnosticLocation::createBeginBrace(const CompoundStmt *CS,
546 const SourceManager &SM) {
547 SourceLocation L = CS->getLBracLoc();
548 return PathDiagnosticLocation(L, SM, SingleLocK);
551 PathDiagnosticLocation
552 PathDiagnosticLocation::createEndBrace(const CompoundStmt *CS,
553 const SourceManager &SM) {
554 SourceLocation L = CS->getRBracLoc();
555 return PathDiagnosticLocation(L, SM, SingleLocK);
558 PathDiagnosticLocation
559 PathDiagnosticLocation::createDeclBegin(const LocationContext *LC,
560 const SourceManager &SM) {
561 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
562 if (const CompoundStmt *CS =
563 dyn_cast_or_null<CompoundStmt>(LC->getDecl()->getBody()))
564 if (!CS->body_empty()) {
565 SourceLocation Loc = (*CS->body_begin())->getLocStart();
566 return PathDiagnosticLocation(Loc, SM, SingleLocK);
569 return PathDiagnosticLocation();
572 PathDiagnosticLocation
573 PathDiagnosticLocation::createDeclEnd(const LocationContext *LC,
574 const SourceManager &SM) {
575 SourceLocation L = LC->getDecl()->getBodyRBrace();
576 return PathDiagnosticLocation(L, SM, SingleLocK);
579 PathDiagnosticLocation
580 PathDiagnosticLocation::create(const ProgramPoint& P,
581 const SourceManager &SMng) {
584 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
585 const CFGBlock *BSrc = BE->getSrc();
586 S = BSrc->getTerminatorCondition();
587 } else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>()) {
589 if (P.getAs<PostStmtPurgeDeadSymbols>())
590 return PathDiagnosticLocation::createEnd(S, SMng, P.getLocationContext());
591 } else if (Optional<PostInitializer> PIP = P.getAs<PostInitializer>()) {
592 return PathDiagnosticLocation(PIP->getInitializer()->getSourceLocation(),
594 } else if (Optional<PostImplicitCall> PIE = P.getAs<PostImplicitCall>()) {
595 return PathDiagnosticLocation(PIE->getLocation(), SMng);
596 } else if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
597 return getLocationForCaller(CE->getCalleeContext(),
598 CE->getLocationContext(),
600 } else if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) {
601 return getLocationForCaller(CEE->getCalleeContext(),
602 CEE->getLocationContext(),
605 llvm_unreachable("Unexpected ProgramPoint");
608 return PathDiagnosticLocation(S, SMng, P.getLocationContext());
611 PathDiagnosticLocation
612 PathDiagnosticLocation::createEndOfPath(const ExplodedNode* N,
613 const SourceManager &SM) {
614 assert(N && "Cannot create a location with a null node.");
616 const ExplodedNode *NI = N;
620 ProgramPoint P = NI->getLocation();
621 if (Optional<StmtPoint> PS = P.getAs<StmtPoint>()) {
623 if (P.getAs<PostStmtPurgeDeadSymbols>())
624 return PathDiagnosticLocation::createEnd(S, SM,
625 NI->getLocationContext());
627 } else if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
628 S = BE->getSrc()->getTerminator();
631 NI = NI->succ_empty() ? 0 : *(NI->succ_begin());
635 const LocationContext *LC = NI->getLocationContext();
636 if (S->getLocStart().isValid())
637 return PathDiagnosticLocation(S, SM, LC);
638 return PathDiagnosticLocation(getValidSourceLocation(S, LC), SM);
641 return createDeclEnd(N->getLocationContext(), SM);
644 PathDiagnosticLocation PathDiagnosticLocation::createSingleLocation(
645 const PathDiagnosticLocation &PDL) {
646 FullSourceLoc L = PDL.asLocation();
647 return PathDiagnosticLocation(L, L.getManager(), SingleLocK);
651 PathDiagnosticLocation::genLocation(SourceLocation L,
652 LocationOrAnalysisDeclContext LAC) const {
654 // Note that we want a 'switch' here so that the compiler can warn us in
655 // case we add more cases.
661 // Defensive checking.
664 return FullSourceLoc(getValidSourceLocation(S, LAC),
665 const_cast<SourceManager&>(*SM));
667 // Defensive checking.
670 return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
673 return FullSourceLoc(L, const_cast<SourceManager&>(*SM));
677 PathDiagnosticLocation::genRange(LocationOrAnalysisDeclContext LAC) const {
679 // Note that we want a 'switch' here so that the compiler can warn us in
680 // case we add more cases.
683 return PathDiagnosticRange(SourceRange(Loc,Loc), true);
687 const Stmt *S = asStmt();
688 switch (S->getStmtClass()) {
691 case Stmt::DeclStmtClass: {
692 const DeclStmt *DS = cast<DeclStmt>(S);
693 if (DS->isSingleDecl()) {
694 // Should always be the case, but we'll be defensive.
695 return SourceRange(DS->getLocStart(),
696 DS->getSingleDecl()->getLocation());
700 // FIXME: Provide better range information for different
702 case Stmt::IfStmtClass:
703 case Stmt::WhileStmtClass:
704 case Stmt::DoStmtClass:
705 case Stmt::ForStmtClass:
706 case Stmt::ChooseExprClass:
707 case Stmt::IndirectGotoStmtClass:
708 case Stmt::SwitchStmtClass:
709 case Stmt::BinaryConditionalOperatorClass:
710 case Stmt::ConditionalOperatorClass:
711 case Stmt::ObjCForCollectionStmtClass: {
712 SourceLocation L = getValidSourceLocation(S, LAC);
713 return SourceRange(L, L);
716 SourceRange R = S->getSourceRange();
722 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
723 return MD->getSourceRange();
724 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
725 if (Stmt *Body = FD->getBody())
726 return Body->getSourceRange();
729 SourceLocation L = D->getLocation();
730 return PathDiagnosticRange(SourceRange(L, L), true);
734 return SourceRange(Loc,Loc);
737 void PathDiagnosticLocation::flatten() {
743 else if (K == DeclK) {
750 //===----------------------------------------------------------------------===//
751 // Manipulation of PathDiagnosticCallPieces.
752 //===----------------------------------------------------------------------===//
754 PathDiagnosticCallPiece *
755 PathDiagnosticCallPiece::construct(const ExplodedNode *N,
756 const CallExitEnd &CE,
757 const SourceManager &SM) {
758 const Decl *caller = CE.getLocationContext()->getDecl();
759 PathDiagnosticLocation pos = getLocationForCaller(CE.getCalleeContext(),
760 CE.getLocationContext(),
762 return new PathDiagnosticCallPiece(caller, pos);
765 PathDiagnosticCallPiece *
766 PathDiagnosticCallPiece::construct(PathPieces &path,
767 const Decl *caller) {
768 PathDiagnosticCallPiece *C = new PathDiagnosticCallPiece(path, caller);
774 void PathDiagnosticCallPiece::setCallee(const CallEnter &CE,
775 const SourceManager &SM) {
776 const StackFrameContext *CalleeCtx = CE.getCalleeContext();
777 Callee = CalleeCtx->getDecl();
779 callEnterWithin = PathDiagnosticLocation::createBegin(Callee, SM);
780 callEnter = getLocationForCaller(CalleeCtx, CE.getLocationContext(), SM);
783 static inline void describeClass(raw_ostream &Out, const CXXRecordDecl *D,
784 StringRef Prefix = StringRef()) {
785 if (!D->getIdentifier())
787 Out << Prefix << '\'' << *D << '\'';
790 static bool describeCodeDecl(raw_ostream &Out, const Decl *D,
791 bool ExtendedDescription,
792 StringRef Prefix = StringRef()) {
796 if (isa<BlockDecl>(D)) {
797 if (ExtendedDescription)
798 Out << Prefix << "anonymous block";
799 return ExtendedDescription;
802 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
804 if (ExtendedDescription && !MD->isUserProvided()) {
805 if (MD->isExplicitlyDefaulted())
811 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD)) {
812 if (CD->isDefaultConstructor())
814 else if (CD->isCopyConstructor())
816 else if (CD->isMoveConstructor())
819 Out << "constructor";
820 describeClass(Out, MD->getParent(), " for ");
822 } else if (isa<CXXDestructorDecl>(MD)) {
823 if (!MD->isUserProvided()) {
825 describeClass(Out, MD->getParent(), " for ");
827 // Use ~Foo for explicitly-written destructors.
828 Out << "'" << *MD << "'";
831 } else if (MD->isCopyAssignmentOperator()) {
832 Out << "copy assignment operator";
833 describeClass(Out, MD->getParent(), " for ");
835 } else if (MD->isMoveAssignmentOperator()) {
836 Out << "move assignment operator";
837 describeClass(Out, MD->getParent(), " for ");
840 if (MD->getParent()->getIdentifier())
841 Out << "'" << *MD->getParent() << "::" << *MD << "'";
843 Out << "'" << *MD << "'";
849 Out << Prefix << '\'' << cast<NamedDecl>(*D) << '\'';
853 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
854 PathDiagnosticCallPiece::getCallEnterEvent() const {
858 SmallString<256> buf;
859 llvm::raw_svector_ostream Out(buf);
862 describeCodeDecl(Out, Callee, /*ExtendedDescription=*/true);
864 assert(callEnter.asLocation().isValid());
865 return new PathDiagnosticEventPiece(callEnter, Out.str());
868 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
869 PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
870 if (!callEnterWithin.asLocation().isValid())
872 if (Callee->isImplicit())
874 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee))
875 if (MD->isDefaulted())
878 SmallString<256> buf;
879 llvm::raw_svector_ostream Out(buf);
881 Out << "Entered call";
882 describeCodeDecl(Out, Caller, /*ExtendedDescription=*/false, " from ");
884 return new PathDiagnosticEventPiece(callEnterWithin, Out.str());
887 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
888 PathDiagnosticCallPiece::getCallExitEvent() const {
892 SmallString<256> buf;
893 llvm::raw_svector_ostream Out(buf);
895 if (!CallStackMessage.empty()) {
896 Out << CallStackMessage;
898 bool DidDescribe = describeCodeDecl(Out, Callee,
899 /*ExtendedDescription=*/false,
902 Out << "Returning to caller";
905 assert(callReturn.asLocation().isValid());
906 return new PathDiagnosticEventPiece(callReturn, Out.str());
909 static void compute_path_size(const PathPieces &pieces, unsigned &size) {
910 for (PathPieces::const_iterator it = pieces.begin(),
911 et = pieces.end(); it != et; ++it) {
912 const PathDiagnosticPiece *piece = it->getPtr();
913 if (const PathDiagnosticCallPiece *cp =
914 dyn_cast<PathDiagnosticCallPiece>(piece)) {
915 compute_path_size(cp->path, size);
922 unsigned PathDiagnostic::full_size() {
924 compute_path_size(path, size);
928 //===----------------------------------------------------------------------===//
929 // FoldingSet profiling methods.
930 //===----------------------------------------------------------------------===//
932 void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
933 ID.AddInteger(Range.getBegin().getRawEncoding());
934 ID.AddInteger(Range.getEnd().getRawEncoding());
935 ID.AddInteger(Loc.getRawEncoding());
939 void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
940 ID.AddInteger((unsigned) getKind());
942 // FIXME: Add profiling support for code hints.
943 ID.AddInteger((unsigned) getDisplayHint());
944 ArrayRef<SourceRange> Ranges = getRanges();
945 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
947 ID.AddInteger(I->getBegin().getRawEncoding());
948 ID.AddInteger(I->getEnd().getRawEncoding());
952 void PathDiagnosticCallPiece::Profile(llvm::FoldingSetNodeID &ID) const {
953 PathDiagnosticPiece::Profile(ID);
954 for (PathPieces::const_iterator it = path.begin(),
955 et = path.end(); it != et; ++it) {
960 void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
961 PathDiagnosticPiece::Profile(ID);
965 void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
966 PathDiagnosticPiece::Profile(ID);
967 for (const_iterator I = begin(), E = end(); I != E; ++I)
971 void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
972 PathDiagnosticSpotPiece::Profile(ID);
973 for (PathPieces::const_iterator I = subPieces.begin(), E = subPieces.end();
978 void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
979 ID.Add(getLocation());
980 ID.AddString(BugType);
981 ID.AddString(VerboseDesc);
982 ID.AddString(Category);
985 void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID &ID) const {
987 for (PathPieces::const_iterator I = path.begin(), E = path.end(); I != E; ++I)
989 for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
993 StackHintGenerator::~StackHintGenerator() {}
995 std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
996 ProgramPoint P = N->getLocation();
997 CallExitEnd CExit = P.castAs<CallExitEnd>();
999 // FIXME: Use CallEvent to abstract this over all calls.
1000 const Stmt *CallSite = CExit.getCalleeContext()->getCallSite();
1001 const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite);
1006 return getMessageForSymbolNotFound();
1008 // Check if one of the parameters are set to the interesting symbol.
1009 ProgramStateRef State = N->getState();
1010 const LocationContext *LCtx = N->getLocationContext();
1011 unsigned ArgIndex = 0;
1012 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1013 E = CE->arg_end(); I != E; ++I, ++ArgIndex){
1014 SVal SV = State->getSVal(*I, LCtx);
1016 // Check if the variable corresponding to the symbol is passed by value.
1017 SymbolRef AS = SV.getAsLocSymbol();
1019 return getMessageForArg(*I, ArgIndex);
1022 // Check if the parameter is a pointer to the symbol.
1023 if (Optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
1024 SVal PSV = State->getSVal(Reg->getRegion());
1025 SymbolRef AS = PSV.getAsLocSymbol();
1027 return getMessageForArg(*I, ArgIndex);
1032 // Check if we are returning the interesting symbol.
1033 SVal SV = State->getSVal(CE, LCtx);
1034 SymbolRef RetSym = SV.getAsLocSymbol();
1035 if (RetSym == Sym) {
1036 return getMessageForReturn(CE);
1039 return getMessageForSymbolNotFound();
1042 std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
1043 unsigned ArgIndex) {
1044 // Printed parameters start at 1, not 0.
1047 SmallString<200> buf;
1048 llvm::raw_svector_ostream os(buf);
1050 os << Msg << " via " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)