1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
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 // "Meta" ASTConsumer for running different source analyses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
15 #include "ModelInjector.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/Analysis/CFG.h"
22 #include "clang/Analysis/CallGraph.h"
23 #include "clang/Analysis/CodeInjector.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
28 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
29 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
30 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
31 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
32 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
35 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
36 #include "llvm/ADT/PostOrderIterator.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/Timer.h"
42 #include "llvm/Support/raw_ostream.h"
47 using namespace clang;
50 #define DEBUG_TYPE "AnalysisConsumer"
52 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz();
54 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
55 STATISTIC(NumFunctionsAnalyzed,
56 "The # of functions and blocks analyzed (as top level "
57 "with inlining turned on).");
58 STATISTIC(NumBlocksInAnalyzedFunctions,
59 "The # of basic blocks in the analyzed functions.");
60 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
61 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
63 //===----------------------------------------------------------------------===//
64 // Special PathDiagnosticConsumers.
65 //===----------------------------------------------------------------------===//
67 void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
68 PathDiagnosticConsumers &C,
69 const std::string &prefix,
70 const Preprocessor &PP) {
71 createHTMLDiagnosticConsumer(AnalyzerOpts, C,
72 llvm::sys::path::parent_path(prefix), PP);
73 createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
76 void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
77 PathDiagnosticConsumers &C,
78 const std::string &Prefix,
79 const clang::Preprocessor &PP) {
80 llvm_unreachable("'text' consumer should be enabled on ClangDiags");
84 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
85 DiagnosticsEngine &Diag;
88 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
89 : Diag(Diag), IncludePath(false) {}
90 ~ClangDiagPathDiagConsumer() override {}
91 StringRef getName() const override { return "ClangDiags"; }
93 bool supportsLogicalOpControlFlow() const override { return true; }
94 bool supportsCrossFileDiagnostics() const override { return true; }
96 PathGenerationScheme getGenerationScheme() const override {
97 return IncludePath ? Minimal : None;
104 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
105 FilesMade *filesMade) override {
106 unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
107 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
109 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
110 E = Diags.end(); I != E; ++I) {
111 const PathDiagnostic *PD = *I;
112 SourceLocation WarnLoc = PD->getLocation().asLocation();
113 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
114 << PD->path.back()->getRanges();
116 // First, add extra notes, even if paths should not be included.
117 for (const auto &Piece : PD->path) {
118 if (!isa<PathDiagnosticNotePiece>(Piece.get()))
121 SourceLocation NoteLoc = Piece->getLocation().asLocation();
122 Diag.Report(NoteLoc, NoteID) << Piece->getString()
123 << Piece->getRanges();
129 // Then, add the path notes if necessary.
130 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
131 for (const auto &Piece : FlatPath) {
132 if (isa<PathDiagnosticNotePiece>(Piece.get()))
135 SourceLocation NoteLoc = Piece->getLocation().asLocation();
136 Diag.Report(NoteLoc, NoteID) << Piece->getString()
137 << Piece->getRanges();
142 } // end anonymous namespace
144 //===----------------------------------------------------------------------===//
145 // AnalysisConsumer declaration.
146 //===----------------------------------------------------------------------===//
150 class AnalysisConsumer : public AnalysisASTConsumer,
151 public RecursiveASTVisitor<AnalysisConsumer> {
157 typedef unsigned AnalysisMode;
159 /// Mode of the analyzes while recursively visiting Decls.
160 AnalysisMode RecVisitorMode;
161 /// Bug Reporter to use while recursively visiting Decls.
162 BugReporter *RecVisitorBR;
166 const Preprocessor &PP;
167 const std::string OutDir;
168 AnalyzerOptionsRef Opts;
169 ArrayRef<std::string> Plugins;
170 CodeInjector *Injector;
172 /// \brief Stores the declarations from the local translation unit.
173 /// Note, we pre-compute the local declarations at parse time as an
174 /// optimization to make sure we do not deserialize everything from disk.
175 /// The local declaration to all declarations ratio might be very small when
176 /// working with a PCH file.
177 SetOfDecls LocalTUDecls;
179 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
180 PathDiagnosticConsumers PathConsumers;
182 StoreManagerCreator CreateStoreMgr;
183 ConstraintManagerCreator CreateConstraintMgr;
185 std::unique_ptr<CheckerManager> checkerMgr;
186 std::unique_ptr<AnalysisManager> Mgr;
188 /// Time the analyzes time of each translation unit.
189 static llvm::Timer* TUTotalTimer;
191 /// The information about analyzed functions shared throughout the
192 /// translation unit.
193 FunctionSummariesTy FunctionSummaries;
195 AnalysisConsumer(const Preprocessor &pp, const std::string &outdir,
196 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
197 CodeInjector *injector)
198 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr), PP(pp),
199 OutDir(outdir), Opts(std::move(opts)), Plugins(plugins),
201 DigestAnalyzerOptions();
202 if (Opts->PrintStats) {
203 llvm::EnableStatistics(false);
204 TUTotalTimer = new llvm::Timer("time", "Analyzer Total Time");
208 ~AnalysisConsumer() override {
209 if (Opts->PrintStats) {
211 llvm::PrintStatistics();
215 void DigestAnalyzerOptions() {
216 if (Opts->AnalysisDiagOpt != PD_NONE) {
217 // Create the PathDiagnosticConsumer.
218 ClangDiagPathDiagConsumer *clangDiags =
219 new ClangDiagPathDiagConsumer(PP.getDiagnostics());
220 PathConsumers.push_back(clangDiags);
222 if (Opts->AnalysisDiagOpt == PD_TEXT) {
223 clangDiags->enablePaths();
225 } else if (!OutDir.empty()) {
226 switch (Opts->AnalysisDiagOpt) {
228 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
230 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \
232 #include "clang/StaticAnalyzer/Core/Analyses.def"
237 // Create the analyzer component creators.
238 switch (Opts->AnalysisStoreOpt) {
240 llvm_unreachable("Unknown store manager.");
241 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
242 case NAME##Model: CreateStoreMgr = CREATEFN; break;
243 #include "clang/StaticAnalyzer/Core/Analyses.def"
246 switch (Opts->AnalysisConstraintsOpt) {
248 llvm_unreachable("Unknown constraint manager.");
249 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
250 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
251 #include "clang/StaticAnalyzer/Core/Analyses.def"
255 void DisplayFunction(const Decl *D, AnalysisMode Mode,
256 ExprEngine::InliningModes IMode) {
257 if (!Opts->AnalyzerDisplayProgress)
260 SourceManager &SM = Mgr->getASTContext().getSourceManager();
261 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
263 llvm::errs() << "ANALYZE";
265 if (Mode == AM_Syntax)
266 llvm::errs() << " (Syntax)";
267 else if (Mode == AM_Path) {
268 llvm::errs() << " (Path, ";
270 case ExprEngine::Inline_Minimal:
271 llvm::errs() << " Inline_Minimal";
273 case ExprEngine::Inline_Regular:
274 llvm::errs() << " Inline_Regular";
280 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
282 llvm::errs() << ": " << Loc.getFilename() << ' '
283 << getFunctionName(D) << '\n';
287 void Initialize(ASTContext &Context) override {
289 checkerMgr = createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
290 PP.getDiagnostics());
292 Mgr = llvm::make_unique<AnalysisManager>(
293 *Ctx, PP.getDiagnostics(), PP.getLangOpts(), PathConsumers,
294 CreateStoreMgr, CreateConstraintMgr, checkerMgr.get(), *Opts, Injector);
297 /// \brief Store the top level decls in the set to be processed later on.
298 /// (Doing this pre-processing avoids deserialization of data from PCH.)
299 bool HandleTopLevelDecl(DeclGroupRef D) override;
300 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
302 void HandleTranslationUnit(ASTContext &C) override;
304 /// \brief Determine which inlining mode should be used when this function is
305 /// analyzed. This allows to redefine the default inlining policies when
306 /// analyzing a given function.
307 ExprEngine::InliningModes
308 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
310 /// \brief Build the call graph for all the top level decls of this TU and
311 /// use it to define the order in which the functions should be visited.
312 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
314 /// \brief Run analyzes(syntax or path sensitive) on the given function.
315 /// \param Mode - determines if we are requesting syntax only or path
316 /// sensitive only analysis.
317 /// \param VisitedCallees - The output parameter, which is populated with the
318 /// set of functions which should be considered analyzed after analyzing the
319 /// given root function.
320 void HandleCode(Decl *D, AnalysisMode Mode,
321 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
322 SetOfConstDecls *VisitedCallees = nullptr);
324 void RunPathSensitiveChecks(Decl *D,
325 ExprEngine::InliningModes IMode,
326 SetOfConstDecls *VisitedCallees);
327 void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
328 ExprEngine::InliningModes IMode,
329 SetOfConstDecls *VisitedCallees);
331 /// Visitors for the RecursiveASTVisitor.
332 bool shouldWalkTypesOfTypeLocs() const { return false; }
334 /// Handle callbacks for arbitrary Decls.
335 bool VisitDecl(Decl *D) {
336 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
337 if (Mode & AM_Syntax)
338 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
342 bool VisitFunctionDecl(FunctionDecl *FD) {
343 IdentifierInfo *II = FD->getIdentifier();
344 if (II && II->getName().startswith("__inline"))
347 // We skip function template definitions, as their semantics is
348 // only determined when they are instantiated.
349 if (FD->isThisDeclarationADefinition() &&
350 !FD->isDependentContext()) {
351 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
352 HandleCode(FD, RecVisitorMode);
357 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
358 if (MD->isThisDeclarationADefinition()) {
359 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
360 HandleCode(MD, RecVisitorMode);
365 bool VisitBlockDecl(BlockDecl *BD) {
367 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
368 // Since we skip function template definitions, we should skip blocks
369 // declared in those functions as well.
370 if (!BD->isDependentContext()) {
371 HandleCode(BD, RecVisitorMode);
377 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
378 PathConsumers.push_back(Consumer);
382 void storeTopLevelDecls(DeclGroupRef DG);
383 std::string getFunctionName(const Decl *D);
385 /// \brief Check if we should skip (not analyze) the given function.
386 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
389 } // end anonymous namespace
392 //===----------------------------------------------------------------------===//
393 // AnalysisConsumer implementation.
394 //===----------------------------------------------------------------------===//
395 llvm::Timer* AnalysisConsumer::TUTotalTimer = nullptr;
397 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
398 storeTopLevelDecls(DG);
402 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
403 storeTopLevelDecls(DG);
406 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
407 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
409 // Skip ObjCMethodDecl, wait for the objc container to avoid
411 if (isa<ObjCMethodDecl>(*I))
414 LocalTUDecls.push_back(*I);
418 static bool shouldSkipFunction(const Decl *D,
419 const SetOfConstDecls &Visited,
420 const SetOfConstDecls &VisitedAsTopLevel) {
421 if (VisitedAsTopLevel.count(D))
424 // We want to re-analyse the functions as top level in the following cases:
425 // - The 'init' methods should be reanalyzed because
426 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
427 // 'nil' and unless we analyze the 'init' functions as top level, we will
428 // not catch errors within defensive code.
429 // - We want to reanalyze all ObjC methods as top level to report Retain
430 // Count naming convention errors more aggressively.
431 if (isa<ObjCMethodDecl>(D))
433 // We also want to reanalyze all C++ copy and move assignment operators to
434 // separately check the two cases where 'this' aliases with the parameter and
435 // where it may not. (cplusplus.SelfAssignmentChecker)
436 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
437 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
441 // Otherwise, if we visited the function before, do not reanalyze it.
442 return Visited.count(D);
445 ExprEngine::InliningModes
446 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
447 const SetOfConstDecls &Visited) {
448 // We want to reanalyze all ObjC methods as top level to report Retain
449 // Count naming convention errors more aggressively. But we should tune down
450 // inlining when reanalyzing an already inlined function.
451 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
452 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
453 if (ObjCM->getMethodFamily() != OMF_init)
454 return ExprEngine::Inline_Minimal;
457 return ExprEngine::Inline_Regular;
460 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
461 // Build the Call Graph by adding all the top level declarations to the graph.
462 // Note: CallGraph can trigger deserialization of more items from a pch
463 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
464 // We rely on random access to add the initially processed Decls to CG.
466 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
467 CG.addToCallGraph(LocalTUDecls[i]);
470 // Walk over all of the call graph nodes in topological order, so that we
471 // analyze parents before the children. Skip the functions inlined into
472 // the previously processed functions. Use external Visited set to identify
473 // inlined functions. The topological order allows the "do not reanalyze
474 // previously inlined function" performance heuristic to be triggered more
476 SetOfConstDecls Visited;
477 SetOfConstDecls VisitedAsTopLevel;
478 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
479 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
480 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
481 NumFunctionTopLevel++;
483 CallGraphNode *N = *I;
484 Decl *D = N->getDecl();
486 // Skip the abstract root node.
490 // Skip the functions which have been processed already or previously
492 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
495 // Analyze the function.
496 SetOfConstDecls VisitedCallees;
498 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
499 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
501 // Add the visited callees to the global visited set.
502 for (const Decl *Callee : VisitedCallees)
503 // Decls from CallGraph are already canonical. But Decls coming from
504 // CallExprs may be not. We should canonicalize them manually.
505 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
506 : Callee->getCanonicalDecl());
507 VisitedAsTopLevel.insert(D);
511 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
512 // Don't run the actions if an error has occurred with parsing the file.
513 DiagnosticsEngine &Diags = PP.getDiagnostics();
514 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
517 // Don't analyze if the user explicitly asked for no checks to be performed
519 if (Opts->DisableAllChecks)
523 if (TUTotalTimer) TUTotalTimer->startTimer();
525 // Introduce a scope to destroy BR before Mgr.
526 BugReporter BR(*Mgr);
527 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
528 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
530 // Run the AST-only checks using the order in which functions are defined.
531 // If inlining is not turned on, use the simplest function order for path
532 // sensitive analyzes as well.
533 RecVisitorMode = AM_Syntax;
534 if (!Mgr->shouldInlineCall())
535 RecVisitorMode |= AM_Path;
538 // Process all the top level declarations.
540 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
541 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
542 // random access. By doing so, we automatically compensate for iterators
543 // possibly being invalidated, although this is a bit slower.
544 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
545 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
546 TraverseDecl(LocalTUDecls[i]);
549 if (Mgr->shouldInlineCall())
550 HandleDeclsCallGraph(LocalTUDeclsSize);
552 // After all decls handled, run checkers on the entire TranslationUnit.
553 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
555 RecVisitorBR = nullptr;
558 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
559 // FIXME: This should be replaced with something that doesn't rely on
560 // side-effects in PathDiagnosticConsumer's destructor. This is required when
561 // used with option -disable-free.
564 if (TUTotalTimer) TUTotalTimer->stopTimer();
566 // Count how many basic blocks we have not covered.
567 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
568 if (NumBlocksInAnalyzedFunctions > 0)
569 PercentReachableBlocks =
570 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
571 NumBlocksInAnalyzedFunctions;
575 std::string AnalysisConsumer::getFunctionName(const Decl *D) {
577 llvm::raw_string_ostream OS(Str);
579 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
580 OS << FD->getQualifiedNameAsString();
582 // In C++, there are overloads.
583 if (Ctx->getLangOpts().CPlusPlus) {
585 for (const auto &P : FD->parameters()) {
586 if (P != *FD->param_begin())
588 OS << P->getType().getAsString();
593 } else if (isa<BlockDecl>(D)) {
594 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
597 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
601 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
603 // FIXME: copy-pasted from CGDebugInfo.cpp.
604 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
605 const DeclContext *DC = OMD->getDeclContext();
606 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
607 OS << OID->getName();
608 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
609 OS << OID->getName();
610 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
611 if (OC->IsClassExtension()) {
612 OS << OC->getClassInterface()->getName();
614 OS << OC->getIdentifier()->getNameStart() << '('
615 << OC->getIdentifier()->getNameStart() << ')';
617 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
618 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
619 << OCD->getIdentifier()->getNameStart() << ')';
620 } else if (isa<ObjCProtocolDecl>(DC)) {
621 // We can extract the type of the class from the self pointer.
622 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
624 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
625 ClassTy.print(OS, PrintingPolicy(LangOptions()));
628 OS << ' ' << OMD->getSelector().getAsString() << ']';
635 AnalysisConsumer::AnalysisMode
636 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
637 if (!Opts->AnalyzeSpecificFunction.empty() &&
638 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
641 // Unless -analyze-all is specified, treat decls differently depending on
642 // where they came from:
643 // - Main source file: run both path-sensitive and non-path-sensitive checks.
644 // - Header files: run non-path-sensitive checks only.
645 // - System headers: don't run any checks.
646 SourceManager &SM = Ctx->getSourceManager();
647 const Stmt *Body = D->getBody();
648 SourceLocation SL = Body ? Body->getLocStart() : D->getLocation();
649 SL = SM.getExpansionLoc(SL);
651 if (!Opts->AnalyzeAll && !SM.isWrittenInMainFile(SL)) {
652 if (SL.isInvalid() || SM.isInSystemHeader(SL))
654 return Mode & ~AM_Path;
660 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
661 ExprEngine::InliningModes IMode,
662 SetOfConstDecls *VisitedCallees) {
665 Mode = getModeForDecl(D, Mode);
669 // Clear the AnalysisManager of old AnalysisDeclContexts.
670 Mgr->ClearContexts();
671 // Ignore autosynthesized code.
672 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
675 DisplayFunction(D, Mode, IMode);
676 CFG *DeclCFG = Mgr->getCFG(D);
678 unsigned CFGSize = DeclCFG->size();
679 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
682 BugReporter BR(*Mgr);
684 if (Mode & AM_Syntax)
685 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
686 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
687 RunPathSensitiveChecks(D, IMode, VisitedCallees);
688 if (IMode != ExprEngine::Inline_Minimal)
689 NumFunctionsAnalyzed++;
693 //===----------------------------------------------------------------------===//
694 // Path-sensitive checking.
695 //===----------------------------------------------------------------------===//
697 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
698 ExprEngine::InliningModes IMode,
699 SetOfConstDecls *VisitedCallees) {
700 // Construct the analysis engine. First check if the CFG is valid.
701 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
705 // See if the LiveVariables analysis scales.
706 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
709 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
711 // Set the graph auditor.
712 std::unique_ptr<ExplodedNode::Auditor> Auditor;
713 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
714 Auditor = CreateUbiViz();
715 ExplodedNode::SetAuditor(Auditor.get());
718 // Execute the worklist algorithm.
719 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
720 Mgr->options.getMaxNodesPerTopLevelFunction());
722 // Release the auditor (if any) so that it doesn't monitor the graph
723 // created BugReporter.
724 ExplodedNode::SetAuditor(nullptr);
726 // Visualize the exploded graph.
727 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
728 Eng.ViewGraph(Mgr->options.TrimGraph);
731 Eng.getBugReporter().FlushReports();
734 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
735 ExprEngine::InliningModes IMode,
736 SetOfConstDecls *Visited) {
738 switch (Mgr->getLangOpts().getGC()) {
739 case LangOptions::NonGC:
740 ActionExprEngine(D, false, IMode, Visited);
743 case LangOptions::GCOnly:
744 ActionExprEngine(D, true, IMode, Visited);
747 case LangOptions::HybridGC:
748 ActionExprEngine(D, false, IMode, Visited);
749 ActionExprEngine(D, true, IMode, Visited);
754 //===----------------------------------------------------------------------===//
755 // AnalysisConsumer creation.
756 //===----------------------------------------------------------------------===//
758 std::unique_ptr<AnalysisASTConsumer>
759 ento::CreateAnalysisConsumer(CompilerInstance &CI) {
760 // Disable the effects of '-Werror' when using the AnalysisConsumer.
761 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
763 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
764 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
766 return llvm::make_unique<AnalysisConsumer>(
767 CI.getPreprocessor(), CI.getFrontendOpts().OutputFile, analyzerOpts,
768 CI.getFrontendOpts().Plugins,
769 hasModelPath ? new ModelInjector(CI) : nullptr);
772 //===----------------------------------------------------------------------===//
773 // Ubigraph Visualization. FIXME: Move to separate file.
774 //===----------------------------------------------------------------------===//
778 class UbigraphViz : public ExplodedNode::Auditor {
779 std::unique_ptr<raw_ostream> Out;
780 std::string Filename;
783 typedef llvm::DenseMap<void*,unsigned> VMap;
787 UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename);
789 ~UbigraphViz() override;
791 void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) override;
794 } // end anonymous namespace
796 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz() {
799 llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P);
800 llvm::errs() << "Writing '" << P << "'.\n";
802 auto Stream = llvm::make_unique<llvm::raw_fd_ostream>(FD, true);
804 return llvm::make_unique<UbigraphViz>(std::move(Stream), P);
807 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
809 assert (Src != Dst && "Self-edges are not allowed.");
811 // Lookup the Src. If it is a new node, it's a root.
812 VMap::iterator SrcI= M.find(Src);
815 if (SrcI == M.end()) {
816 M[Src] = SrcID = Cntr++;
817 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
820 SrcID = SrcI->second;
823 VMap::iterator DstI= M.find(Dst);
826 if (DstI == M.end()) {
827 M[Dst] = DstID = Cntr++;
828 *Out << "('vertex', " << DstID << ")\n";
831 // We have hit DstID before. Change its style to reflect a cache hit.
832 DstID = DstI->second;
833 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
837 *Out << "('edge', " << SrcID << ", " << DstID
838 << ", ('arrow','true'), ('oriented', 'true'))\n";
841 UbigraphViz::UbigraphViz(std::unique_ptr<raw_ostream> OutStream,
843 : Out(std::move(OutStream)), Filename(Filename), Cntr(0) {
845 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
846 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
847 " ('size', '1.5'))\n";
850 UbigraphViz::~UbigraphViz() {
852 llvm::errs() << "Running 'ubiviz' program... ";
855 if (auto Path = llvm::sys::findProgramByName("ubiviz"))
857 const char *args[] = {Ubiviz.c_str(), Filename.c_str(), nullptr};
859 if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], nullptr, nullptr, 0, 0,
861 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
865 llvm::sys::fs::remove(Filename);