AnalysisConsumer.cpp revision 55fc873017f10f6f566b182b70f6fc22aefa3464
1//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// 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// "Meta" ASTConsumer for running different source analyses. 11// 12//===----------------------------------------------------------------------===// 13 14#define DEBUG_TYPE "AnalysisConsumer" 15 16#include "AnalysisConsumer.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/Decl.h" 19#include "clang/AST/DeclCXX.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/ParentMap.h" 22#include "clang/AST/RecursiveASTVisitor.h" 23#include "clang/Analysis/Analyses/LiveVariables.h" 24#include "clang/Analysis/CFG.h" 25#include "clang/Analysis/CallGraph.h" 26#include "clang/Basic/FileManager.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/Lex/Preprocessor.h" 29#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 30#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 31#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 32#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 33#include "clang/StaticAnalyzer/Core/CheckerManager.h" 34#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 35#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 36#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 37#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h" 38#include "llvm/ADT/DepthFirstIterator.h" 39#include "llvm/ADT/OwningPtr.h" 40#include "llvm/ADT/SmallPtrSet.h" 41#include "llvm/ADT/Statistic.h" 42#include "llvm/Support/Path.h" 43#include "llvm/Support/Program.h" 44#include "llvm/Support/Timer.h" 45#include "llvm/Support/raw_ostream.h" 46#include <queue> 47 48using namespace clang; 49using namespace ento; 50using llvm::SmallPtrSet; 51 52static ExplodedNode::Auditor* CreateUbiViz(); 53 54STATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 55STATISTIC(NumFunctionsAnalyzed, "The # of functions analysed (as top level)."); 56STATISTIC(NumBlocksInAnalyzedFunctions, 57 "The # of basic blocks in the analyzed functions."); 58STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 59STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 60 61//===----------------------------------------------------------------------===// 62// Special PathDiagnosticConsumers. 63//===----------------------------------------------------------------------===// 64 65static void createPlistHTMLDiagnosticConsumer(PathDiagnosticConsumers &C, 66 const std::string &prefix, 67 const Preprocessor &PP) { 68 createHTMLDiagnosticConsumer(C, llvm::sys::path::parent_path(prefix), PP); 69 createPlistDiagnosticConsumer(C, prefix, PP); 70} 71 72namespace { 73class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer { 74 DiagnosticsEngine &Diag; 75public: 76 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) : Diag(Diag) {} 77 virtual ~ClangDiagPathDiagConsumer() {} 78 virtual StringRef getName() const { return "ClangDiags"; } 79 virtual PathGenerationScheme getGenerationScheme() const { return None; } 80 81 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, 82 FilesMade *filesMade) { 83 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(), 84 E = Diags.end(); I != E; ++I) { 85 const PathDiagnostic *PD = *I; 86 StringRef desc = PD->getShortDescription(); 87 SmallString<512> TmpStr; 88 llvm::raw_svector_ostream Out(TmpStr); 89 for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) { 90 if (*I == '%') 91 Out << "%%"; 92 else 93 Out << *I; 94 } 95 Out.flush(); 96 unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning, 97 TmpStr); 98 SourceLocation L = PD->getLocation().asLocation(); 99 DiagnosticBuilder diagBuilder = Diag.Report(L, ErrorDiag); 100 101 // Get the ranges from the last point in the path. 102 ArrayRef<SourceRange> Ranges = PD->path.back()->getRanges(); 103 104 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), 105 E = Ranges.end(); I != E; ++I) { 106 diagBuilder << *I; 107 } 108 } 109 } 110}; 111} // end anonymous namespace 112 113//===----------------------------------------------------------------------===// 114// AnalysisConsumer declaration. 115//===----------------------------------------------------------------------===// 116 117namespace { 118 119class AnalysisConsumer : public ASTConsumer, 120 public RecursiveASTVisitor<AnalysisConsumer> { 121 enum { 122 AM_None = 0, 123 AM_Syntax = 0x1, 124 AM_Path = 0x2 125 }; 126 typedef unsigned AnalysisMode; 127 128 /// Mode of the analyzes while recursively visiting Decls. 129 AnalysisMode RecVisitorMode; 130 /// Bug Reporter to use while recursively visiting Decls. 131 BugReporter *RecVisitorBR; 132 133public: 134 ASTContext *Ctx; 135 const Preprocessor &PP; 136 const std::string OutDir; 137 AnalyzerOptionsRef Opts; 138 ArrayRef<std::string> Plugins; 139 140 /// \brief Stores the declarations from the local translation unit. 141 /// Note, we pre-compute the local declarations at parse time as an 142 /// optimization to make sure we do not deserialize everything from disk. 143 /// The local declaration to all declarations ratio might be very small when 144 /// working with a PCH file. 145 SetOfDecls LocalTUDecls; 146 147 // Set of PathDiagnosticConsumers. Owned by AnalysisManager. 148 PathDiagnosticConsumers PathConsumers; 149 150 StoreManagerCreator CreateStoreMgr; 151 ConstraintManagerCreator CreateConstraintMgr; 152 153 OwningPtr<CheckerManager> checkerMgr; 154 OwningPtr<AnalysisManager> Mgr; 155 156 /// Time the analyzes time of each translation unit. 157 static llvm::Timer* TUTotalTimer; 158 159 /// The information about analyzed functions shared throughout the 160 /// translation unit. 161 FunctionSummariesTy FunctionSummaries; 162 163 AnalysisConsumer(const Preprocessor& pp, 164 const std::string& outdir, 165 AnalyzerOptionsRef opts, 166 ArrayRef<std::string> plugins) 167 : RecVisitorMode(0), RecVisitorBR(0), 168 Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins) { 169 DigestAnalyzerOptions(); 170 if (Opts->PrintStats) { 171 llvm::EnableStatistics(); 172 TUTotalTimer = new llvm::Timer("Analyzer Total Time"); 173 } 174 } 175 176 ~AnalysisConsumer() { 177 if (Opts->PrintStats) 178 delete TUTotalTimer; 179 } 180 181 void DigestAnalyzerOptions() { 182 // Create the PathDiagnosticConsumer. 183 PathConsumers.push_back(new ClangDiagPathDiagConsumer(PP.getDiagnostics())); 184 185 if (!OutDir.empty()) { 186 switch (Opts->AnalysisDiagOpt) { 187 default: 188#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \ 189 case PD_##NAME: CREATEFN(PathConsumers, OutDir, PP); break; 190#include "clang/StaticAnalyzer/Core/Analyses.def" 191 } 192 } else if (Opts->AnalysisDiagOpt == PD_TEXT) { 193 // Create the text client even without a specified output file since 194 // it just uses diagnostic notes. 195 createTextPathDiagnosticConsumer(PathConsumers, "", PP); 196 } 197 198 // Create the analyzer component creators. 199 switch (Opts->AnalysisStoreOpt) { 200 default: 201 llvm_unreachable("Unknown store manager."); 202#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 203 case NAME##Model: CreateStoreMgr = CREATEFN; break; 204#include "clang/StaticAnalyzer/Core/Analyses.def" 205 } 206 207 switch (Opts->AnalysisConstraintsOpt) { 208 default: 209 llvm_unreachable("Unknown store manager."); 210#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 211 case NAME##Model: CreateConstraintMgr = CREATEFN; break; 212#include "clang/StaticAnalyzer/Core/Analyses.def" 213 } 214 } 215 216 void DisplayFunction(const Decl *D, AnalysisMode Mode) { 217 if (!Opts->AnalyzerDisplayProgress) 218 return; 219 220 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 221 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 222 if (Loc.isValid()) { 223 llvm::errs() << "ANALYZE"; 224 225 if (Mode == AM_Syntax) 226 llvm::errs() << " (Syntax)"; 227 else if (Mode == AM_Path) 228 llvm::errs() << " (Path)"; 229 else 230 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!"); 231 232 llvm::errs() << ": " << Loc.getFilename(); 233 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { 234 const NamedDecl *ND = cast<NamedDecl>(D); 235 llvm::errs() << ' ' << *ND << '\n'; 236 } 237 else if (isa<BlockDecl>(D)) { 238 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:" 239 << Loc.getColumn() << '\n'; 240 } 241 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 242 Selector S = MD->getSelector(); 243 llvm::errs() << ' ' << S.getAsString(); 244 } 245 } 246 } 247 248 virtual void Initialize(ASTContext &Context) { 249 Ctx = &Context; 250 checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins, 251 PP.getDiagnostics())); 252 Mgr.reset(new AnalysisManager(*Ctx, 253 PP.getDiagnostics(), 254 PP.getLangOpts(), 255 PathConsumers, 256 CreateStoreMgr, 257 CreateConstraintMgr, 258 checkerMgr.get(), 259 *Opts)); 260 } 261 262 /// \brief Store the top level decls in the set to be processed later on. 263 /// (Doing this pre-processing avoids deserialization of data from PCH.) 264 virtual bool HandleTopLevelDecl(DeclGroupRef D); 265 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D); 266 267 virtual void HandleTranslationUnit(ASTContext &C); 268 269 /// \brief Build the call graph for all the top level decls of this TU and 270 /// use it to define the order in which the functions should be visited. 271 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 272 273 /// \brief Run analyzes(syntax or path sensitive) on the given function. 274 /// \param Mode - determines if we are requesting syntax only or path 275 /// sensitive only analysis. 276 /// \param VisitedCallees - The output parameter, which is populated with the 277 /// set of functions which should be considered analyzed after analyzing the 278 /// given root function. 279 void HandleCode(Decl *D, AnalysisMode Mode, 280 SetOfConstDecls *VisitedCallees = 0); 281 282 void RunPathSensitiveChecks(Decl *D, SetOfConstDecls *VisitedCallees); 283 void ActionExprEngine(Decl *D, bool ObjCGCEnabled, 284 SetOfConstDecls *VisitedCallees); 285 286 /// Visitors for the RecursiveASTVisitor. 287 bool shouldWalkTypesOfTypeLocs() const { return false; } 288 289 /// Handle callbacks for arbitrary Decls. 290 bool VisitDecl(Decl *D) { 291 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode); 292 if (Mode & AM_Syntax) 293 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 294 return true; 295 } 296 297 bool VisitFunctionDecl(FunctionDecl *FD) { 298 IdentifierInfo *II = FD->getIdentifier(); 299 if (II && II->getName().startswith("__inline")) 300 return true; 301 302 // We skip function template definitions, as their semantics is 303 // only determined when they are instantiated. 304 if (FD->isThisDeclarationADefinition() && 305 !FD->isDependentContext()) { 306 HandleCode(FD, RecVisitorMode); 307 } 308 return true; 309 } 310 311 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 312 if (MD->isThisDeclarationADefinition()) 313 HandleCode(MD, RecVisitorMode); 314 return true; 315 } 316 317private: 318 void storeTopLevelDecls(DeclGroupRef DG); 319 320 /// \brief Check if we should skip (not analyze) the given function. 321 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode); 322 323}; 324} // end anonymous namespace 325 326 327//===----------------------------------------------------------------------===// 328// AnalysisConsumer implementation. 329//===----------------------------------------------------------------------===// 330llvm::Timer* AnalysisConsumer::TUTotalTimer = 0; 331 332bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 333 storeTopLevelDecls(DG); 334 return true; 335} 336 337void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 338 storeTopLevelDecls(DG); 339} 340 341void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 342 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 343 344 // Skip ObjCMethodDecl, wait for the objc container to avoid 345 // analyzing twice. 346 if (isa<ObjCMethodDecl>(*I)) 347 continue; 348 349 LocalTUDecls.push_back(*I); 350 } 351} 352 353static bool shouldSkipFunction(CallGraphNode *N, 354 SmallPtrSet<CallGraphNode*,24> Visited) { 355 // We want to re-analyse the functions as top level in several cases: 356 // - The 'init' methods should be reanalyzed because 357 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 358 // 'nil' and unless we analyze the 'init' functions as top level, we will not 359 // catch errors within defensive code. 360 // - We want to reanalyze all ObjC methods as top level to report Retain 361 // Count naming convention errors more aggressively. 362 if (isa<ObjCMethodDecl>(N->getDecl())) 363 return false; 364 365 // Otherwise, if we visited the function before, do not reanalyze it. 366 return Visited.count(N); 367} 368 369void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 370 // Otherwise, use the Callgraph to derive the order. 371 // Build the Call Graph. 372 CallGraph CG; 373 374 // Add all the top level declarations to the graph. 375 // Note: CallGraph can trigger deserialization of more items from a pch 376 // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 377 // We rely on random access to add the initially processed Decls to CG. 378 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 379 CG.addToCallGraph(LocalTUDecls[i]); 380 } 381 382 // Find the top level nodes - children of root + the unreachable (parentless) 383 // nodes. 384 llvm::SmallVector<CallGraphNode*, 24> TopLevelFunctions; 385 for (CallGraph::nodes_iterator TI = CG.parentless_begin(), 386 TE = CG.parentless_end(); TI != TE; ++TI) { 387 TopLevelFunctions.push_back(*TI); 388 NumFunctionTopLevel++; 389 } 390 CallGraphNode *Entry = CG.getRoot(); 391 for (CallGraphNode::iterator I = Entry->begin(), 392 E = Entry->end(); I != E; ++I) { 393 TopLevelFunctions.push_back(*I); 394 NumFunctionTopLevel++; 395 } 396 397 // Make sure the nodes are sorted in order reverse of their definition in the 398 // translation unit. This step is very important for performance. It ensures 399 // that we analyze the root functions before the externally available 400 // subroutines. 401 std::deque<CallGraphNode*> BFSQueue; 402 for (llvm::SmallVector<CallGraphNode*, 24>::reverse_iterator 403 TI = TopLevelFunctions.rbegin(), TE = TopLevelFunctions.rend(); 404 TI != TE; ++TI) 405 BFSQueue.push_back(*TI); 406 407 // BFS over all of the functions, while skipping the ones inlined into 408 // the previously processed functions. Use external Visited set, which is 409 // also modified when we inline a function. 410 SmallPtrSet<CallGraphNode*,24> Visited; 411 while(!BFSQueue.empty()) { 412 CallGraphNode *N = BFSQueue.front(); 413 BFSQueue.pop_front(); 414 415 // Push the children into the queue. 416 for (CallGraphNode::const_iterator CI = N->begin(), 417 CE = N->end(); CI != CE; ++CI) { 418 if (!shouldSkipFunction(*CI, Visited)) 419 BFSQueue.push_back(*CI); 420 } 421 422 // Skip the functions which have been processed already or previously 423 // inlined. 424 if (shouldSkipFunction(N, Visited)) 425 continue; 426 427 // Analyze the function. 428 SetOfConstDecls VisitedCallees; 429 Decl *D = N->getDecl(); 430 assert(D); 431 HandleCode(D, AM_Path, 432 (Mgr->options.InliningMode == All ? 0 : &VisitedCallees)); 433 434 // Add the visited callees to the global visited set. 435 for (SetOfConstDecls::iterator I = VisitedCallees.begin(), 436 E = VisitedCallees.end(); I != E; ++I) { 437 CallGraphNode *VN = CG.getNode(*I); 438 if (VN) 439 Visited.insert(VN); 440 } 441 Visited.insert(N); 442 } 443} 444 445void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 446 // Don't run the actions if an error has occurred with parsing the file. 447 DiagnosticsEngine &Diags = PP.getDiagnostics(); 448 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 449 return; 450 451 { 452 if (TUTotalTimer) TUTotalTimer->startTimer(); 453 454 // Introduce a scope to destroy BR before Mgr. 455 BugReporter BR(*Mgr); 456 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 457 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 458 459 // Run the AST-only checks using the order in which functions are defined. 460 // If inlining is not turned on, use the simplest function order for path 461 // sensitive analyzes as well. 462 RecVisitorMode = AM_Syntax; 463 if (!Mgr->shouldInlineCall()) 464 RecVisitorMode |= AM_Path; 465 RecVisitorBR = &BR; 466 467 // Process all the top level declarations. 468 // 469 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 470 // entries. Thus we don't use an iterator, but rely on LocalTUDecls 471 // random access. By doing so, we automatically compensate for iterators 472 // possibly being invalidated, although this is a bit slower. 473 const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 474 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 475 TraverseDecl(LocalTUDecls[i]); 476 } 477 478 if (Mgr->shouldInlineCall()) 479 HandleDeclsCallGraph(LocalTUDeclsSize); 480 481 // After all decls handled, run checkers on the entire TranslationUnit. 482 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 483 484 RecVisitorBR = 0; 485 } 486 487 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 488 // FIXME: This should be replaced with something that doesn't rely on 489 // side-effects in PathDiagnosticConsumer's destructor. This is required when 490 // used with option -disable-free. 491 Mgr.reset(NULL); 492 493 if (TUTotalTimer) TUTotalTimer->stopTimer(); 494 495 // Count how many basic blocks we have not covered. 496 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 497 if (NumBlocksInAnalyzedFunctions > 0) 498 PercentReachableBlocks = 499 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 500 NumBlocksInAnalyzedFunctions; 501 502} 503 504static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) { 505 if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) 506 WL.push_back(BD); 507 508 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 509 I!=E; ++I) 510 if (DeclContext *DC = dyn_cast<DeclContext>(*I)) 511 FindBlocks(DC, WL); 512} 513 514static std::string getFunctionName(const Decl *D) { 515 if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { 516 return ID->getSelector().getAsString(); 517 } 518 if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) { 519 IdentifierInfo *II = ND->getIdentifier(); 520 if (II) 521 return II->getName(); 522 } 523 return ""; 524} 525 526AnalysisConsumer::AnalysisMode 527AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) { 528 if (!Opts->AnalyzeSpecificFunction.empty() && 529 getFunctionName(D) != Opts->AnalyzeSpecificFunction) 530 return AM_None; 531 532 // Unless -analyze-all is specified, treat decls differently depending on 533 // where they came from: 534 // - Main source file: run both path-sensitive and non-path-sensitive checks. 535 // - Header files: run non-path-sensitive checks only. 536 // - System headers: don't run any checks. 537 SourceManager &SM = Ctx->getSourceManager(); 538 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 539 if (!Opts->AnalyzeAll && !SM.isFromMainFile(SL)) { 540 if (SL.isInvalid() || SM.isInSystemHeader(SL)) 541 return AM_None; 542 return Mode & ~AM_Path; 543 } 544 545 return Mode; 546} 547 548void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 549 SetOfConstDecls *VisitedCallees) { 550 Mode = getModeForDecl(D, Mode); 551 if (Mode == AM_None) 552 return; 553 554 DisplayFunction(D, Mode); 555 CFG *DeclCFG = Mgr->getCFG(D); 556 if (DeclCFG) { 557 unsigned CFGSize = DeclCFG->size(); 558 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize; 559 } 560 561 562 // Clear the AnalysisManager of old AnalysisDeclContexts. 563 Mgr->ClearContexts(); 564 565 // Dispatch on the actions. 566 SmallVector<Decl*, 10> WL; 567 WL.push_back(D); 568 569 if (D->hasBody() && Opts->AnalyzeNestedBlocks) 570 FindBlocks(cast<DeclContext>(D), WL); 571 572 BugReporter BR(*Mgr); 573 for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 574 WI != WE; ++WI) 575 if ((*WI)->hasBody()) { 576 if (Mode & AM_Syntax) 577 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR); 578 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) { 579 RunPathSensitiveChecks(*WI, VisitedCallees); 580 NumFunctionsAnalyzed++; 581 } 582 } 583} 584 585//===----------------------------------------------------------------------===// 586// Path-sensitive checking. 587//===----------------------------------------------------------------------===// 588 589void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled, 590 SetOfConstDecls *VisitedCallees) { 591 // Construct the analysis engine. First check if the CFG is valid. 592 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 593 if (!Mgr->getCFG(D)) 594 return; 595 596 // See if the LiveVariables analysis scales. 597 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 598 return; 599 600 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries); 601 602 // Set the graph auditor. 603 OwningPtr<ExplodedNode::Auditor> Auditor; 604 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) { 605 Auditor.reset(CreateUbiViz()); 606 ExplodedNode::SetAuditor(Auditor.get()); 607 } 608 609 // Execute the worklist algorithm. 610 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 611 Mgr->options.MaxNodes); 612 613 // Release the auditor (if any) so that it doesn't monitor the graph 614 // created BugReporter. 615 ExplodedNode::SetAuditor(0); 616 617 // Visualize the exploded graph. 618 if (Mgr->options.visualizeExplodedGraphWithGraphViz) 619 Eng.ViewGraph(Mgr->options.TrimGraph); 620 621 // Display warnings. 622 Eng.getBugReporter().FlushReports(); 623} 624 625void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 626 SetOfConstDecls *Visited) { 627 628 switch (Mgr->getLangOpts().getGC()) { 629 case LangOptions::NonGC: 630 ActionExprEngine(D, false, Visited); 631 break; 632 633 case LangOptions::GCOnly: 634 ActionExprEngine(D, true, Visited); 635 break; 636 637 case LangOptions::HybridGC: 638 ActionExprEngine(D, false, Visited); 639 ActionExprEngine(D, true, Visited); 640 break; 641 } 642} 643 644//===----------------------------------------------------------------------===// 645// AnalysisConsumer creation. 646//===----------------------------------------------------------------------===// 647 648ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 649 const std::string& outDir, 650 AnalyzerOptionsRef opts, 651 ArrayRef<std::string> plugins) { 652 // Disable the effects of '-Werror' when using the AnalysisConsumer. 653 pp.getDiagnostics().setWarningsAsErrors(false); 654 655 return new AnalysisConsumer(pp, outDir, opts, plugins); 656} 657 658//===----------------------------------------------------------------------===// 659// Ubigraph Visualization. FIXME: Move to separate file. 660//===----------------------------------------------------------------------===// 661 662namespace { 663 664class UbigraphViz : public ExplodedNode::Auditor { 665 OwningPtr<raw_ostream> Out; 666 llvm::sys::Path Dir, Filename; 667 unsigned Cntr; 668 669 typedef llvm::DenseMap<void*,unsigned> VMap; 670 VMap M; 671 672public: 673 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 674 llvm::sys::Path& filename); 675 676 ~UbigraphViz(); 677 678 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 679}; 680 681} // end anonymous namespace 682 683static ExplodedNode::Auditor* CreateUbiViz() { 684 std::string ErrMsg; 685 686 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 687 if (!ErrMsg.empty()) 688 return 0; 689 690 llvm::sys::Path Filename = Dir; 691 Filename.appendComponent("llvm_ubi"); 692 Filename.makeUnique(true,&ErrMsg); 693 694 if (!ErrMsg.empty()) 695 return 0; 696 697 llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 698 699 OwningPtr<llvm::raw_fd_ostream> Stream; 700 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 701 702 if (!ErrMsg.empty()) 703 return 0; 704 705 return new UbigraphViz(Stream.take(), Dir, Filename); 706} 707 708void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 709 710 assert (Src != Dst && "Self-edges are not allowed."); 711 712 // Lookup the Src. If it is a new node, it's a root. 713 VMap::iterator SrcI= M.find(Src); 714 unsigned SrcID; 715 716 if (SrcI == M.end()) { 717 M[Src] = SrcID = Cntr++; 718 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 719 } 720 else 721 SrcID = SrcI->second; 722 723 // Lookup the Dst. 724 VMap::iterator DstI= M.find(Dst); 725 unsigned DstID; 726 727 if (DstI == M.end()) { 728 M[Dst] = DstID = Cntr++; 729 *Out << "('vertex', " << DstID << ")\n"; 730 } 731 else { 732 // We have hit DstID before. Change its style to reflect a cache hit. 733 DstID = DstI->second; 734 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 735 } 736 737 // Add the edge. 738 *Out << "('edge', " << SrcID << ", " << DstID 739 << ", ('arrow','true'), ('oriented', 'true'))\n"; 740} 741 742UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 743 llvm::sys::Path& filename) 744 : Out(out), Dir(dir), Filename(filename), Cntr(0) { 745 746 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 747 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 748 " ('size', '1.5'))\n"; 749} 750 751UbigraphViz::~UbigraphViz() { 752 Out.reset(0); 753 llvm::errs() << "Running 'ubiviz' program... "; 754 std::string ErrMsg; 755 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 756 std::vector<const char*> args; 757 args.push_back(Ubiviz.c_str()); 758 args.push_back(Filename.c_str()); 759 args.push_back(0); 760 761 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 762 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 763 } 764 765 // Delete the directory. 766 Dir.eraseFromDisk(true); 767} 768