AnalysisConsumer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // "Meta" ASTConsumer for running different source analyses.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
  13. #include "ModelInjector.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/RecursiveASTVisitor.h"
  18. #include "clang/Analysis/Analyses/LiveVariables.h"
  19. #include "clang/Analysis/CFG.h"
  20. #include "clang/Analysis/CallGraph.h"
  21. #include "clang/Analysis/CodeInjector.h"
  22. #include "clang/Analysis/MacroExpansionContext.h"
  23. #include "clang/Analysis/PathDiagnostic.h"
  24. #include "clang/Basic/SourceManager.h"
  25. #include "clang/CrossTU/CrossTranslationUnit.h"
  26. #include "clang/Frontend/CompilerInstance.h"
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Rewrite/Core/Rewriter.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/CheckerManager.h"
  33. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  34. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  35. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  36. #include "llvm/ADT/PostOrderIterator.h"
  37. #include "llvm/ADT/ScopeExit.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. #include <utility>
  47. using namespace clang;
  48. using namespace ento;
  49. #define DEBUG_TYPE "AnalysisConsumer"
  50. STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
  51. STATISTIC(NumFunctionsAnalyzed,
  52. "The # of functions and blocks analyzed (as top level "
  53. "with inlining turned on).");
  54. STATISTIC(NumBlocksInAnalyzedFunctions,
  55. "The # of basic blocks in the analyzed functions.");
  56. STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
  57. "The # of visited basic blocks in the analyzed functions.");
  58. STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
  59. STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
  60. //===----------------------------------------------------------------------===//
  61. // AnalysisConsumer declaration.
  62. //===----------------------------------------------------------------------===//
  63. namespace {
  64. class AnalysisConsumer : public AnalysisASTConsumer,
  65. public RecursiveASTVisitor<AnalysisConsumer> {
  66. enum {
  67. AM_None = 0,
  68. AM_Syntax = 0x1,
  69. AM_Path = 0x2
  70. };
  71. typedef unsigned AnalysisMode;
  72. /// Mode of the analyzes while recursively visiting Decls.
  73. AnalysisMode RecVisitorMode;
  74. /// Bug Reporter to use while recursively visiting Decls.
  75. BugReporter *RecVisitorBR;
  76. std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
  77. public:
  78. ASTContext *Ctx;
  79. Preprocessor &PP;
  80. const std::string OutDir;
  81. AnalyzerOptionsRef Opts;
  82. ArrayRef<std::string> Plugins;
  83. CodeInjector *Injector;
  84. cross_tu::CrossTranslationUnitContext CTU;
  85. /// Stores the declarations from the local translation unit.
  86. /// Note, we pre-compute the local declarations at parse time as an
  87. /// optimization to make sure we do not deserialize everything from disk.
  88. /// The local declaration to all declarations ratio might be very small when
  89. /// working with a PCH file.
  90. SetOfDecls LocalTUDecls;
  91. MacroExpansionContext MacroExpansions;
  92. // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
  93. PathDiagnosticConsumers PathConsumers;
  94. StoreManagerCreator CreateStoreMgr;
  95. ConstraintManagerCreator CreateConstraintMgr;
  96. std::unique_ptr<CheckerManager> checkerMgr;
  97. std::unique_ptr<AnalysisManager> Mgr;
  98. /// Time the analyzes time of each translation unit.
  99. std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
  100. std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
  101. std::unique_ptr<llvm::Timer> ExprEngineTimer;
  102. std::unique_ptr<llvm::Timer> BugReporterTimer;
  103. /// The information about analyzed functions shared throughout the
  104. /// translation unit.
  105. FunctionSummariesTy FunctionSummaries;
  106. AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
  107. AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
  108. CodeInjector *injector)
  109. : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
  110. PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
  111. Plugins(plugins), Injector(injector), CTU(CI),
  112. MacroExpansions(CI.getLangOpts()) {
  113. DigestAnalyzerOptions();
  114. if (Opts->AnalyzerDisplayProgress || Opts->PrintStats ||
  115. Opts->ShouldSerializeStats) {
  116. AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
  117. "analyzer", "Analyzer timers");
  118. SyntaxCheckTimer = std::make_unique<llvm::Timer>(
  119. "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);
  120. ExprEngineTimer = std::make_unique<llvm::Timer>(
  121. "exprengine", "Path exploration time", *AnalyzerTimers);
  122. BugReporterTimer = std::make_unique<llvm::Timer>(
  123. "bugreporter", "Path-sensitive report post-processing time",
  124. *AnalyzerTimers);
  125. }
  126. if (Opts->PrintStats || Opts->ShouldSerializeStats) {
  127. llvm::EnableStatistics(/* DoPrintOnExit= */ false);
  128. }
  129. if (Opts->ShouldDisplayMacroExpansions)
  130. MacroExpansions.registerForPreprocessor(PP);
  131. }
  132. ~AnalysisConsumer() override {
  133. if (Opts->PrintStats) {
  134. llvm::PrintStatistics();
  135. }
  136. }
  137. void DigestAnalyzerOptions() {
  138. switch (Opts->AnalysisDiagOpt) {
  139. case PD_NONE:
  140. break;
  141. #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
  142. case PD_##NAME: \
  143. CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
  144. MacroExpansions); \
  145. break;
  146. #include "clang/StaticAnalyzer/Core/Analyses.def"
  147. default:
  148. llvm_unreachable("Unknown analyzer output type!");
  149. }
  150. // Create the analyzer component creators.
  151. switch (Opts->AnalysisStoreOpt) {
  152. default:
  153. llvm_unreachable("Unknown store manager.");
  154. #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
  155. case NAME##Model: CreateStoreMgr = CREATEFN; break;
  156. #include "clang/StaticAnalyzer/Core/Analyses.def"
  157. }
  158. switch (Opts->AnalysisConstraintsOpt) {
  159. default:
  160. llvm_unreachable("Unknown constraint manager.");
  161. #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
  162. case NAME##Model: CreateConstraintMgr = CREATEFN; break;
  163. #include "clang/StaticAnalyzer/Core/Analyses.def"
  164. }
  165. }
  166. void DisplayTime(llvm::TimeRecord &Time) {
  167. if (!Opts->AnalyzerDisplayProgress) {
  168. return;
  169. }
  170. llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000)
  171. << " ms\n";
  172. }
  173. void DisplayFunction(const Decl *D, AnalysisMode Mode,
  174. ExprEngine::InliningModes IMode) {
  175. if (!Opts->AnalyzerDisplayProgress)
  176. return;
  177. SourceManager &SM = Mgr->getASTContext().getSourceManager();
  178. PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
  179. if (Loc.isValid()) {
  180. llvm::errs() << "ANALYZE";
  181. if (Mode == AM_Syntax)
  182. llvm::errs() << " (Syntax)";
  183. else if (Mode == AM_Path) {
  184. llvm::errs() << " (Path, ";
  185. switch (IMode) {
  186. case ExprEngine::Inline_Minimal:
  187. llvm::errs() << " Inline_Minimal";
  188. break;
  189. case ExprEngine::Inline_Regular:
  190. llvm::errs() << " Inline_Regular";
  191. break;
  192. }
  193. llvm::errs() << ")";
  194. } else
  195. assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
  196. llvm::errs() << ": " << Loc.getFilename() << ' '
  197. << AnalysisDeclContext::getFunctionName(D);
  198. }
  199. }
  200. void Initialize(ASTContext &Context) override {
  201. Ctx = &Context;
  202. checkerMgr = std::make_unique<CheckerManager>(*Ctx, *Opts, PP, Plugins,
  203. CheckerRegistrationFns);
  204. Mgr = std::make_unique<AnalysisManager>(*Ctx, PP, PathConsumers,
  205. CreateStoreMgr, CreateConstraintMgr,
  206. checkerMgr.get(), *Opts, Injector);
  207. }
  208. /// Store the top level decls in the set to be processed later on.
  209. /// (Doing this pre-processing avoids deserialization of data from PCH.)
  210. bool HandleTopLevelDecl(DeclGroupRef D) override;
  211. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
  212. void HandleTranslationUnit(ASTContext &C) override;
  213. /// Determine which inlining mode should be used when this function is
  214. /// analyzed. This allows to redefine the default inlining policies when
  215. /// analyzing a given function.
  216. ExprEngine::InliningModes
  217. getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
  218. /// Build the call graph for all the top level decls of this TU and
  219. /// use it to define the order in which the functions should be visited.
  220. void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
  221. /// Run analyzes(syntax or path sensitive) on the given function.
  222. /// \param Mode - determines if we are requesting syntax only or path
  223. /// sensitive only analysis.
  224. /// \param VisitedCallees - The output parameter, which is populated with the
  225. /// set of functions which should be considered analyzed after analyzing the
  226. /// given root function.
  227. void HandleCode(Decl *D, AnalysisMode Mode,
  228. ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
  229. SetOfConstDecls *VisitedCallees = nullptr);
  230. void RunPathSensitiveChecks(Decl *D,
  231. ExprEngine::InliningModes IMode,
  232. SetOfConstDecls *VisitedCallees);
  233. /// Visitors for the RecursiveASTVisitor.
  234. bool shouldWalkTypesOfTypeLocs() const { return false; }
  235. /// Handle callbacks for arbitrary Decls.
  236. bool VisitDecl(Decl *D) {
  237. AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
  238. if (Mode & AM_Syntax) {
  239. if (SyntaxCheckTimer)
  240. SyntaxCheckTimer->startTimer();
  241. checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
  242. if (SyntaxCheckTimer)
  243. SyntaxCheckTimer->stopTimer();
  244. }
  245. return true;
  246. }
  247. bool VisitVarDecl(VarDecl *VD) {
  248. if (!Opts->IsNaiveCTUEnabled)
  249. return true;
  250. if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
  251. if (!cross_tu::containsConst(VD, *Ctx))
  252. return true;
  253. } else {
  254. // Cannot be initialized in another TU.
  255. return true;
  256. }
  257. if (VD->getAnyInitializer())
  258. return true;
  259. llvm::Expected<const VarDecl *> CTUDeclOrError =
  260. CTU.getCrossTUDefinition(VD, Opts->CTUDir, Opts->CTUIndexName,
  261. Opts->DisplayCTUProgress);
  262. if (!CTUDeclOrError) {
  263. handleAllErrors(CTUDeclOrError.takeError(),
  264. [&](const cross_tu::IndexError &IE) {
  265. CTU.emitCrossTUDiagnostics(IE);
  266. });
  267. }
  268. return true;
  269. }
  270. bool VisitFunctionDecl(FunctionDecl *FD) {
  271. IdentifierInfo *II = FD->getIdentifier();
  272. if (II && II->getName().startswith("__inline"))
  273. return true;
  274. // We skip function template definitions, as their semantics is
  275. // only determined when they are instantiated.
  276. if (FD->isThisDeclarationADefinition() &&
  277. !FD->isDependentContext()) {
  278. assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
  279. HandleCode(FD, RecVisitorMode);
  280. }
  281. return true;
  282. }
  283. bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
  284. if (MD->isThisDeclarationADefinition()) {
  285. assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
  286. HandleCode(MD, RecVisitorMode);
  287. }
  288. return true;
  289. }
  290. bool VisitBlockDecl(BlockDecl *BD) {
  291. if (BD->hasBody()) {
  292. assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
  293. // Since we skip function template definitions, we should skip blocks
  294. // declared in those functions as well.
  295. if (!BD->isDependentContext()) {
  296. HandleCode(BD, RecVisitorMode);
  297. }
  298. }
  299. return true;
  300. }
  301. void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
  302. PathConsumers.push_back(Consumer);
  303. }
  304. void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
  305. CheckerRegistrationFns.push_back(std::move(Fn));
  306. }
  307. private:
  308. void storeTopLevelDecls(DeclGroupRef DG);
  309. std::string getFunctionName(const Decl *D);
  310. /// Check if we should skip (not analyze) the given function.
  311. AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
  312. void runAnalysisOnTranslationUnit(ASTContext &C);
  313. /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
  314. void reportAnalyzerProgress(StringRef S);
  315. }; // namespace
  316. } // end anonymous namespace
  317. //===----------------------------------------------------------------------===//
  318. // AnalysisConsumer implementation.
  319. //===----------------------------------------------------------------------===//
  320. bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
  321. storeTopLevelDecls(DG);
  322. return true;
  323. }
  324. void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
  325. storeTopLevelDecls(DG);
  326. }
  327. void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
  328. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
  329. // Skip ObjCMethodDecl, wait for the objc container to avoid
  330. // analyzing twice.
  331. if (isa<ObjCMethodDecl>(*I))
  332. continue;
  333. LocalTUDecls.push_back(*I);
  334. }
  335. }
  336. static bool shouldSkipFunction(const Decl *D,
  337. const SetOfConstDecls &Visited,
  338. const SetOfConstDecls &VisitedAsTopLevel) {
  339. if (VisitedAsTopLevel.count(D))
  340. return true;
  341. // Skip analysis of inheriting constructors as top-level functions. These
  342. // constructors don't even have a body written down in the code, so even if
  343. // we find a bug, we won't be able to display it.
  344. if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  345. if (CD->isInheritingConstructor())
  346. return true;
  347. // We want to re-analyse the functions as top level in the following cases:
  348. // - The 'init' methods should be reanalyzed because
  349. // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
  350. // 'nil' and unless we analyze the 'init' functions as top level, we will
  351. // not catch errors within defensive code.
  352. // - We want to reanalyze all ObjC methods as top level to report Retain
  353. // Count naming convention errors more aggressively.
  354. if (isa<ObjCMethodDecl>(D))
  355. return false;
  356. // We also want to reanalyze all C++ copy and move assignment operators to
  357. // separately check the two cases where 'this' aliases with the parameter and
  358. // where it may not. (cplusplus.SelfAssignmentChecker)
  359. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  360. if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
  361. return false;
  362. }
  363. // Otherwise, if we visited the function before, do not reanalyze it.
  364. return Visited.count(D);
  365. }
  366. ExprEngine::InliningModes
  367. AnalysisConsumer::getInliningModeForFunction(const Decl *D,
  368. const SetOfConstDecls &Visited) {
  369. // We want to reanalyze all ObjC methods as top level to report Retain
  370. // Count naming convention errors more aggressively. But we should tune down
  371. // inlining when reanalyzing an already inlined function.
  372. if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
  373. const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
  374. if (ObjCM->getMethodFamily() != OMF_init)
  375. return ExprEngine::Inline_Minimal;
  376. }
  377. return ExprEngine::Inline_Regular;
  378. }
  379. void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
  380. // Build the Call Graph by adding all the top level declarations to the graph.
  381. // Note: CallGraph can trigger deserialization of more items from a pch
  382. // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
  383. // We rely on random access to add the initially processed Decls to CG.
  384. CallGraph CG;
  385. for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
  386. CG.addToCallGraph(LocalTUDecls[i]);
  387. }
  388. // Walk over all of the call graph nodes in topological order, so that we
  389. // analyze parents before the children. Skip the functions inlined into
  390. // the previously processed functions. Use external Visited set to identify
  391. // inlined functions. The topological order allows the "do not reanalyze
  392. // previously inlined function" performance heuristic to be triggered more
  393. // often.
  394. SetOfConstDecls Visited;
  395. SetOfConstDecls VisitedAsTopLevel;
  396. llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
  397. for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
  398. I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
  399. NumFunctionTopLevel++;
  400. CallGraphNode *N = *I;
  401. Decl *D = N->getDecl();
  402. // Skip the abstract root node.
  403. if (!D)
  404. continue;
  405. // Skip the functions which have been processed already or previously
  406. // inlined.
  407. if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
  408. continue;
  409. // Analyze the function.
  410. SetOfConstDecls VisitedCallees;
  411. HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
  412. (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
  413. // Add the visited callees to the global visited set.
  414. for (const Decl *Callee : VisitedCallees)
  415. // Decls from CallGraph are already canonical. But Decls coming from
  416. // CallExprs may be not. We should canonicalize them manually.
  417. Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
  418. : Callee->getCanonicalDecl());
  419. VisitedAsTopLevel.insert(D);
  420. }
  421. }
  422. static bool fileContainsString(StringRef Substring, ASTContext &C) {
  423. const SourceManager &SM = C.getSourceManager();
  424. FileID FID = SM.getMainFileID();
  425. StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
  426. return Buffer.contains(Substring);
  427. }
  428. void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
  429. BugReporter BR(*Mgr);
  430. TranslationUnitDecl *TU = C.getTranslationUnitDecl();
  431. if (SyntaxCheckTimer)
  432. SyntaxCheckTimer->startTimer();
  433. checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
  434. if (SyntaxCheckTimer)
  435. SyntaxCheckTimer->stopTimer();
  436. // Run the AST-only checks using the order in which functions are defined.
  437. // If inlining is not turned on, use the simplest function order for path
  438. // sensitive analyzes as well.
  439. RecVisitorMode = AM_Syntax;
  440. if (!Mgr->shouldInlineCall())
  441. RecVisitorMode |= AM_Path;
  442. RecVisitorBR = &BR;
  443. // Process all the top level declarations.
  444. //
  445. // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
  446. // entries. Thus we don't use an iterator, but rely on LocalTUDecls
  447. // random access. By doing so, we automatically compensate for iterators
  448. // possibly being invalidated, although this is a bit slower.
  449. const unsigned LocalTUDeclsSize = LocalTUDecls.size();
  450. for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
  451. TraverseDecl(LocalTUDecls[i]);
  452. }
  453. if (Mgr->shouldInlineCall())
  454. HandleDeclsCallGraph(LocalTUDeclsSize);
  455. // After all decls handled, run checkers on the entire TranslationUnit.
  456. checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
  457. BR.FlushReports();
  458. RecVisitorBR = nullptr;
  459. }
  460. void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
  461. if (Opts->AnalyzerDisplayProgress)
  462. llvm::errs() << S;
  463. }
  464. void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
  465. // Don't run the actions if an error has occurred with parsing the file.
  466. DiagnosticsEngine &Diags = PP.getDiagnostics();
  467. if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
  468. return;
  469. // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
  470. // FIXME: This should be replaced with something that doesn't rely on
  471. // side-effects in PathDiagnosticConsumer's destructor. This is required when
  472. // used with option -disable-free.
  473. const auto DiagFlusherScopeExit =
  474. llvm::make_scope_exit([this] { Mgr.reset(); });
  475. if (Opts->ShouldIgnoreBisonGeneratedFiles &&
  476. fileContainsString("/* A Bison parser, made by", C)) {
  477. reportAnalyzerProgress("Skipping bison-generated file\n");
  478. return;
  479. }
  480. if (Opts->ShouldIgnoreFlexGeneratedFiles &&
  481. fileContainsString("/* A lexical scanner generated by flex", C)) {
  482. reportAnalyzerProgress("Skipping flex-generated file\n");
  483. return;
  484. }
  485. // Don't analyze if the user explicitly asked for no checks to be performed
  486. // on this file.
  487. if (Opts->DisableAllCheckers) {
  488. reportAnalyzerProgress("All checks are disabled using a supplied option\n");
  489. return;
  490. }
  491. // Otherwise, just run the analysis.
  492. runAnalysisOnTranslationUnit(C);
  493. // Count how many basic blocks we have not covered.
  494. NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
  495. NumVisitedBlocksInAnalyzedFunctions =
  496. FunctionSummaries.getTotalNumVisitedBasicBlocks();
  497. if (NumBlocksInAnalyzedFunctions > 0)
  498. PercentReachableBlocks =
  499. (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
  500. NumBlocksInAnalyzedFunctions;
  501. }
  502. AnalysisConsumer::AnalysisMode
  503. AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
  504. if (!Opts->AnalyzeSpecificFunction.empty() &&
  505. AnalysisDeclContext::getFunctionName(D) != Opts->AnalyzeSpecificFunction)
  506. return AM_None;
  507. // Unless -analyze-all is specified, treat decls differently depending on
  508. // where they came from:
  509. // - Main source file: run both path-sensitive and non-path-sensitive checks.
  510. // - Header files: run non-path-sensitive checks only.
  511. // - System headers: don't run any checks.
  512. if (Opts->AnalyzeAll)
  513. return Mode;
  514. const SourceManager &SM = Ctx->getSourceManager();
  515. const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation {
  516. const Stmt *Body = D->getBody();
  517. SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
  518. return SM.getExpansionLoc(SL);
  519. }(D);
  520. // Ignore system headers.
  521. if (Loc.isInvalid() || SM.isInSystemHeader(Loc))
  522. return AM_None;
  523. // Disable path sensitive analysis in user-headers.
  524. if (!Mgr->isInCodeFile(Loc))
  525. return Mode & ~AM_Path;
  526. return Mode;
  527. }
  528. void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
  529. ExprEngine::InliningModes IMode,
  530. SetOfConstDecls *VisitedCallees) {
  531. if (!D->hasBody())
  532. return;
  533. Mode = getModeForDecl(D, Mode);
  534. if (Mode == AM_None)
  535. return;
  536. // Clear the AnalysisManager of old AnalysisDeclContexts.
  537. Mgr->ClearContexts();
  538. // Ignore autosynthesized code.
  539. if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
  540. return;
  541. CFG *DeclCFG = Mgr->getCFG(D);
  542. if (DeclCFG)
  543. MaxCFGSize.updateMax(DeclCFG->size());
  544. DisplayFunction(D, Mode, IMode);
  545. BugReporter BR(*Mgr);
  546. if (Mode & AM_Syntax) {
  547. llvm::TimeRecord CheckerStartTime;
  548. if (SyntaxCheckTimer) {
  549. CheckerStartTime = SyntaxCheckTimer->getTotalTime();
  550. SyntaxCheckTimer->startTimer();
  551. }
  552. checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
  553. if (SyntaxCheckTimer) {
  554. SyntaxCheckTimer->stopTimer();
  555. llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
  556. CheckerEndTime -= CheckerStartTime;
  557. DisplayTime(CheckerEndTime);
  558. }
  559. }
  560. BR.FlushReports();
  561. if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
  562. RunPathSensitiveChecks(D, IMode, VisitedCallees);
  563. if (IMode != ExprEngine::Inline_Minimal)
  564. NumFunctionsAnalyzed++;
  565. }
  566. }
  567. //===----------------------------------------------------------------------===//
  568. // Path-sensitive checking.
  569. //===----------------------------------------------------------------------===//
  570. void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
  571. ExprEngine::InliningModes IMode,
  572. SetOfConstDecls *VisitedCallees) {
  573. // Construct the analysis engine. First check if the CFG is valid.
  574. // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
  575. if (!Mgr->getCFG(D))
  576. return;
  577. // See if the LiveVariables analysis scales.
  578. if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
  579. return;
  580. ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
  581. // Execute the worklist algorithm.
  582. llvm::TimeRecord ExprEngineStartTime;
  583. if (ExprEngineTimer) {
  584. ExprEngineStartTime = ExprEngineTimer->getTotalTime();
  585. ExprEngineTimer->startTimer();
  586. }
  587. Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
  588. Mgr->options.MaxNodesPerTopLevelFunction);
  589. if (ExprEngineTimer) {
  590. ExprEngineTimer->stopTimer();
  591. llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
  592. ExprEngineEndTime -= ExprEngineStartTime;
  593. DisplayTime(ExprEngineEndTime);
  594. }
  595. if (!Mgr->options.DumpExplodedGraphTo.empty())
  596. Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
  597. // Visualize the exploded graph.
  598. if (Mgr->options.visualizeExplodedGraphWithGraphViz)
  599. Eng.ViewGraph(Mgr->options.TrimGraph);
  600. // Display warnings.
  601. if (BugReporterTimer)
  602. BugReporterTimer->startTimer();
  603. Eng.getBugReporter().FlushReports();
  604. if (BugReporterTimer)
  605. BugReporterTimer->stopTimer();
  606. }
  607. //===----------------------------------------------------------------------===//
  608. // AnalysisConsumer creation.
  609. //===----------------------------------------------------------------------===//
  610. std::unique_ptr<AnalysisASTConsumer>
  611. ento::CreateAnalysisConsumer(CompilerInstance &CI) {
  612. // Disable the effects of '-Werror' when using the AnalysisConsumer.
  613. CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
  614. AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
  615. bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
  616. return std::make_unique<AnalysisConsumer>(
  617. CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
  618. CI.getFrontendOpts().Plugins,
  619. hasModelPath ? new ModelInjector(CI) : nullptr);
  620. }