clang API Documentation
00001 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // "Meta" ASTConsumer for running different source analyses. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h" 00015 #include "clang/AST/ASTConsumer.h" 00016 #include "clang/AST/DataRecursiveASTVisitor.h" 00017 #include "clang/AST/Decl.h" 00018 #include "clang/AST/DeclCXX.h" 00019 #include "clang/AST/DeclObjC.h" 00020 #include "clang/AST/ParentMap.h" 00021 #include "clang/Analysis/CodeInjector.h" 00022 #include "clang/Analysis/Analyses/LiveVariables.h" 00023 #include "clang/Analysis/CFG.h" 00024 #include "clang/Analysis/CallGraph.h" 00025 #include "clang/Basic/FileManager.h" 00026 #include "clang/Basic/SourceManager.h" 00027 #include "clang/Lex/Preprocessor.h" 00028 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 00029 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 00030 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 00031 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 00032 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 00033 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 00034 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 00035 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 00036 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h" 00037 #include "clang/Frontend/CompilerInstance.h" 00038 #include "llvm/ADT/DepthFirstIterator.h" 00039 #include "llvm/ADT/PostOrderIterator.h" 00040 #include "llvm/ADT/SmallPtrSet.h" 00041 #include "llvm/ADT/Statistic.h" 00042 #include "llvm/Support/FileSystem.h" 00043 #include "llvm/Support/Path.h" 00044 #include "llvm/Support/Program.h" 00045 #include "llvm/Support/Timer.h" 00046 #include "llvm/Support/raw_ostream.h" 00047 #include "ModelInjector.h" 00048 #include <memory> 00049 #include <queue> 00050 00051 using namespace clang; 00052 using namespace ento; 00053 using llvm::SmallPtrSet; 00054 00055 #define DEBUG_TYPE "AnalysisConsumer" 00056 00057 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz(); 00058 00059 STATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 00060 STATISTIC(NumFunctionsAnalyzed, 00061 "The # of functions and blocks analyzed (as top level " 00062 "with inlining turned on)."); 00063 STATISTIC(NumBlocksInAnalyzedFunctions, 00064 "The # of basic blocks in the analyzed functions."); 00065 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 00066 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 00067 00068 //===----------------------------------------------------------------------===// 00069 // Special PathDiagnosticConsumers. 00070 //===----------------------------------------------------------------------===// 00071 00072 void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 00073 PathDiagnosticConsumers &C, 00074 const std::string &prefix, 00075 const Preprocessor &PP) { 00076 createHTMLDiagnosticConsumer(AnalyzerOpts, C, 00077 llvm::sys::path::parent_path(prefix), PP); 00078 createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP); 00079 } 00080 00081 void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 00082 PathDiagnosticConsumers &C, 00083 const std::string &Prefix, 00084 const clang::Preprocessor &PP) { 00085 llvm_unreachable("'text' consumer should be enabled on ClangDiags"); 00086 } 00087 00088 namespace { 00089 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer { 00090 DiagnosticsEngine &Diag; 00091 bool IncludePath; 00092 public: 00093 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) 00094 : Diag(Diag), IncludePath(false) {} 00095 virtual ~ClangDiagPathDiagConsumer() {} 00096 StringRef getName() const override { return "ClangDiags"; } 00097 00098 bool supportsLogicalOpControlFlow() const override { return true; } 00099 bool supportsCrossFileDiagnostics() const override { return true; } 00100 00101 PathGenerationScheme getGenerationScheme() const override { 00102 return IncludePath ? Minimal : None; 00103 } 00104 00105 void enablePaths() { 00106 IncludePath = true; 00107 } 00108 00109 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, 00110 FilesMade *filesMade) override { 00111 unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0"); 00112 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0"); 00113 00114 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(), 00115 E = Diags.end(); I != E; ++I) { 00116 const PathDiagnostic *PD = *I; 00117 SourceLocation WarnLoc = PD->getLocation().asLocation(); 00118 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription() 00119 << PD->path.back()->getRanges(); 00120 00121 if (!IncludePath) 00122 continue; 00123 00124 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true); 00125 for (PathPieces::const_iterator PI = FlatPath.begin(), 00126 PE = FlatPath.end(); 00127 PI != PE; ++PI) { 00128 SourceLocation NoteLoc = (*PI)->getLocation().asLocation(); 00129 Diag.Report(NoteLoc, NoteID) << (*PI)->getString() 00130 << (*PI)->getRanges(); 00131 } 00132 } 00133 } 00134 }; 00135 } // end anonymous namespace 00136 00137 //===----------------------------------------------------------------------===// 00138 // AnalysisConsumer declaration. 00139 //===----------------------------------------------------------------------===// 00140 00141 namespace { 00142 00143 class AnalysisConsumer : public AnalysisASTConsumer, 00144 public DataRecursiveASTVisitor<AnalysisConsumer> { 00145 enum { 00146 AM_None = 0, 00147 AM_Syntax = 0x1, 00148 AM_Path = 0x2 00149 }; 00150 typedef unsigned AnalysisMode; 00151 00152 /// Mode of the analyzes while recursively visiting Decls. 00153 AnalysisMode RecVisitorMode; 00154 /// Bug Reporter to use while recursively visiting Decls. 00155 BugReporter *RecVisitorBR; 00156 00157 public: 00158 ASTContext *Ctx; 00159 const Preprocessor &PP; 00160 const std::string OutDir; 00161 AnalyzerOptionsRef Opts; 00162 ArrayRef<std::string> Plugins; 00163 CodeInjector *Injector; 00164 00165 /// \brief Stores the declarations from the local translation unit. 00166 /// Note, we pre-compute the local declarations at parse time as an 00167 /// optimization to make sure we do not deserialize everything from disk. 00168 /// The local declaration to all declarations ratio might be very small when 00169 /// working with a PCH file. 00170 SetOfDecls LocalTUDecls; 00171 00172 // Set of PathDiagnosticConsumers. Owned by AnalysisManager. 00173 PathDiagnosticConsumers PathConsumers; 00174 00175 StoreManagerCreator CreateStoreMgr; 00176 ConstraintManagerCreator CreateConstraintMgr; 00177 00178 std::unique_ptr<CheckerManager> checkerMgr; 00179 std::unique_ptr<AnalysisManager> Mgr; 00180 00181 /// Time the analyzes time of each translation unit. 00182 static llvm::Timer* TUTotalTimer; 00183 00184 /// The information about analyzed functions shared throughout the 00185 /// translation unit. 00186 FunctionSummariesTy FunctionSummaries; 00187 00188 AnalysisConsumer(const Preprocessor& pp, 00189 const std::string& outdir, 00190 AnalyzerOptionsRef opts, 00191 ArrayRef<std::string> plugins, 00192 CodeInjector *injector) 00193 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr), PP(pp), 00194 OutDir(outdir), Opts(opts), Plugins(plugins), Injector(injector) { 00195 DigestAnalyzerOptions(); 00196 if (Opts->PrintStats) { 00197 llvm::EnableStatistics(); 00198 TUTotalTimer = new llvm::Timer("Analyzer Total Time"); 00199 } 00200 } 00201 00202 ~AnalysisConsumer() { 00203 if (Opts->PrintStats) 00204 delete TUTotalTimer; 00205 } 00206 00207 void DigestAnalyzerOptions() { 00208 if (Opts->AnalysisDiagOpt != PD_NONE) { 00209 // Create the PathDiagnosticConsumer. 00210 ClangDiagPathDiagConsumer *clangDiags = 00211 new ClangDiagPathDiagConsumer(PP.getDiagnostics()); 00212 PathConsumers.push_back(clangDiags); 00213 00214 if (Opts->AnalysisDiagOpt == PD_TEXT) { 00215 clangDiags->enablePaths(); 00216 00217 } else if (!OutDir.empty()) { 00218 switch (Opts->AnalysisDiagOpt) { 00219 default: 00220 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \ 00221 case PD_##NAME: \ 00222 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \ 00223 break; 00224 #include "clang/StaticAnalyzer/Core/Analyses.def" 00225 } 00226 } 00227 } 00228 00229 // Create the analyzer component creators. 00230 switch (Opts->AnalysisStoreOpt) { 00231 default: 00232 llvm_unreachable("Unknown store manager."); 00233 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 00234 case NAME##Model: CreateStoreMgr = CREATEFN; break; 00235 #include "clang/StaticAnalyzer/Core/Analyses.def" 00236 } 00237 00238 switch (Opts->AnalysisConstraintsOpt) { 00239 default: 00240 llvm_unreachable("Unknown constraint manager."); 00241 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 00242 case NAME##Model: CreateConstraintMgr = CREATEFN; break; 00243 #include "clang/StaticAnalyzer/Core/Analyses.def" 00244 } 00245 } 00246 00247 void DisplayFunction(const Decl *D, AnalysisMode Mode, 00248 ExprEngine::InliningModes IMode) { 00249 if (!Opts->AnalyzerDisplayProgress) 00250 return; 00251 00252 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 00253 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 00254 if (Loc.isValid()) { 00255 llvm::errs() << "ANALYZE"; 00256 00257 if (Mode == AM_Syntax) 00258 llvm::errs() << " (Syntax)"; 00259 else if (Mode == AM_Path) { 00260 llvm::errs() << " (Path, "; 00261 switch (IMode) { 00262 case ExprEngine::Inline_Minimal: 00263 llvm::errs() << " Inline_Minimal"; 00264 break; 00265 case ExprEngine::Inline_Regular: 00266 llvm::errs() << " Inline_Regular"; 00267 break; 00268 } 00269 llvm::errs() << ")"; 00270 } 00271 else 00272 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!"); 00273 00274 llvm::errs() << ": " << Loc.getFilename(); 00275 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { 00276 const NamedDecl *ND = cast<NamedDecl>(D); 00277 llvm::errs() << ' ' << *ND << '\n'; 00278 } 00279 else if (isa<BlockDecl>(D)) { 00280 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:" 00281 << Loc.getColumn() << '\n'; 00282 } 00283 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 00284 Selector S = MD->getSelector(); 00285 llvm::errs() << ' ' << S.getAsString(); 00286 } 00287 } 00288 } 00289 00290 void Initialize(ASTContext &Context) override { 00291 Ctx = &Context; 00292 checkerMgr = createCheckerManager(*Opts, PP.getLangOpts(), Plugins, 00293 PP.getDiagnostics()); 00294 00295 Mgr = llvm::make_unique<AnalysisManager>( 00296 *Ctx, PP.getDiagnostics(), PP.getLangOpts(), PathConsumers, 00297 CreateStoreMgr, CreateConstraintMgr, checkerMgr.get(), *Opts, Injector); 00298 } 00299 00300 /// \brief Store the top level decls in the set to be processed later on. 00301 /// (Doing this pre-processing avoids deserialization of data from PCH.) 00302 bool HandleTopLevelDecl(DeclGroupRef D) override; 00303 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override; 00304 00305 void HandleTranslationUnit(ASTContext &C) override; 00306 00307 /// \brief Determine which inlining mode should be used when this function is 00308 /// analyzed. This allows to redefine the default inlining policies when 00309 /// analyzing a given function. 00310 ExprEngine::InliningModes 00311 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited); 00312 00313 /// \brief Build the call graph for all the top level decls of this TU and 00314 /// use it to define the order in which the functions should be visited. 00315 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 00316 00317 /// \brief Run analyzes(syntax or path sensitive) on the given function. 00318 /// \param Mode - determines if we are requesting syntax only or path 00319 /// sensitive only analysis. 00320 /// \param VisitedCallees - The output parameter, which is populated with the 00321 /// set of functions which should be considered analyzed after analyzing the 00322 /// given root function. 00323 void HandleCode(Decl *D, AnalysisMode Mode, 00324 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal, 00325 SetOfConstDecls *VisitedCallees = nullptr); 00326 00327 void RunPathSensitiveChecks(Decl *D, 00328 ExprEngine::InliningModes IMode, 00329 SetOfConstDecls *VisitedCallees); 00330 void ActionExprEngine(Decl *D, bool ObjCGCEnabled, 00331 ExprEngine::InliningModes IMode, 00332 SetOfConstDecls *VisitedCallees); 00333 00334 /// Visitors for the RecursiveASTVisitor. 00335 bool shouldWalkTypesOfTypeLocs() const { return false; } 00336 00337 /// Handle callbacks for arbitrary Decls. 00338 bool VisitDecl(Decl *D) { 00339 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode); 00340 if (Mode & AM_Syntax) 00341 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 00342 return true; 00343 } 00344 00345 bool VisitFunctionDecl(FunctionDecl *FD) { 00346 IdentifierInfo *II = FD->getIdentifier(); 00347 if (II && II->getName().startswith("__inline")) 00348 return true; 00349 00350 // We skip function template definitions, as their semantics is 00351 // only determined when they are instantiated. 00352 if (FD->isThisDeclarationADefinition() && 00353 !FD->isDependentContext()) { 00354 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 00355 HandleCode(FD, RecVisitorMode); 00356 } 00357 return true; 00358 } 00359 00360 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 00361 if (MD->isThisDeclarationADefinition()) { 00362 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 00363 HandleCode(MD, RecVisitorMode); 00364 } 00365 return true; 00366 } 00367 00368 bool VisitBlockDecl(BlockDecl *BD) { 00369 if (BD->hasBody()) { 00370 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 00371 HandleCode(BD, RecVisitorMode); 00372 } 00373 return true; 00374 } 00375 00376 virtual void 00377 AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override { 00378 PathConsumers.push_back(Consumer); 00379 } 00380 00381 private: 00382 void storeTopLevelDecls(DeclGroupRef DG); 00383 00384 /// \brief Check if we should skip (not analyze) the given function. 00385 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode); 00386 00387 }; 00388 } // end anonymous namespace 00389 00390 00391 //===----------------------------------------------------------------------===// 00392 // AnalysisConsumer implementation. 00393 //===----------------------------------------------------------------------===// 00394 llvm::Timer* AnalysisConsumer::TUTotalTimer = nullptr; 00395 00396 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 00397 storeTopLevelDecls(DG); 00398 return true; 00399 } 00400 00401 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 00402 storeTopLevelDecls(DG); 00403 } 00404 00405 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 00406 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 00407 00408 // Skip ObjCMethodDecl, wait for the objc container to avoid 00409 // analyzing twice. 00410 if (isa<ObjCMethodDecl>(*I)) 00411 continue; 00412 00413 LocalTUDecls.push_back(*I); 00414 } 00415 } 00416 00417 static bool shouldSkipFunction(const Decl *D, 00418 const SetOfConstDecls &Visited, 00419 const SetOfConstDecls &VisitedAsTopLevel) { 00420 if (VisitedAsTopLevel.count(D)) 00421 return true; 00422 00423 // We want to re-analyse the functions as top level in the following cases: 00424 // - The 'init' methods should be reanalyzed because 00425 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 00426 // 'nil' and unless we analyze the 'init' functions as top level, we will 00427 // not catch errors within defensive code. 00428 // - We want to reanalyze all ObjC methods as top level to report Retain 00429 // Count naming convention errors more aggressively. 00430 if (isa<ObjCMethodDecl>(D)) 00431 return false; 00432 00433 // Otherwise, if we visited the function before, do not reanalyze it. 00434 return Visited.count(D); 00435 } 00436 00437 ExprEngine::InliningModes 00438 AnalysisConsumer::getInliningModeForFunction(const Decl *D, 00439 const SetOfConstDecls &Visited) { 00440 // We want to reanalyze all ObjC methods as top level to report Retain 00441 // Count naming convention errors more aggressively. But we should tune down 00442 // inlining when reanalyzing an already inlined function. 00443 if (Visited.count(D)) { 00444 assert(isa<ObjCMethodDecl>(D) && 00445 "We are only reanalyzing ObjCMethods."); 00446 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D); 00447 if (ObjCM->getMethodFamily() != OMF_init) 00448 return ExprEngine::Inline_Minimal; 00449 } 00450 00451 return ExprEngine::Inline_Regular; 00452 } 00453 00454 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 00455 // Build the Call Graph by adding all the top level declarations to the graph. 00456 // Note: CallGraph can trigger deserialization of more items from a pch 00457 // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 00458 // We rely on random access to add the initially processed Decls to CG. 00459 CallGraph CG; 00460 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 00461 CG.addToCallGraph(LocalTUDecls[i]); 00462 } 00463 00464 // Walk over all of the call graph nodes in topological order, so that we 00465 // analyze parents before the children. Skip the functions inlined into 00466 // the previously processed functions. Use external Visited set to identify 00467 // inlined functions. The topological order allows the "do not reanalyze 00468 // previously inlined function" performance heuristic to be triggered more 00469 // often. 00470 SetOfConstDecls Visited; 00471 SetOfConstDecls VisitedAsTopLevel; 00472 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG); 00473 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator 00474 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) { 00475 NumFunctionTopLevel++; 00476 00477 CallGraphNode *N = *I; 00478 Decl *D = N->getDecl(); 00479 00480 // Skip the abstract root node. 00481 if (!D) 00482 continue; 00483 00484 // Skip the functions which have been processed already or previously 00485 // inlined. 00486 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel)) 00487 continue; 00488 00489 // Analyze the function. 00490 SetOfConstDecls VisitedCallees; 00491 00492 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited), 00493 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees)); 00494 00495 // Add the visited callees to the global visited set. 00496 for (SetOfConstDecls::iterator I = VisitedCallees.begin(), 00497 E = VisitedCallees.end(); I != E; ++I) { 00498 Visited.insert(*I); 00499 } 00500 VisitedAsTopLevel.insert(D); 00501 } 00502 } 00503 00504 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 00505 // Don't run the actions if an error has occurred with parsing the file. 00506 DiagnosticsEngine &Diags = PP.getDiagnostics(); 00507 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 00508 return; 00509 00510 // Don't analyze if the user explicitly asked for no checks to be performed 00511 // on this file. 00512 if (Opts->DisableAllChecks) 00513 return; 00514 00515 { 00516 if (TUTotalTimer) TUTotalTimer->startTimer(); 00517 00518 // Introduce a scope to destroy BR before Mgr. 00519 BugReporter BR(*Mgr); 00520 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 00521 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 00522 00523 // Run the AST-only checks using the order in which functions are defined. 00524 // If inlining is not turned on, use the simplest function order for path 00525 // sensitive analyzes as well. 00526 RecVisitorMode = AM_Syntax; 00527 if (!Mgr->shouldInlineCall()) 00528 RecVisitorMode |= AM_Path; 00529 RecVisitorBR = &BR; 00530 00531 // Process all the top level declarations. 00532 // 00533 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 00534 // entries. Thus we don't use an iterator, but rely on LocalTUDecls 00535 // random access. By doing so, we automatically compensate for iterators 00536 // possibly being invalidated, although this is a bit slower. 00537 const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 00538 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 00539 TraverseDecl(LocalTUDecls[i]); 00540 } 00541 00542 if (Mgr->shouldInlineCall()) 00543 HandleDeclsCallGraph(LocalTUDeclsSize); 00544 00545 // After all decls handled, run checkers on the entire TranslationUnit. 00546 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 00547 00548 RecVisitorBR = nullptr; 00549 } 00550 00551 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 00552 // FIXME: This should be replaced with something that doesn't rely on 00553 // side-effects in PathDiagnosticConsumer's destructor. This is required when 00554 // used with option -disable-free. 00555 Mgr.reset(); 00556 00557 if (TUTotalTimer) TUTotalTimer->stopTimer(); 00558 00559 // Count how many basic blocks we have not covered. 00560 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 00561 if (NumBlocksInAnalyzedFunctions > 0) 00562 PercentReachableBlocks = 00563 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 00564 NumBlocksInAnalyzedFunctions; 00565 00566 } 00567 00568 static std::string getFunctionName(const Decl *D) { 00569 if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { 00570 return ID->getSelector().getAsString(); 00571 } 00572 if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) { 00573 IdentifierInfo *II = ND->getIdentifier(); 00574 if (II) 00575 return II->getName(); 00576 } 00577 return ""; 00578 } 00579 00580 AnalysisConsumer::AnalysisMode 00581 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) { 00582 if (!Opts->AnalyzeSpecificFunction.empty() && 00583 getFunctionName(D) != Opts->AnalyzeSpecificFunction) 00584 return AM_None; 00585 00586 // Unless -analyze-all is specified, treat decls differently depending on 00587 // where they came from: 00588 // - Main source file: run both path-sensitive and non-path-sensitive checks. 00589 // - Header files: run non-path-sensitive checks only. 00590 // - System headers: don't run any checks. 00591 SourceManager &SM = Ctx->getSourceManager(); 00592 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 00593 if (!Opts->AnalyzeAll && !SM.isInMainFile(SL)) { 00594 if (SL.isInvalid() || SM.isInSystemHeader(SL)) 00595 return AM_None; 00596 return Mode & ~AM_Path; 00597 } 00598 00599 return Mode; 00600 } 00601 00602 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 00603 ExprEngine::InliningModes IMode, 00604 SetOfConstDecls *VisitedCallees) { 00605 if (!D->hasBody()) 00606 return; 00607 Mode = getModeForDecl(D, Mode); 00608 if (Mode == AM_None) 00609 return; 00610 00611 DisplayFunction(D, Mode, IMode); 00612 CFG *DeclCFG = Mgr->getCFG(D); 00613 if (DeclCFG) { 00614 unsigned CFGSize = DeclCFG->size(); 00615 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize; 00616 } 00617 00618 // Clear the AnalysisManager of old AnalysisDeclContexts. 00619 Mgr->ClearContexts(); 00620 BugReporter BR(*Mgr); 00621 00622 if (Mode & AM_Syntax) 00623 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR); 00624 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) { 00625 RunPathSensitiveChecks(D, IMode, VisitedCallees); 00626 if (IMode != ExprEngine::Inline_Minimal) 00627 NumFunctionsAnalyzed++; 00628 } 00629 } 00630 00631 //===----------------------------------------------------------------------===// 00632 // Path-sensitive checking. 00633 //===----------------------------------------------------------------------===// 00634 00635 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled, 00636 ExprEngine::InliningModes IMode, 00637 SetOfConstDecls *VisitedCallees) { 00638 // Construct the analysis engine. First check if the CFG is valid. 00639 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 00640 if (!Mgr->getCFG(D)) 00641 return; 00642 00643 // See if the LiveVariables analysis scales. 00644 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 00645 return; 00646 00647 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode); 00648 00649 // Set the graph auditor. 00650 std::unique_ptr<ExplodedNode::Auditor> Auditor; 00651 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) { 00652 Auditor = CreateUbiViz(); 00653 ExplodedNode::SetAuditor(Auditor.get()); 00654 } 00655 00656 // Execute the worklist algorithm. 00657 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 00658 Mgr->options.getMaxNodesPerTopLevelFunction()); 00659 00660 // Release the auditor (if any) so that it doesn't monitor the graph 00661 // created BugReporter. 00662 ExplodedNode::SetAuditor(nullptr); 00663 00664 // Visualize the exploded graph. 00665 if (Mgr->options.visualizeExplodedGraphWithGraphViz) 00666 Eng.ViewGraph(Mgr->options.TrimGraph); 00667 00668 // Display warnings. 00669 Eng.getBugReporter().FlushReports(); 00670 } 00671 00672 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 00673 ExprEngine::InliningModes IMode, 00674 SetOfConstDecls *Visited) { 00675 00676 switch (Mgr->getLangOpts().getGC()) { 00677 case LangOptions::NonGC: 00678 ActionExprEngine(D, false, IMode, Visited); 00679 break; 00680 00681 case LangOptions::GCOnly: 00682 ActionExprEngine(D, true, IMode, Visited); 00683 break; 00684 00685 case LangOptions::HybridGC: 00686 ActionExprEngine(D, false, IMode, Visited); 00687 ActionExprEngine(D, true, IMode, Visited); 00688 break; 00689 } 00690 } 00691 00692 //===----------------------------------------------------------------------===// 00693 // AnalysisConsumer creation. 00694 //===----------------------------------------------------------------------===// 00695 00696 std::unique_ptr<AnalysisASTConsumer> 00697 ento::CreateAnalysisConsumer(CompilerInstance &CI) { 00698 // Disable the effects of '-Werror' when using the AnalysisConsumer. 00699 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false); 00700 00701 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts(); 00702 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0; 00703 00704 return llvm::make_unique<AnalysisConsumer>( 00705 CI.getPreprocessor(), CI.getFrontendOpts().OutputFile, analyzerOpts, 00706 CI.getFrontendOpts().Plugins, 00707 hasModelPath ? new ModelInjector(CI) : nullptr); 00708 } 00709 00710 //===----------------------------------------------------------------------===// 00711 // Ubigraph Visualization. FIXME: Move to separate file. 00712 //===----------------------------------------------------------------------===// 00713 00714 namespace { 00715 00716 class UbigraphViz : public ExplodedNode::Auditor { 00717 std::unique_ptr<raw_ostream> Out; 00718 std::string Filename; 00719 unsigned Cntr; 00720 00721 typedef llvm::DenseMap<void*,unsigned> VMap; 00722 VMap M; 00723 00724 public: 00725 UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename); 00726 00727 ~UbigraphViz(); 00728 00729 void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) override; 00730 }; 00731 00732 } // end anonymous namespace 00733 00734 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz() { 00735 SmallString<128> P; 00736 int FD; 00737 llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P); 00738 llvm::errs() << "Writing '" << P.str() << "'.\n"; 00739 00740 auto Stream = llvm::make_unique<llvm::raw_fd_ostream>(FD, true); 00741 00742 return llvm::make_unique<UbigraphViz>(std::move(Stream), P); 00743 } 00744 00745 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 00746 00747 assert (Src != Dst && "Self-edges are not allowed."); 00748 00749 // Lookup the Src. If it is a new node, it's a root. 00750 VMap::iterator SrcI= M.find(Src); 00751 unsigned SrcID; 00752 00753 if (SrcI == M.end()) { 00754 M[Src] = SrcID = Cntr++; 00755 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 00756 } 00757 else 00758 SrcID = SrcI->second; 00759 00760 // Lookup the Dst. 00761 VMap::iterator DstI= M.find(Dst); 00762 unsigned DstID; 00763 00764 if (DstI == M.end()) { 00765 M[Dst] = DstID = Cntr++; 00766 *Out << "('vertex', " << DstID << ")\n"; 00767 } 00768 else { 00769 // We have hit DstID before. Change its style to reflect a cache hit. 00770 DstID = DstI->second; 00771 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 00772 } 00773 00774 // Add the edge. 00775 *Out << "('edge', " << SrcID << ", " << DstID 00776 << ", ('arrow','true'), ('oriented', 'true'))\n"; 00777 } 00778 00779 UbigraphViz::UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename) 00780 : Out(std::move(Out)), Filename(Filename), Cntr(0) { 00781 00782 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 00783 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 00784 " ('size', '1.5'))\n"; 00785 } 00786 00787 UbigraphViz::~UbigraphViz() { 00788 Out.reset(); 00789 llvm::errs() << "Running 'ubiviz' program... "; 00790 std::string ErrMsg; 00791 std::string Ubiviz; 00792 if (auto Path = llvm::sys::findProgramByName("ubiviz")) 00793 Ubiviz = *Path; 00794 std::vector<const char*> args; 00795 args.push_back(Ubiviz.c_str()); 00796 args.push_back(Filename.c_str()); 00797 args.push_back(nullptr); 00798 00799 if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], nullptr, nullptr, 0, 0, 00800 &ErrMsg)) { 00801 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 00802 } 00803 00804 // Delete the file. 00805 llvm::sys::fs::remove(Filename); 00806 }