AnalysisConsumer.cpp 28 KB

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