1 //===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the PathDiagnostic-related interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
27 
28 using namespace clang;
29 using namespace ento;
30 
containsEvent() const31 bool PathDiagnosticMacroPiece::containsEvent() const {
32   for (PathPieces::const_iterator I = subPieces.begin(), E = subPieces.end();
33        I!=E; ++I) {
34     if (isa<PathDiagnosticEventPiece>(*I))
35       return true;
36     if (PathDiagnosticMacroPiece *MP = dyn_cast<PathDiagnosticMacroPiece>(*I))
37       if (MP->containsEvent())
38         return true;
39   }
40   return false;
41 }
42 
StripTrailingDots(StringRef s)43 static StringRef StripTrailingDots(StringRef s) {
44   for (StringRef::size_type i = s.size(); i != 0; --i)
45     if (s[i - 1] != '.')
46       return s.substr(0, i);
47   return "";
48 }
49 
PathDiagnosticPiece(StringRef s,Kind k,DisplayHint hint)50 PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
51                                          Kind k, DisplayHint hint)
52   : str(StripTrailingDots(s)), kind(k), Hint(hint),
53     LastInMainSourceFile(false) {}
54 
PathDiagnosticPiece(Kind k,DisplayHint hint)55 PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
56   : kind(k), Hint(hint), LastInMainSourceFile(false) {}
57 
~PathDiagnosticPiece()58 PathDiagnosticPiece::~PathDiagnosticPiece() {}
~PathDiagnosticEventPiece()59 PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
~PathDiagnosticCallPiece()60 PathDiagnosticCallPiece::~PathDiagnosticCallPiece() {}
~PathDiagnosticControlFlowPiece()61 PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
~PathDiagnosticMacroPiece()62 PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {}
63 
64 
~PathPieces()65 PathPieces::~PathPieces() {}
66 
flattenTo(PathPieces & Primary,PathPieces & Current,bool ShouldFlattenMacros) const67 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();
71 
72     switch (Piece->getKind()) {
73     case PathDiagnosticPiece::Call: {
74       PathDiagnosticCallPiece *Call = cast<PathDiagnosticCallPiece>(Piece);
75       IntrusiveRefCntPtr<PathDiagnosticEventPiece> CallEnter =
76         Call->getCallEnterEvent();
77       if (CallEnter)
78         Current.push_back(CallEnter);
79       Call->path.flattenTo(Primary, Primary, ShouldFlattenMacros);
80       IntrusiveRefCntPtr<PathDiagnosticEventPiece> callExit =
81         Call->getCallExitEvent();
82       if (callExit)
83         Current.push_back(callExit);
84       break;
85     }
86     case PathDiagnosticPiece::Macro: {
87       PathDiagnosticMacroPiece *Macro = cast<PathDiagnosticMacroPiece>(Piece);
88       if (ShouldFlattenMacros) {
89         Macro->subPieces.flattenTo(Primary, Primary, ShouldFlattenMacros);
90       } else {
91         Current.push_back(Piece);
92         PathPieces NewPath;
93         Macro->subPieces.flattenTo(Primary, NewPath, ShouldFlattenMacros);
94         // FIXME: This probably shouldn't mutate the original path piece.
95         Macro->subPieces = NewPath;
96       }
97       break;
98     }
99     case PathDiagnosticPiece::Event:
100     case PathDiagnosticPiece::ControlFlow:
101       Current.push_back(Piece);
102       break;
103     }
104   }
105 }
106 
107 
~PathDiagnostic()108 PathDiagnostic::~PathDiagnostic() {}
109 
PathDiagnostic(StringRef CheckName,const Decl * declWithIssue,StringRef bugtype,StringRef verboseDesc,StringRef shortDesc,StringRef category,PathDiagnosticLocation LocationToUnique,const Decl * DeclToUnique)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),
123     path(pathImpl) {}
124 
125 static PathDiagnosticCallPiece *
getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece * CP,const SourceManager & SMgr)126 getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
127                                 const SourceManager &SMgr) {
128   SourceLocation CallLoc = CP->callEnter.asLocation();
129 
130   // If the call is within a macro, don't do anything (for now).
131   if (CallLoc.isMacroID())
132     return nullptr;
133 
134   assert(SMgr.isInMainFile(CallLoc) &&
135          "The call piece should be in the main file.");
136 
137   // Check if CP represents a path through a function outside of the main file.
138   if (!SMgr.isInMainFile(CP->callEnterWithin.asLocation()))
139     return CP;
140 
141   const PathPieces &Path = CP->path;
142   if (Path.empty())
143     return nullptr;
144 
145   // Check if the last piece in the callee path is a call to a function outside
146   // of the main file.
147   if (PathDiagnosticCallPiece *CPInner =
148       dyn_cast<PathDiagnosticCallPiece>(Path.back())) {
149     return getFirstStackedCallToHeaderFile(CPInner, SMgr);
150   }
151 
152   // Otherwise, the last piece is in the main file.
153   return nullptr;
154 }
155 
resetDiagnosticLocationToMainFile()156 void PathDiagnostic::resetDiagnosticLocationToMainFile() {
157   if (path.empty())
158     return;
159 
160   PathDiagnosticPiece *LastP = path.back().get();
161   assert(LastP);
162   const SourceManager &SMgr = LastP->getLocation().getManager();
163 
164   // We only need to check if the report ends inside headers, if the last piece
165   // is a call piece.
166   if (PathDiagnosticCallPiece *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
167     CP = getFirstStackedCallToHeaderFile(CP, SMgr);
168     if (CP) {
169       // Mark the piece.
170        CP->setAsLastInMainSourceFile();
171 
172       // Update the path diagnostic message.
173       const NamedDecl *ND = dyn_cast<NamedDecl>(CP->getCallee());
174       if (ND) {
175         SmallString<200> buf;
176         llvm::raw_svector_ostream os(buf);
177         os << " (within a call to '" << ND->getDeclName() << "')";
178         appendToDesc(os.str());
179       }
180 
181       // Reset the report containing declaration and location.
182       DeclWithIssue = CP->getCaller();
183       Loc = CP->getLocation();
184 
185       return;
186     }
187   }
188 }
189 
anchor()190 void PathDiagnosticConsumer::anchor() { }
191 
~PathDiagnosticConsumer()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) {
196     delete &*it;
197   }
198 }
199 
HandlePathDiagnostic(std::unique_ptr<PathDiagnostic> D)200 void PathDiagnosticConsumer::HandlePathDiagnostic(
201     std::unique_ptr<PathDiagnostic> D) {
202   if (!D || D->path.empty())
203     return;
204 
205   // We need to flatten the locations (convert Stmt* to locations) because
206   // the referenced statements may be freed by the time the diagnostics
207   // are emitted.
208   D->flattenLocations();
209 
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.
214     FileID FID;
215     const SourceManager &SMgr = D->path.front()->getLocation().getManager();
216     SmallVector<const PathPieces *, 5> WorkList;
217     WorkList.push_back(&D->path);
218 
219     while (!WorkList.empty()) {
220       const PathPieces &path = *WorkList.pop_back_val();
221 
222       for (PathPieces::const_iterator I = path.begin(), E = path.end(); I != E;
223            ++I) {
224         const PathDiagnosticPiece *piece = I->get();
225         FullSourceLoc L = piece->getLocation().asLocation().getExpansionLoc();
226 
227         if (FID.isInvalid()) {
228           FID = SMgr.getFileID(L);
229         } else if (SMgr.getFileID(L) != FID)
230           return; // FIXME: Emit a warning?
231 
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?
242         }
243 
244         if (const PathDiagnosticCallPiece *call =
245             dyn_cast<PathDiagnosticCallPiece>(piece)) {
246           WorkList.push_back(&call->path);
247         }
248         else if (const PathDiagnosticMacroPiece *macro =
249                  dyn_cast<PathDiagnosticMacroPiece>(piece)) {
250           WorkList.push_back(&macro->subPieces);
251         }
252       }
253     }
254 
255     if (FID.isInvalid())
256       return; // FIXME: Emit a warning?
257   }
258 
259   // Profile the node to see if we already have something matching it
260   llvm::FoldingSetNodeID profile;
261   D->Profile(profile);
262   void *InsertPos = nullptr;
263 
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)
272       return;
273 
274     assert(orig != D.get());
275     Diags.RemoveNode(orig);
276     delete orig;
277   }
278 
279   Diags.InsertNode(D.release());
280 }
281 
282 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y);
283 static Optional<bool>
compareControlFlow(const PathDiagnosticControlFlowPiece & X,const PathDiagnosticControlFlowPiece & Y)284 compareControlFlow(const PathDiagnosticControlFlowPiece &X,
285                    const PathDiagnosticControlFlowPiece &Y) {
286   FullSourceLoc XSL = X.getStartLocation().asLocation();
287   FullSourceLoc YSL = Y.getStartLocation().asLocation();
288   if (XSL != YSL)
289     return XSL.isBeforeInTranslationUnitThan(YSL);
290   FullSourceLoc XEL = X.getEndLocation().asLocation();
291   FullSourceLoc YEL = Y.getEndLocation().asLocation();
292   if (XEL != YEL)
293     return XEL.isBeforeInTranslationUnitThan(YEL);
294   return None;
295 }
296 
compareMacro(const PathDiagnosticMacroPiece & X,const PathDiagnosticMacroPiece & Y)297 static Optional<bool> compareMacro(const PathDiagnosticMacroPiece &X,
298                                    const PathDiagnosticMacroPiece &Y) {
299   return comparePath(X.subPieces, Y.subPieces);
300 }
301 
compareCall(const PathDiagnosticCallPiece & X,const PathDiagnosticCallPiece & Y)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();
306   if (X_CEL != Y_CEL)
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();
314   if (X_CRL != Y_CRL)
315     return X_CRL.isBeforeInTranslationUnitThan(Y_CRL);
316   return comparePath(X.path, Y.path);
317 }
318 
comparePiece(const PathDiagnosticPiece & X,const PathDiagnosticPiece & Y)319 static Optional<bool> comparePiece(const PathDiagnosticPiece &X,
320                                    const PathDiagnosticPiece &Y) {
321   if (X.getKind() != Y.getKind())
322     return X.getKind() < Y.getKind();
323 
324   FullSourceLoc XL = X.getLocation().asLocation();
325   FullSourceLoc YL = Y.getLocation().asLocation();
326   if (XL != YL)
327     return XL.isBeforeInTranslationUnitThan(YL);
328 
329   if (X.getString() != Y.getString())
330     return X.getString() < Y.getString();
331 
332   if (X.getRanges().size() != Y.getRanges().size())
333     return X.getRanges().size() < Y.getRanges().size();
334 
335   const SourceManager &SM = XL.getManager();
336 
337   for (unsigned i = 0, n = X.getRanges().size(); i < n; ++i) {
338     SourceRange XR = X.getRanges()[i];
339     SourceRange YR = Y.getRanges()[i];
340     if (XR != YR) {
341       if (XR.getBegin() != YR.getBegin())
342         return SM.isBeforeInTranslationUnit(XR.getBegin(), YR.getBegin());
343       return SM.isBeforeInTranslationUnit(XR.getEnd(), YR.getEnd());
344     }
345   }
346 
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:
352       return None;
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));
359   }
360   llvm_unreachable("all cases handled");
361 }
362 
comparePath(const PathPieces & X,const PathPieces & Y)363 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) {
364   if (X.size() != Y.size())
365     return X.size() < Y.size();
366 
367   PathPieces::const_iterator X_I = X.begin(), X_end = X.end();
368   PathPieces::const_iterator Y_I = Y.begin(), Y_end = Y.end();
369 
370   for ( ; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) {
371     Optional<bool> b = comparePiece(**X_I, **Y_I);
372     if (b.hasValue())
373       return b.getValue();
374   }
375 
376   return None;
377 }
378 
compare(const PathDiagnostic & X,const PathDiagnostic & Y)379 static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) {
380   FullSourceLoc XL = X.getLocation().asLocation();
381   FullSourceLoc YL = Y.getLocation().asLocation();
382   if (XL != YL)
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();
394     if (!XD)
395       return true;
396     const Decl *YD = Y.getDeclWithIssue();
397     if (!YD)
398       return false;
399     SourceLocation XDL = XD->getLocation();
400     SourceLocation YDL = YD->getLocation();
401     if (XDL != YDL) {
402       const SourceManager &SM = XL.getManager();
403       return SM.isBeforeInTranslationUnit(XDL, YDL);
404     }
405   }
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) {
411     if (*XI != *YI)
412       return (*XI) < (*YI);
413   }
414   Optional<bool> b = comparePath(X.path, Y.path);
415   assert(b.hasValue());
416   return b.getValue();
417 }
418 
FlushDiagnostics(PathDiagnosticConsumer::FilesMade * Files)419 void PathDiagnosticConsumer::FlushDiagnostics(
420                                      PathDiagnosticConsumer::FilesMade *Files) {
421   if (flushed)
422     return;
423 
424   flushed = true;
425 
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);
431   }
432 
433   // Sort the diagnostics so that they are always emitted in a deterministic
434   // order.
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);
439     });
440 
441   FlushDiagnosticsImpl(BatchDiags, Files);
442 
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;
447     delete D;
448   }
449 
450   // Clear out the FoldingSet.
451   Diags.clear();
452 }
453 
~FilesMade()454 PathDiagnosticConsumer::FilesMade::~FilesMade() {
455   for (PDFileEntry &Entry : *this)
456     Entry.~PDFileEntry();
457 }
458 
addDiagnostic(const PathDiagnostic & PD,StringRef ConsumerName,StringRef FileName)459 void PathDiagnosticConsumer::FilesMade::addDiagnostic(const PathDiagnostic &PD,
460                                                       StringRef ConsumerName,
461                                                       StringRef FileName) {
462   llvm::FoldingSetNodeID NodeID;
463   NodeID.Add(PD);
464   void *InsertPos;
465   PDFileEntry *Entry = FindNodeOrInsertPos(NodeID, InsertPos);
466   if (!Entry) {
467     Entry = Alloc.Allocate<PDFileEntry>();
468     Entry = new (Entry) PDFileEntry(NodeID);
469     InsertNode(Entry, InsertPos);
470   }
471 
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());
475 
476   Entry->files.push_back(std::make_pair(ConsumerName,
477                                         StringRef(FileName_cstr,
478                                                   FileName.size())));
479 }
480 
481 PathDiagnosticConsumer::PDFileEntry::ConsumerFiles *
getFiles(const PathDiagnostic & PD)482 PathDiagnosticConsumer::FilesMade::getFiles(const PathDiagnostic &PD) {
483   llvm::FoldingSetNodeID NodeID;
484   NodeID.Add(PD);
485   void *InsertPos;
486   PDFileEntry *Entry = FindNodeOrInsertPos(NodeID, InsertPos);
487   if (!Entry)
488     return nullptr;
489   return &Entry->files;
490 }
491 
492 //===----------------------------------------------------------------------===//
493 // PathDiagnosticLocation methods.
494 //===----------------------------------------------------------------------===//
495 
getValidSourceLocation(const Stmt * S,LocationOrAnalysisDeclContext LAC,bool UseEnd=false)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.");
502 
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.
505   if (!L.isValid()) {
506 
507     AnalysisDeclContext *ADC;
508     if (LAC.is<const LocationContext*>())
509       ADC = LAC.get<const LocationContext*>()->getAnalysisDeclContext();
510     else
511       ADC = LAC.get<AnalysisDeclContext*>();
512 
513     ParentMap &PM = ADC->getParentMap();
514 
515     const Stmt *Parent = S;
516     do {
517       Parent = PM.getParent(Parent);
518 
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).
523       if (!Parent) {
524         const Stmt *Body = ADC->getBody();
525         if (Body)
526           L = Body->getLocStart();
527         else
528           L = ADC->getDecl()->getLocEnd();
529         break;
530       }
531 
532       L = UseEnd ? Parent->getLocEnd() : Parent->getLocStart();
533     } while (!L.isValid());
534   }
535 
536   return L;
537 }
538 
539 static PathDiagnosticLocation
getLocationForCaller(const StackFrameContext * SFC,const LocationContext * CallerCtx,const SourceManager & SM)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()];
545 
546   switch (Source.getKind()) {
547   case CFGElement::Statement:
548     return PathDiagnosticLocation(Source.castAs<CFGStmt>().getStmt(),
549                                   SM, CallerCtx);
550   case CFGElement::Initializer: {
551     const CFGInitializer &Init = Source.castAs<CFGInitializer>();
552     return PathDiagnosticLocation(Init.getInitializer()->getInit(),
553                                   SM, CallerCtx);
554   }
555   case CFGElement::AutomaticObjectDtor: {
556     const CFGAutomaticObjDtor &Dtor = Source.castAs<CFGAutomaticObjDtor>();
557     return PathDiagnosticLocation::createEnd(Dtor.getTriggerStmt(),
558                                              SM, CallerCtx);
559   }
560   case CFGElement::DeleteDtor: {
561     const CFGDeleteDtor &Dtor = Source.castAs<CFGDeleteDtor>();
562     return PathDiagnosticLocation(Dtor.getDeleteExpr(), SM, CallerCtx);
563   }
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);
570   }
571   case CFGElement::TemporaryDtor:
572   case CFGElement::NewAllocator:
573     llvm_unreachable("not yet implemented!");
574   }
575 
576   llvm_unreachable("Unknown CFGElement kind");
577 }
578 
579 
580 PathDiagnosticLocation
createBegin(const Decl * D,const SourceManager & SM)581   PathDiagnosticLocation::createBegin(const Decl *D,
582                                       const SourceManager &SM) {
583   return PathDiagnosticLocation(D->getLocStart(), SM, SingleLocK);
584 }
585 
586 PathDiagnosticLocation
createBegin(const Stmt * S,const SourceManager & SM,LocationOrAnalysisDeclContext LAC)587   PathDiagnosticLocation::createBegin(const Stmt *S,
588                                       const SourceManager &SM,
589                                       LocationOrAnalysisDeclContext LAC) {
590   return PathDiagnosticLocation(getValidSourceLocation(S, LAC),
591                                 SM, SingleLocK);
592 }
593 
594 
595 PathDiagnosticLocation
createEnd(const Stmt * S,const SourceManager & SM,LocationOrAnalysisDeclContext LAC)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),
602                                 SM, SingleLocK);
603 }
604 
605 PathDiagnosticLocation
createOperatorLoc(const BinaryOperator * BO,const SourceManager & SM)606   PathDiagnosticLocation::createOperatorLoc(const BinaryOperator *BO,
607                                             const SourceManager &SM) {
608   return PathDiagnosticLocation(BO->getOperatorLoc(), SM, SingleLocK);
609 }
610 
611 PathDiagnosticLocation
createConditionalColonLoc(const ConditionalOperator * CO,const SourceManager & SM)612   PathDiagnosticLocation::createConditionalColonLoc(
613                                             const ConditionalOperator *CO,
614                                             const SourceManager &SM) {
615   return PathDiagnosticLocation(CO->getColonLoc(), SM, SingleLocK);
616 }
617 
618 
619 PathDiagnosticLocation
createMemberLoc(const MemberExpr * ME,const SourceManager & SM)620   PathDiagnosticLocation::createMemberLoc(const MemberExpr *ME,
621                                           const SourceManager &SM) {
622   return PathDiagnosticLocation(ME->getMemberLoc(), SM, SingleLocK);
623 }
624 
625 PathDiagnosticLocation
createBeginBrace(const CompoundStmt * CS,const SourceManager & SM)626   PathDiagnosticLocation::createBeginBrace(const CompoundStmt *CS,
627                                            const SourceManager &SM) {
628   SourceLocation L = CS->getLBracLoc();
629   return PathDiagnosticLocation(L, SM, SingleLocK);
630 }
631 
632 PathDiagnosticLocation
createEndBrace(const CompoundStmt * CS,const SourceManager & SM)633   PathDiagnosticLocation::createEndBrace(const CompoundStmt *CS,
634                                          const SourceManager &SM) {
635   SourceLocation L = CS->getRBracLoc();
636   return PathDiagnosticLocation(L, SM, SingleLocK);
637 }
638 
639 PathDiagnosticLocation
createDeclBegin(const LocationContext * LC,const SourceManager & SM)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);
648     }
649 
650   return PathDiagnosticLocation();
651 }
652 
653 PathDiagnosticLocation
createDeclEnd(const LocationContext * LC,const SourceManager & SM)654   PathDiagnosticLocation::createDeclEnd(const LocationContext *LC,
655                                         const SourceManager &SM) {
656   SourceLocation L = LC->getDecl()->getBodyRBrace();
657   return PathDiagnosticLocation(L, SM, SingleLocK);
658 }
659 
660 PathDiagnosticLocation
create(const ProgramPoint & P,const SourceManager & SMng)661   PathDiagnosticLocation::create(const ProgramPoint& P,
662                                  const SourceManager &SMng) {
663 
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>()) {
669     S = SP->getStmt();
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(),
674                                   SMng);
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(),
680                                 SMng);
681   } else if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) {
682     return getLocationForCaller(CEE->getCalleeContext(),
683                                 CEE->getLocationContext(),
684                                 SMng);
685   } else {
686     llvm_unreachable("Unexpected ProgramPoint");
687   }
688 
689   return PathDiagnosticLocation(S, SMng, P.getLocationContext());
690 }
691 
getStmt(const ExplodedNode * N)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();
704 
705   return nullptr;
706 }
707 
getNextStmt(const ExplodedNode * N)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:
717           continue;
718         case Stmt::BinaryOperatorClass: {
719           BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
720           if (Op == BO_LAnd || Op == BO_LOr)
721             continue;
722           break;
723         }
724         default:
725           break;
726       }
727       // We found the statement, so return it.
728       return S;
729     }
730   }
731 
732   return nullptr;
733 }
734 
735 PathDiagnosticLocation
createEndOfPath(const ExplodedNode * N,const SourceManager & SM)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);
740 
741   if (!S) {
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);
745     S = getNextStmt(N);
746   }
747 
748   if (S) {
749     ProgramPoint P = N->getLocation();
750     const LocationContext *LC = N->getLocationContext();
751 
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);
755 
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);
759 
760     if (P.getAs<PostStmtPurgeDeadSymbols>())
761       return PathDiagnosticLocation::createEnd(S, SM, LC);
762 
763     if (S->getLocStart().isValid())
764       return PathDiagnosticLocation(S, SM, LC);
765     return PathDiagnosticLocation(getValidSourceLocation(S, LC), SM);
766   }
767 
768   return createDeclEnd(N->getLocationContext(), SM);
769 }
770 
createSingleLocation(const PathDiagnosticLocation & PDL)771 PathDiagnosticLocation PathDiagnosticLocation::createSingleLocation(
772                                            const PathDiagnosticLocation &PDL) {
773   FullSourceLoc L = PDL.asLocation();
774   return PathDiagnosticLocation(L, L.getManager(), SingleLocK);
775 }
776 
777 FullSourceLoc
genLocation(SourceLocation L,LocationOrAnalysisDeclContext LAC) const778   PathDiagnosticLocation::genLocation(SourceLocation L,
779                                       LocationOrAnalysisDeclContext LAC) const {
780   assert(isValid());
781   // Note that we want a 'switch' here so that the compiler can warn us in
782   // case we add more cases.
783   switch (K) {
784     case SingleLocK:
785     case RangeK:
786       break;
787     case StmtK:
788       // Defensive checking.
789       if (!S)
790         break;
791       return FullSourceLoc(getValidSourceLocation(S, LAC),
792                            const_cast<SourceManager&>(*SM));
793     case DeclK:
794       // Defensive checking.
795       if (!D)
796         break;
797       return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
798   }
799 
800   return FullSourceLoc(L, const_cast<SourceManager&>(*SM));
801 }
802 
803 PathDiagnosticRange
genRange(LocationOrAnalysisDeclContext LAC) const804   PathDiagnosticLocation::genRange(LocationOrAnalysisDeclContext LAC) const {
805   assert(isValid());
806   // Note that we want a 'switch' here so that the compiler can warn us in
807   // case we add more cases.
808   switch (K) {
809     case SingleLocK:
810       return PathDiagnosticRange(SourceRange(Loc,Loc), true);
811     case RangeK:
812       break;
813     case StmtK: {
814       const Stmt *S = asStmt();
815       switch (S->getStmtClass()) {
816         default:
817           break;
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());
824           }
825           break;
826         }
827           // FIXME: Provide better range information for different
828           //  terminators.
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);
841         }
842       }
843       SourceRange R = S->getSourceRange();
844       if (R.isValid())
845         return R;
846       break;
847     }
848     case DeclK:
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();
854       }
855       else {
856         SourceLocation L = D->getLocation();
857         return PathDiagnosticRange(SourceRange(L, L), true);
858       }
859   }
860 
861   return SourceRange(Loc,Loc);
862 }
863 
flatten()864 void PathDiagnosticLocation::flatten() {
865   if (K == StmtK) {
866     K = RangeK;
867     S = nullptr;
868     D = nullptr;
869   }
870   else if (K == DeclK) {
871     K = SingleLocK;
872     S = nullptr;
873     D = nullptr;
874   }
875 }
876 
877 //===----------------------------------------------------------------------===//
878 // Manipulation of PathDiagnosticCallPieces.
879 //===----------------------------------------------------------------------===//
880 
881 PathDiagnosticCallPiece *
construct(const ExplodedNode * N,const CallExitEnd & CE,const SourceManager & SM)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(),
888                                                     SM);
889   return new PathDiagnosticCallPiece(caller, pos);
890 }
891 
892 PathDiagnosticCallPiece *
construct(PathPieces & path,const Decl * caller)893 PathDiagnosticCallPiece::construct(PathPieces &path,
894                                    const Decl *caller) {
895   PathDiagnosticCallPiece *C = new PathDiagnosticCallPiece(path, caller);
896   path.clear();
897   path.push_front(C);
898   return C;
899 }
900 
setCallee(const CallEnter & CE,const SourceManager & SM)901 void PathDiagnosticCallPiece::setCallee(const CallEnter &CE,
902                                         const SourceManager &SM) {
903   const StackFrameContext *CalleeCtx = CE.getCalleeContext();
904   Callee = CalleeCtx->getDecl();
905 
906   callEnterWithin = PathDiagnosticLocation::createBegin(Callee, SM);
907   callEnter = getLocationForCaller(CalleeCtx, CE.getLocationContext(), SM);
908 }
909 
describeClass(raw_ostream & Out,const CXXRecordDecl * D,StringRef Prefix=StringRef ())910 static inline void describeClass(raw_ostream &Out, const CXXRecordDecl *D,
911                                  StringRef Prefix = StringRef()) {
912   if (!D->getIdentifier())
913     return;
914   Out << Prefix << '\'' << *D << '\'';
915 }
916 
describeCodeDecl(raw_ostream & Out,const Decl * D,bool ExtendedDescription,StringRef Prefix=StringRef ())917 static bool describeCodeDecl(raw_ostream &Out, const Decl *D,
918                              bool ExtendedDescription,
919                              StringRef Prefix = StringRef()) {
920   if (!D)
921     return false;
922 
923   if (isa<BlockDecl>(D)) {
924     if (ExtendedDescription)
925       Out << Prefix << "anonymous block";
926     return ExtendedDescription;
927   }
928 
929   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
930     Out << Prefix;
931     if (ExtendedDescription && !MD->isUserProvided()) {
932       if (MD->isExplicitlyDefaulted())
933         Out << "defaulted ";
934       else
935         Out << "implicit ";
936     }
937 
938     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD)) {
939       if (CD->isDefaultConstructor())
940         Out << "default ";
941       else if (CD->isCopyConstructor())
942         Out << "copy ";
943       else if (CD->isMoveConstructor())
944         Out << "move ";
945 
946       Out << "constructor";
947       describeClass(Out, MD->getParent(), " for ");
948 
949     } else if (isa<CXXDestructorDecl>(MD)) {
950       if (!MD->isUserProvided()) {
951         Out << "destructor";
952         describeClass(Out, MD->getParent(), " for ");
953       } else {
954         // Use ~Foo for explicitly-written destructors.
955         Out << "'" << *MD << "'";
956       }
957 
958     } else if (MD->isCopyAssignmentOperator()) {
959         Out << "copy assignment operator";
960         describeClass(Out, MD->getParent(), " for ");
961 
962     } else if (MD->isMoveAssignmentOperator()) {
963         Out << "move assignment operator";
964         describeClass(Out, MD->getParent(), " for ");
965 
966     } else {
967       if (MD->getParent()->getIdentifier())
968         Out << "'" << *MD->getParent() << "::" << *MD << "'";
969       else
970         Out << "'" << *MD << "'";
971     }
972 
973     return true;
974   }
975 
976   Out << Prefix << '\'' << cast<NamedDecl>(*D) << '\'';
977   return true;
978 }
979 
980 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
getCallEnterEvent() const981 PathDiagnosticCallPiece::getCallEnterEvent() const {
982   if (!Callee)
983     return nullptr;
984 
985   SmallString<256> buf;
986   llvm::raw_svector_ostream Out(buf);
987 
988   Out << "Calling ";
989   describeCodeDecl(Out, Callee, /*ExtendedDescription=*/true);
990 
991   assert(callEnter.asLocation().isValid());
992   return new PathDiagnosticEventPiece(callEnter, Out.str());
993 }
994 
995 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
getCallEnterWithinCallerEvent() const996 PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
997   if (!callEnterWithin.asLocation().isValid())
998     return nullptr;
999   if (Callee->isImplicit() || !Callee->hasBody())
1000     return nullptr;
1001   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee))
1002     if (MD->isDefaulted())
1003       return nullptr;
1004 
1005   SmallString<256> buf;
1006   llvm::raw_svector_ostream Out(buf);
1007 
1008   Out << "Entered call";
1009   describeCodeDecl(Out, Caller, /*ExtendedDescription=*/false, " from ");
1010 
1011   return new PathDiagnosticEventPiece(callEnterWithin, Out.str());
1012 }
1013 
1014 IntrusiveRefCntPtr<PathDiagnosticEventPiece>
getCallExitEvent() const1015 PathDiagnosticCallPiece::getCallExitEvent() const {
1016   if (NoExit)
1017     return nullptr;
1018 
1019   SmallString<256> buf;
1020   llvm::raw_svector_ostream Out(buf);
1021 
1022   if (!CallStackMessage.empty()) {
1023     Out << CallStackMessage;
1024   } else {
1025     bool DidDescribe = describeCodeDecl(Out, Callee,
1026                                         /*ExtendedDescription=*/false,
1027                                         "Returning from ");
1028     if (!DidDescribe)
1029       Out << "Returning to caller";
1030   }
1031 
1032   assert(callReturn.asLocation().isValid());
1033   return new PathDiagnosticEventPiece(callReturn, Out.str());
1034 }
1035 
compute_path_size(const PathPieces & pieces,unsigned & size)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);
1043     }
1044     else
1045       ++size;
1046   }
1047 }
1048 
full_size()1049 unsigned PathDiagnostic::full_size() {
1050   unsigned size = 0;
1051   compute_path_size(path, size);
1052   return size;
1053 }
1054 
1055 //===----------------------------------------------------------------------===//
1056 // FoldingSet profiling methods.
1057 //===----------------------------------------------------------------------===//
1058 
Profile(llvm::FoldingSetNodeID & ID) const1059 void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
1060   ID.AddInteger(Range.getBegin().getRawEncoding());
1061   ID.AddInteger(Range.getEnd().getRawEncoding());
1062   ID.AddInteger(Loc.getRawEncoding());
1063   return;
1064 }
1065 
Profile(llvm::FoldingSetNodeID & ID) const1066 void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1067   ID.AddInteger((unsigned) getKind());
1068   ID.AddString(str);
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();
1073                                         I != E; ++I) {
1074     ID.AddInteger(I->getBegin().getRawEncoding());
1075     ID.AddInteger(I->getEnd().getRawEncoding());
1076   }
1077 }
1078 
Profile(llvm::FoldingSetNodeID & ID) const1079 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) {
1083     ID.Add(**it);
1084   }
1085 }
1086 
Profile(llvm::FoldingSetNodeID & ID) const1087 void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1088   PathDiagnosticPiece::Profile(ID);
1089   ID.Add(Pos);
1090 }
1091 
Profile(llvm::FoldingSetNodeID & ID) const1092 void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1093   PathDiagnosticPiece::Profile(ID);
1094   for (const_iterator I = begin(), E = end(); I != E; ++I)
1095     ID.Add(*I);
1096 }
1097 
Profile(llvm::FoldingSetNodeID & ID) const1098 void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1099   PathDiagnosticSpotPiece::Profile(ID);
1100   for (PathPieces::const_iterator I = subPieces.begin(), E = subPieces.end();
1101        I != E; ++I)
1102     ID.Add(**I);
1103 }
1104 
Profile(llvm::FoldingSetNodeID & ID) const1105 void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
1106   ID.Add(getLocation());
1107   ID.AddString(BugType);
1108   ID.AddString(VerboseDesc);
1109   ID.AddString(Category);
1110 }
1111 
FullProfile(llvm::FoldingSetNodeID & ID) const1112 void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID &ID) const {
1113   Profile(ID);
1114   for (PathPieces::const_iterator I = path.begin(), E = path.end(); I != E; ++I)
1115     ID.Add(**I);
1116   for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
1117     ID.AddString(*I);
1118 }
1119 
~StackHintGenerator()1120 StackHintGenerator::~StackHintGenerator() {}
1121 
getMessage(const ExplodedNode * N)1122 std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
1123   ProgramPoint P = N->getLocation();
1124   CallExitEnd CExit = P.castAs<CallExitEnd>();
1125 
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);
1129   if (!CE)
1130     return "";
1131 
1132   if (!N)
1133     return getMessageForSymbolNotFound();
1134 
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);
1142 
1143     // Check if the variable corresponding to the symbol is passed by value.
1144     SymbolRef AS = SV.getAsLocSymbol();
1145     if (AS == Sym) {
1146       return getMessageForArg(*I, ArgIndex);
1147     }
1148 
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();
1153       if (AS == Sym) {
1154         return getMessageForArg(*I, ArgIndex);
1155       }
1156     }
1157   }
1158 
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);
1164   }
1165 
1166   return getMessageForSymbolNotFound();
1167 }
1168 
getMessageForArg(const Expr * ArgE,unsigned ArgIndex)1169 std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
1170                                                           unsigned ArgIndex) {
1171   // Printed parameters start at 1, not 0.
1172   ++ArgIndex;
1173 
1174   SmallString<200> buf;
1175   llvm::raw_svector_ostream os(buf);
1176 
1177   os << Msg << " via " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
1178      << " parameter";
1179 
1180   return os.str();
1181 }
1182