blob: 4324ed2d96c8d9c5fa6e6760e5b3fbac394f1c4f [file] [log] [blame]
Ted Kremenekf0413bf2008-07-02 00:03:09 +00001//===--- 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
Alexander Kornienko6de39492014-01-03 17:23:10 +000014#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000015#include "ModelInjector.h"
Ted Kremenekf0413bf2008-07-02 00:03:09 +000016#include "clang/AST/Decl.h"
Zhongxing Xu686b8452009-12-16 05:29:59 +000017#include "clang/AST/DeclCXX.h"
Ted Kremenekf0413bf2008-07-02 00:03:09 +000018#include "clang/AST/DeclObjC.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000019#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/Analyses/LiveVariables.h"
Daniel Dunbarb5f20252009-11-05 02:41:58 +000021#include "clang/Analysis/CFG.h"
Anna Zakseee91102012-03-08 23:16:38 +000022#include "clang/Analysis/CallGraph.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000023#include "clang/Analysis/CodeInjector.h"
Daniel Dunbarb5f20252009-11-05 02:41:58 +000024#include "clang/Basic/SourceManager.h"
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +000025#include "clang/CrossTU/CrossTranslationUnit.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbarb5f20252009-11-05 02:41:58 +000027#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
29#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
30#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
31#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.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 "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000037#include "llvm/ADT/PostOrderIterator.h"
Anna Zaksb0286542012-02-27 21:33:16 +000038#include "llvm/ADT/Statistic.h"
Rafael Espindola4168ee72013-06-26 06:13:06 +000039#include "llvm/Support/FileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/Path.h"
41#include "llvm/Support/Program.h"
42#include "llvm/Support/Timer.h"
43#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000044#include <memory>
Anna Zaksca70ed52012-03-13 19:32:13 +000045#include <queue>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000046#include <utility>
Anna Zaksca70ed52012-03-13 19:32:13 +000047
Ted Kremenekf0413bf2008-07-02 00:03:09 +000048using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000049using namespace ento;
Ted Kremenekf0413bf2008-07-02 00:03:09 +000050
Chandler Carruth10346662014-04-22 03:17:02 +000051#define DEBUG_TYPE "AnalysisConsumer"
52
Anna Zaks394d07e2012-03-09 21:14:01 +000053STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
Anna Zaks5d484782012-12-07 21:51:47 +000054STATISTIC(NumFunctionsAnalyzed,
Anna Zaksad3704c2012-12-17 20:08:54 +000055 "The # of functions and blocks analyzed (as top level "
56 "with inlining turned on).");
Anna Zakscc24e452012-04-03 02:05:47 +000057STATISTIC(NumBlocksInAnalyzedFunctions,
Anna Zaksad3704c2012-12-17 20:08:54 +000058 "The # of basic blocks in the analyzed functions.");
George Karpenkov2a639852018-02-09 23:37:47 +000059STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
60 "The # of visited basic blocks in the analyzed functions.");
Anna Zakscc24e452012-04-03 02:05:47 +000061STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
Anna Zaks40b87fc2012-07-05 20:44:02 +000062STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
Anna Zakseee91102012-03-08 23:16:38 +000063
Ted Kremenekb5351812009-02-17 04:27:41 +000064//===----------------------------------------------------------------------===//
David Blaikie0cc49432011-09-27 01:43:33 +000065// Special PathDiagnosticConsumers.
Ted Kremenek04ade6f2009-07-27 22:13:39 +000066//===----------------------------------------------------------------------===//
67
Jordan Rose367843a2013-08-16 01:06:30 +000068void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
69 PathDiagnosticConsumers &C,
70 const std::string &prefix,
71 const Preprocessor &PP) {
Ted Kremenek3a081a02012-12-19 01:35:35 +000072 createHTMLDiagnosticConsumer(AnalyzerOpts, C,
73 llvm::sys::path::parent_path(prefix), PP);
Artem Dergachev21948342018-05-16 00:11:24 +000074 createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
Ted Kremenek04ade6f2009-07-27 22:13:39 +000075}
76
Jordan Rose367843a2013-08-16 01:06:30 +000077void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
78 PathDiagnosticConsumers &C,
79 const std::string &Prefix,
80 const clang::Preprocessor &PP) {
81 llvm_unreachable("'text' consumer should be enabled on ClangDiags");
82}
83
Ted Kremenek9bf9af92012-08-16 17:45:23 +000084namespace {
85class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
86 DiagnosticsEngine &Diag;
Jordan Rose367843a2013-08-16 01:06:30 +000087 bool IncludePath;
Ted Kremenek9bf9af92012-08-16 17:45:23 +000088public:
Jordan Rose367843a2013-08-16 01:06:30 +000089 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
90 : Diag(Diag), IncludePath(false) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000091 ~ClangDiagPathDiagConsumer() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +000092 StringRef getName() const override { return "ClangDiags"; }
Jordan Rose367843a2013-08-16 01:06:30 +000093
Craig Topperfb6b25b2014-03-15 04:29:04 +000094 bool supportsLogicalOpControlFlow() const override { return true; }
95 bool supportsCrossFileDiagnostics() const override { return true; }
Jordan Rose367843a2013-08-16 01:06:30 +000096
Craig Topperfb6b25b2014-03-15 04:29:04 +000097 PathGenerationScheme getGenerationScheme() const override {
Jordan Rose367843a2013-08-16 01:06:30 +000098 return IncludePath ? Minimal : None;
99 }
100
101 void enablePaths() {
102 IncludePath = true;
103 }
104
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000105 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000106 FilesMade *filesMade) override {
Alp Toker5c494cb2013-12-23 17:59:59 +0000107 unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
108 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
109
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000110 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
111 E = Diags.end(); I != E; ++I) {
112 const PathDiagnostic *PD = *I;
Alp Toker5c494cb2013-12-23 17:59:59 +0000113 SourceLocation WarnLoc = PD->getLocation().asLocation();
Alexander Kornienkoa74979d2014-03-06 13:23:30 +0000114 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
115 << PD->path.back()->getRanges();
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000116
Artem Dergachevb1991c52016-10-07 19:25:10 +0000117 // First, add extra notes, even if paths should not be included.
118 for (const auto &Piece : PD->path) {
119 if (!isa<PathDiagnosticNotePiece>(Piece.get()))
120 continue;
121
122 SourceLocation NoteLoc = Piece->getLocation().asLocation();
123 Diag.Report(NoteLoc, NoteID) << Piece->getString()
124 << Piece->getRanges();
125 }
126
Jordan Rose367843a2013-08-16 01:06:30 +0000127 if (!IncludePath)
128 continue;
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000129
Artem Dergachevb1991c52016-10-07 19:25:10 +0000130 // Then, add the path notes if necessary.
Jordan Rose367843a2013-08-16 01:06:30 +0000131 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
Artem Dergachevb1991c52016-10-07 19:25:10 +0000132 for (const auto &Piece : FlatPath) {
133 if (isa<PathDiagnosticNotePiece>(Piece.get()))
134 continue;
135
136 SourceLocation NoteLoc = Piece->getLocation().asLocation();
137 Diag.Report(NoteLoc, NoteID) << Piece->getString()
138 << Piece->getRanges();
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000139 }
140 }
141 }
142};
143} // end anonymous namespace
144
Ted Kremenek04ade6f2009-07-27 22:13:39 +0000145//===----------------------------------------------------------------------===//
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000146// AnalysisConsumer declaration.
147//===----------------------------------------------------------------------===//
148
149namespace {
150
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000151class AnalysisConsumer : public AnalysisASTConsumer,
Richard Smith50668452015-11-24 03:55:01 +0000152 public RecursiveASTVisitor<AnalysisConsumer> {
Jordan Rosed8665b32012-10-10 17:55:40 +0000153 enum {
154 AM_None = 0,
155 AM_Syntax = 0x1,
156 AM_Path = 0x2
Anna Zaks14189512012-03-13 19:32:00 +0000157 };
Jordan Rosed8665b32012-10-10 17:55:40 +0000158 typedef unsigned AnalysisMode;
Anna Zaks14189512012-03-13 19:32:00 +0000159
160 /// Mode of the analyzes while recursively visiting Decls.
161 AnalysisMode RecVisitorMode;
162 /// Bug Reporter to use while recursively visiting Decls.
163 BugReporter *RecVisitorBR;
164
Alexander Kornienkod00ed8e2018-06-27 14:56:12 +0000165 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
166
Zhongxing Xu685a1d82010-04-30 04:14:20 +0000167public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000168 ASTContext *Ctx;
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000169 const Preprocessor &PP;
170 const std::string OutDir;
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000171 AnalyzerOptionsRef Opts;
Jordy Rose59cce712011-08-16 21:24:21 +0000172 ArrayRef<std::string> Plugins;
Ted Kremenekeeccb302014-08-27 15:14:15 +0000173 CodeInjector *Injector;
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000174 cross_tu::CrossTranslationUnitContext CTU;
Zhongxing Xub9a45a42009-08-03 03:27:37 +0000175
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000176 /// Stores the declarations from the local translation unit.
Anna Zaks8e078522012-04-12 22:36:48 +0000177 /// Note, we pre-compute the local declarations at parse time as an
178 /// optimization to make sure we do not deserialize everything from disk.
179 /// The local declaration to all declarations ratio might be very small when
180 /// working with a PCH file.
181 SetOfDecls LocalTUDecls;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000182
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000183 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
184 PathDiagnosticConsumers PathConsumers;
Zhongxing Xub9a45a42009-08-03 03:27:37 +0000185
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000186 StoreManagerCreator CreateStoreMgr;
187 ConstraintManagerCreator CreateConstraintMgr;
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000188
Ahmed Charlesb8984322014-03-07 20:03:18 +0000189 std::unique_ptr<CheckerManager> checkerMgr;
190 std::unique_ptr<AnalysisManager> Mgr;
Zhongxing Xubcbe44f2009-08-03 03:13:46 +0000191
Anna Zaks9bd4be92012-03-05 20:53:59 +0000192 /// Time the analyzes time of each translation unit.
George Karpenkov5a755b32018-02-10 01:49:20 +0000193 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
194 std::unique_ptr<llvm::Timer> TUTotalTimer;
Anna Zaks9bd4be92012-03-05 20:53:59 +0000195
Anna Zaks54fd4a02012-03-30 05:48:10 +0000196 /// The information about analyzed functions shared throughout the
197 /// translation unit.
198 FunctionSummariesTy FunctionSummaries;
199
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000200 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000201 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
Ted Kremenekeeccb302014-08-27 15:14:15 +0000202 CodeInjector *injector)
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000203 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
204 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
205 Plugins(plugins), Injector(injector), CTU(CI) {
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000206 DigestAnalyzerOptions();
George Karpenkov5a755b32018-02-10 01:49:20 +0000207 if (Opts->PrintStats || Opts->shouldSerializeStats()) {
208 AnalyzerTimers = llvm::make_unique<llvm::TimerGroup>(
209 "analyzer", "Analyzer timers");
210 TUTotalTimer = llvm::make_unique<llvm::Timer>(
211 "time", "Analyzer total time", *AnalyzerTimers);
212 llvm::EnableStatistics(/* PrintOnExit= */ false);
Anna Zaks9bd4be92012-03-05 20:53:59 +0000213 }
214 }
215
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000216 ~AnalysisConsumer() override {
Matthias Braunabb6eea2016-09-26 18:53:34 +0000217 if (Opts->PrintStats) {
Matthias Braunabb6eea2016-09-26 18:53:34 +0000218 llvm::PrintStatistics();
219 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000220 }
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000221
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000222 void DigestAnalyzerOptions() {
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000223 if (Opts->AnalysisDiagOpt != PD_NONE) {
224 // Create the PathDiagnosticConsumer.
225 ClangDiagPathDiagConsumer *clangDiags =
226 new ClangDiagPathDiagConsumer(PP.getDiagnostics());
227 PathConsumers.push_back(clangDiags);
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000228
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000229 if (Opts->AnalysisDiagOpt == PD_TEXT) {
230 clangDiags->enablePaths();
Jordan Rose367843a2013-08-16 01:06:30 +0000231
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000232 } else if (!OutDir.empty()) {
233 switch (Opts->AnalysisDiagOpt) {
234 default:
235#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
236 case PD_##NAME: \
Alp Tokerf994cef2014-07-05 03:08:06 +0000237 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000238 break;
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000239#include "clang/StaticAnalyzer/Core/Analyses.def"
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000240 }
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000241 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000242 }
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000243
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000244 // Create the analyzer component creators.
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000245 switch (Opts->AnalysisStoreOpt) {
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000246 default:
David Blaikie83d382b2011-09-23 05:06:16 +0000247 llvm_unreachable("Unknown store manager.");
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000248#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000249 case NAME##Model: CreateStoreMgr = CREATEFN; break;
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000250#include "clang/StaticAnalyzer/Core/Analyses.def"
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000251 }
Mike Stump11289f42009-09-09 15:08:12 +0000252
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000253 switch (Opts->AnalysisConstraintsOpt) {
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000254 default:
Anna Zaks297176c2013-02-07 23:29:20 +0000255 llvm_unreachable("Unknown constraint manager.");
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000256#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000257 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000258#include "clang/StaticAnalyzer/Core/Analyses.def"
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000259 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000260 }
Ted Kremenek39df94b2010-02-14 19:08:51 +0000261
Anna Zakse9eb13a2013-02-02 00:30:02 +0000262 void DisplayFunction(const Decl *D, AnalysisMode Mode,
263 ExprEngine::InliningModes IMode) {
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000264 if (!Opts->AnalyzerDisplayProgress)
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000265 return;
Ted Kremenek39df94b2010-02-14 19:08:51 +0000266
Ted Kremenek68189912009-12-07 22:06:12 +0000267 SourceManager &SM = Mgr->getASTContext().getSourceManager();
268 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000269 if (Loc.isValid()) {
Anna Zaks14189512012-03-13 19:32:00 +0000270 llvm::errs() << "ANALYZE";
Jordan Rosed8665b32012-10-10 17:55:40 +0000271
272 if (Mode == AM_Syntax)
273 llvm::errs() << " (Syntax)";
Anna Zakse9eb13a2013-02-02 00:30:02 +0000274 else if (Mode == AM_Path) {
275 llvm::errs() << " (Path, ";
276 switch (IMode) {
Anna Zaksb13d21b2013-03-26 18:57:58 +0000277 case ExprEngine::Inline_Minimal:
278 llvm::errs() << " Inline_Minimal";
Anna Zakse9eb13a2013-02-02 00:30:02 +0000279 break;
Anna Zaksb13d21b2013-03-26 18:57:58 +0000280 case ExprEngine::Inline_Regular:
281 llvm::errs() << " Inline_Regular";
Anna Zakse9eb13a2013-02-02 00:30:02 +0000282 break;
283 }
284 llvm::errs() << ")";
285 }
Jordan Rosed8665b32012-10-10 17:55:40 +0000286 else
287 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
288
Artem Dergachev6a76a162016-08-08 16:01:02 +0000289 llvm::errs() << ": " << Loc.getFilename() << ' '
290 << getFunctionName(D) << '\n';
Ted Kremenek7043fba2010-10-22 22:08:29 +0000291 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000292 }
Mike Stump11289f42009-09-09 15:08:12 +0000293
Craig Topperfb6b25b2014-03-15 04:29:04 +0000294 void Initialize(ASTContext &Context) override {
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000295 Ctx = &Context;
George Karpenkov4ece68a2018-08-06 23:09:07 +0000296 checkerMgr = createCheckerManager(
297 *Ctx, *Opts, Plugins, CheckerRegistrationFns, PP.getDiagnostics());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000298
David Blaikie53dd8fe2014-08-29 20:11:03 +0000299 Mgr = llvm::make_unique<AnalysisManager>(
George Karpenkov4ece68a2018-08-06 23:09:07 +0000300 *Ctx, PP.getDiagnostics(), PathConsumers, CreateStoreMgr,
301 CreateConstraintMgr, checkerMgr.get(), *Opts, Injector);
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000302 }
Mike Stump11289f42009-09-09 15:08:12 +0000303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304 /// Store the top level decls in the set to be processed later on.
Anna Zaks8e078522012-04-12 22:36:48 +0000305 /// (Doing this pre-processing avoids deserialization of data from PCH.)
Craig Topperfb6b25b2014-03-15 04:29:04 +0000306 bool HandleTopLevelDecl(DeclGroupRef D) override;
307 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
Anna Zaks8e078522012-04-12 22:36:48 +0000308
Craig Topperfb6b25b2014-03-15 04:29:04 +0000309 void HandleTranslationUnit(ASTContext &C) override;
Ted Kremeneka1ec4f32011-01-20 17:09:48 +0000310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000311 /// Determine which inlining mode should be used when this function is
Anna Zaksb13d21b2013-03-26 18:57:58 +0000312 /// analyzed. This allows to redefine the default inlining policies when
313 /// analyzing a given function.
Anna Zaks5d484782012-12-07 21:51:47 +0000314 ExprEngine::InliningModes
Anna Zaksd5478fd2014-08-29 20:01:38 +0000315 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
Anna Zaks5d484782012-12-07 21:51:47 +0000316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000317 /// Build the call graph for all the top level decls of this TU and
Anna Zaks8e078522012-04-12 22:36:48 +0000318 /// use it to define the order in which the functions should be visited.
Jordan Rose85c8c812012-10-10 17:55:37 +0000319 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
Anna Zaks14189512012-03-13 19:32:00 +0000320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// Run analyzes(syntax or path sensitive) on the given function.
Anna Zaks14189512012-03-13 19:32:00 +0000322 /// \param Mode - determines if we are requesting syntax only or path
323 /// sensitive only analysis.
324 /// \param VisitedCallees - The output parameter, which is populated with the
325 /// set of functions which should be considered analyzed after analyzing the
326 /// given root function.
Anna Zaks8e078522012-04-12 22:36:48 +0000327 void HandleCode(Decl *D, AnalysisMode Mode,
Anna Zaksb13d21b2013-03-26 18:57:58 +0000328 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
Craig Topper0dbb7832014-05-27 02:45:47 +0000329 SetOfConstDecls *VisitedCallees = nullptr);
Anna Zaks14189512012-03-13 19:32:00 +0000330
Anna Zaks5d484782012-12-07 21:51:47 +0000331 void RunPathSensitiveChecks(Decl *D,
332 ExprEngine::InliningModes IMode,
333 SetOfConstDecls *VisitedCallees);
Anna Zaks14189512012-03-13 19:32:00 +0000334
335 /// Visitors for the RecursiveASTVisitor.
Anna Zakse7e7c9e2012-05-11 23:15:18 +0000336 bool shouldWalkTypesOfTypeLocs() const { return false; }
Anna Zaks14189512012-03-13 19:32:00 +0000337
338 /// Handle callbacks for arbitrary Decls.
339 bool VisitDecl(Decl *D) {
Jordan Rosed8665b32012-10-10 17:55:40 +0000340 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
341 if (Mode & AM_Syntax)
342 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
Anna Zaks14189512012-03-13 19:32:00 +0000343 return true;
344 }
345
346 bool VisitFunctionDecl(FunctionDecl *FD) {
347 IdentifierInfo *II = FD->getIdentifier();
348 if (II && II->getName().startswith("__inline"))
349 return true;
350
351 // We skip function template definitions, as their semantics is
352 // only determined when they are instantiated.
353 if (FD->isThisDeclarationADefinition() &&
354 !FD->isDependentContext()) {
Anna Zaks5d484782012-12-07 21:51:47 +0000355 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Anna Zaks14189512012-03-13 19:32:00 +0000356 HandleCode(FD, RecVisitorMode);
357 }
358 return true;
359 }
360
361 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
Anna Zaks5d484782012-12-07 21:51:47 +0000362 if (MD->isThisDeclarationADefinition()) {
363 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Anna Zaks14189512012-03-13 19:32:00 +0000364 HandleCode(MD, RecVisitorMode);
Anna Zaks5d484782012-12-07 21:51:47 +0000365 }
Anna Zaks14189512012-03-13 19:32:00 +0000366 return true;
367 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000368
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000369 bool VisitBlockDecl(BlockDecl *BD) {
370 if (BD->hasBody()) {
371 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Devin Coughlin6e644ab2015-11-18 22:46:52 +0000372 // Since we skip function template definitions, we should skip blocks
373 // declared in those functions as well.
374 if (!BD->isDependentContext()) {
375 HandleCode(BD, RecVisitorMode);
376 }
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000377 }
378 return true;
379 }
Anna Zaks8e078522012-04-12 22:36:48 +0000380
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000381 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000382 PathConsumers.push_back(Consumer);
383 }
384
Alexander Kornienkod00ed8e2018-06-27 14:56:12 +0000385 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
386 CheckerRegistrationFns.push_back(std::move(Fn));
387 }
388
Anna Zaks8e078522012-04-12 22:36:48 +0000389private:
390 void storeTopLevelDecls(DeclGroupRef DG);
Artem Dergachev6a76a162016-08-08 16:01:02 +0000391 std::string getFunctionName(const Decl *D);
Anna Zaks8e078522012-04-12 22:36:48 +0000392
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000393 /// Check if we should skip (not analyze) the given function.
Jordan Rosed8665b32012-10-10 17:55:40 +0000394 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000395 void runAnalysisOnTranslationUnit(ASTContext &C);
Anna Zaks8e078522012-04-12 22:36:48 +0000396
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000397 /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
398 void reportAnalyzerProgress(StringRef S);
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000399};
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000400} // end anonymous namespace
401
Anna Zaks14189512012-03-13 19:32:00 +0000402
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000403//===----------------------------------------------------------------------===//
404// AnalysisConsumer implementation.
405//===----------------------------------------------------------------------===//
Anna Zaks8e078522012-04-12 22:36:48 +0000406bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
407 storeTopLevelDecls(DG);
408 return true;
409}
410
411void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
412 storeTopLevelDecls(DG);
413}
414
415void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
416 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
417
418 // Skip ObjCMethodDecl, wait for the objc container to avoid
419 // analyzing twice.
420 if (isa<ObjCMethodDecl>(*I))
421 continue;
422
Ted Kremenek2964aac2012-04-27 04:54:28 +0000423 LocalTUDecls.push_back(*I);
Anna Zaks8e078522012-04-12 22:36:48 +0000424 }
425}
426
Anna Zaks5f2af812012-12-14 19:08:17 +0000427static bool shouldSkipFunction(const Decl *D,
Alexander Kornienkofe659982014-04-23 16:39:41 +0000428 const SetOfConstDecls &Visited,
429 const SetOfConstDecls &VisitedAsTopLevel) {
Anna Zaks5f2af812012-12-14 19:08:17 +0000430 if (VisitedAsTopLevel.count(D))
Anna Zaks5d484782012-12-07 21:51:47 +0000431 return true;
432
433 // We want to re-analyse the functions as top level in the following cases:
Anna Zaksa8017ec2012-08-30 23:42:02 +0000434 // - The 'init' methods should be reanalyzed because
435 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
Anna Zaks5d484782012-12-07 21:51:47 +0000436 // 'nil' and unless we analyze the 'init' functions as top level, we will
437 // not catch errors within defensive code.
Anna Zaksa8017ec2012-08-30 23:42:02 +0000438 // - We want to reanalyze all ObjC methods as top level to report Retain
439 // Count naming convention errors more aggressively.
Anna Zaks5f2af812012-12-14 19:08:17 +0000440 if (isa<ObjCMethodDecl>(D))
Anna Zaksa8017ec2012-08-30 23:42:02 +0000441 return false;
Devin Coughlinf57f90d2016-07-21 23:42:31 +0000442 // We also want to reanalyze all C++ copy and move assignment operators to
443 // separately check the two cases where 'this' aliases with the parameter and
444 // where it may not. (cplusplus.SelfAssignmentChecker)
445 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
446 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
447 return false;
448 }
Anna Zaksa8017ec2012-08-30 23:42:02 +0000449
450 // Otherwise, if we visited the function before, do not reanalyze it.
Anna Zaks5f2af812012-12-14 19:08:17 +0000451 return Visited.count(D);
Anna Zaksa8017ec2012-08-30 23:42:02 +0000452}
453
Anna Zaks5d484782012-12-07 21:51:47 +0000454ExprEngine::InliningModes
Anna Zaks5f2af812012-12-14 19:08:17 +0000455AnalysisConsumer::getInliningModeForFunction(const Decl *D,
Alexander Kornienkofe659982014-04-23 16:39:41 +0000456 const SetOfConstDecls &Visited) {
Anna Zaks5d484782012-12-07 21:51:47 +0000457 // We want to reanalyze all ObjC methods as top level to report Retain
Anna Zaksb13d21b2013-03-26 18:57:58 +0000458 // Count naming convention errors more aggressively. But we should tune down
Anna Zaks5d484782012-12-07 21:51:47 +0000459 // inlining when reanalyzing an already inlined function.
Devin Coughlinf57f90d2016-07-21 23:42:31 +0000460 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
Anna Zaks5f2af812012-12-14 19:08:17 +0000461 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
Anna Zaks5d484782012-12-07 21:51:47 +0000462 if (ObjCM->getMethodFamily() != OMF_init)
Anna Zaksb13d21b2013-03-26 18:57:58 +0000463 return ExprEngine::Inline_Minimal;
Anna Zaks5d484782012-12-07 21:51:47 +0000464 }
465
Anna Zaksb13d21b2013-03-26 18:57:58 +0000466 return ExprEngine::Inline_Regular;
Anna Zaks5d484782012-12-07 21:51:47 +0000467}
468
Jordan Rose85c8c812012-10-10 17:55:37 +0000469void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
Anna Zaks1ee76c12012-12-21 17:27:01 +0000470 // Build the Call Graph by adding all the top level declarations to the graph.
Anna Zaks2774f992012-05-31 18:07:55 +0000471 // Note: CallGraph can trigger deserialization of more items from a pch
472 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
473 // We rely on random access to add the initially processed Decls to CG.
Anna Zaks1ee76c12012-12-21 17:27:01 +0000474 CallGraph CG;
Anna Zaks2774f992012-05-31 18:07:55 +0000475 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
Anna Zaks34d89b72012-05-30 23:14:48 +0000476 CG.addToCallGraph(LocalTUDecls[i]);
477 }
Anna Zakseee91102012-03-08 23:16:38 +0000478
Anna Zaks1ee76c12012-12-21 17:27:01 +0000479 // Walk over all of the call graph nodes in topological order, so that we
480 // analyze parents before the children. Skip the functions inlined into
481 // the previously processed functions. Use external Visited set to identify
482 // inlined functions. The topological order allows the "do not reanalyze
483 // previously inlined function" performance heuristic to be triggered more
484 // often.
Anna Zaks5f2af812012-12-14 19:08:17 +0000485 SetOfConstDecls Visited;
486 SetOfConstDecls VisitedAsTopLevel;
Anna Zaks1ee76c12012-12-21 17:27:01 +0000487 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
488 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
489 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
490 NumFunctionTopLevel++;
Anna Zaksca70ed52012-03-13 19:32:13 +0000491
Anna Zaks1ee76c12012-12-21 17:27:01 +0000492 CallGraphNode *N = *I;
Anna Zaks5f2af812012-12-14 19:08:17 +0000493 Decl *D = N->getDecl();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000494
Anna Zaks1ee76c12012-12-21 17:27:01 +0000495 // Skip the abstract root node.
496 if (!D)
497 continue;
Anna Zaks5f2af812012-12-14 19:08:17 +0000498
Anna Zaksca70ed52012-03-13 19:32:13 +0000499 // Skip the functions which have been processed already or previously
500 // inlined.
Anna Zaks5f2af812012-12-14 19:08:17 +0000501 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
Anna Zaksca70ed52012-03-13 19:32:13 +0000502 continue;
503
504 // Analyze the function.
Anna Zaks8e078522012-04-12 22:36:48 +0000505 SetOfConstDecls VisitedCallees;
Anna Zaks5d484782012-12-07 21:51:47 +0000506
Anna Zaks5f2af812012-12-14 19:08:17 +0000507 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
Craig Topper0dbb7832014-05-27 02:45:47 +0000508 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
Anna Zaksca70ed52012-03-13 19:32:13 +0000509
510 // Add the visited callees to the global visited set.
Yury Gribov054873b2016-01-11 09:38:48 +0000511 for (const Decl *Callee : VisitedCallees)
512 // Decls from CallGraph are already canonical. But Decls coming from
513 // CallExprs may be not. We should canonicalize them manually.
514 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
515 : Callee->getCanonicalDecl());
Anna Zaks5f2af812012-12-14 19:08:17 +0000516 VisitedAsTopLevel.insert(D);
Anna Zakseee91102012-03-08 23:16:38 +0000517 }
Ted Kremenek60120fb2011-08-27 21:28:09 +0000518}
519
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000520static bool isBisonFile(ASTContext &C) {
521 const SourceManager &SM = C.getSourceManager();
522 FileID FID = SM.getMainFileID();
523 StringRef Buffer = SM.getBuffer(FID)->getBuffer();
524 if (Buffer.startswith("/* A Bison parser, made by"))
525 return true;
526 return false;
527}
528
529void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
530 BugReporter BR(*Mgr);
531 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
532 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
533
534 // Run the AST-only checks using the order in which functions are defined.
535 // If inlining is not turned on, use the simplest function order for path
536 // sensitive analyzes as well.
537 RecVisitorMode = AM_Syntax;
538 if (!Mgr->shouldInlineCall())
539 RecVisitorMode |= AM_Path;
540 RecVisitorBR = &BR;
541
542 // Process all the top level declarations.
543 //
544 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
545 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
546 // random access. By doing so, we automatically compensate for iterators
547 // possibly being invalidated, although this is a bit slower.
548 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
549 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
550 TraverseDecl(LocalTUDecls[i]);
551 }
552
553 if (Mgr->shouldInlineCall())
554 HandleDeclsCallGraph(LocalTUDeclsSize);
555
556 // After all decls handled, run checkers on the entire TranslationUnit.
557 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
558
559 RecVisitorBR = nullptr;
560}
561
562void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
563 if (Opts->AnalyzerDisplayProgress)
564 llvm::errs() << S;
565}
566
Ted Kremeneka1ec4f32011-01-20 17:09:48 +0000567void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000568
Anna Zaks14189512012-03-13 19:32:00 +0000569 // Don't run the actions if an error has occurred with parsing the file.
570 DiagnosticsEngine &Diags = PP.getDiagnostics();
571 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
572 return;
573
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000574 if (TUTotalTimer) TUTotalTimer->startTimer();
Anna Zaksd5478fd2014-08-29 20:01:38 +0000575
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000576 if (isBisonFile(C)) {
577 reportAnalyzerProgress("Skipping bison-generated file\n");
578 } else if (Opts->DisableAllChecks) {
Anna Zaks9bd4be92012-03-05 20:53:59 +0000579
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000580 // Don't analyze if the user explicitly asked for no checks to be performed
581 // on this file.
582 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
583 } else {
584 // Otherwise, just run the analysis.
585 runAnalysisOnTranslationUnit(C);
Anna Zaks17f57b02012-01-07 16:49:46 +0000586 }
Ted Kremeneke69ab052011-05-05 03:41:17 +0000587
Anna Zaks9bd4be92012-03-05 20:53:59 +0000588 if (TUTotalTimer) TUTotalTimer->stopTimer();
Anna Zaks8382e452012-04-05 02:10:21 +0000589
590 // Count how many basic blocks we have not covered.
591 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
George Karpenkov2a639852018-02-09 23:37:47 +0000592 NumVisitedBlocksInAnalyzedFunctions =
593 FunctionSummaries.getTotalNumVisitedBasicBlocks();
Anna Zaks8382e452012-04-05 02:10:21 +0000594 if (NumBlocksInAnalyzedFunctions > 0)
595 PercentReachableBlocks =
596 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
597 NumBlocksInAnalyzedFunctions;
598
George Karpenkov5a755b32018-02-10 01:49:20 +0000599 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
600 // FIXME: This should be replaced with something that doesn't rely on
601 // side-effects in PathDiagnosticConsumer's destructor. This is required when
602 // used with option -disable-free.
603 Mgr.reset();
Ted Kremenek0e7d2522008-07-03 04:29:21 +0000604}
605
Artem Dergachev6a76a162016-08-08 16:01:02 +0000606std::string AnalysisConsumer::getFunctionName(const Decl *D) {
607 std::string Str;
608 llvm::raw_string_ostream OS(Str);
609
610 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
611 OS << FD->getQualifiedNameAsString();
612
613 // In C++, there are overloads.
614 if (Ctx->getLangOpts().CPlusPlus) {
615 OS << '(';
616 for (const auto &P : FD->parameters()) {
617 if (P != *FD->param_begin())
618 OS << ", ";
619 OS << P->getType().getAsString();
620 }
621 OS << ')';
622 }
623
624 } else if (isa<BlockDecl>(D)) {
625 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
626
627 if (Loc.isValid()) {
628 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
629 << ')';
630 }
631
632 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
633
634 // FIXME: copy-pasted from CGDebugInfo.cpp.
635 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
636 const DeclContext *DC = OMD->getDeclContext();
637 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
638 OS << OID->getName();
639 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
640 OS << OID->getName();
641 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
642 if (OC->IsClassExtension()) {
643 OS << OC->getClassInterface()->getName();
644 } else {
645 OS << OC->getIdentifier()->getNameStart() << '('
646 << OC->getIdentifier()->getNameStart() << ')';
647 }
648 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +0000649 OS << OCD->getClassInterface()->getName() << '('
650 << OCD->getName() << ')';
Artem Dergachev6a76a162016-08-08 16:01:02 +0000651 } else if (isa<ObjCProtocolDecl>(DC)) {
652 // We can extract the type of the class from the self pointer.
653 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
654 QualType ClassTy =
655 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
656 ClassTy.print(OS, PrintingPolicy(LangOptions()));
657 }
658 }
659 OS << ' ' << OMD->getSelector().getAsString() << ']';
660
Anna Zakseee91102012-03-08 23:16:38 +0000661 }
Artem Dergachev6a76a162016-08-08 16:01:02 +0000662
663 return OS.str();
Anna Zakseee91102012-03-08 23:16:38 +0000664}
665
Jordan Rosed8665b32012-10-10 17:55:40 +0000666AnalysisConsumer::AnalysisMode
667AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000668 if (!Opts->AnalyzeSpecificFunction.empty() &&
669 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
Jordan Rosed8665b32012-10-10 17:55:40 +0000670 return AM_None;
Mike Stump11289f42009-09-09 15:08:12 +0000671
Jordan Rosed8665b32012-10-10 17:55:40 +0000672 // Unless -analyze-all is specified, treat decls differently depending on
673 // where they came from:
674 // - Main source file: run both path-sensitive and non-path-sensitive checks.
675 // - Header files: run non-path-sensitive checks only.
676 // - System headers: don't run any checks.
Ted Kremenek4c721bf2010-06-15 00:55:40 +0000677 SourceManager &SM = Ctx->getSourceManager();
Aaron Ballman65693872015-08-20 21:27:35 +0000678 const Stmt *Body = D->getBody();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000679 SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
Anna Zaks3849dea2015-06-26 17:42:58 +0000680 SL = SM.getExpansionLoc(SL);
681
Artem Dergachev516837f2018-04-25 21:51:26 +0000682 if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
Jordan Rosed8665b32012-10-10 17:55:40 +0000683 if (SL.isInvalid() || SM.isInSystemHeader(SL))
684 return AM_None;
685 return Mode & ~AM_Path;
686 }
Anna Zaksaa19abe2012-03-13 19:31:54 +0000687
Jordan Rosed8665b32012-10-10 17:55:40 +0000688 return Mode;
Anna Zaksaa19abe2012-03-13 19:31:54 +0000689}
690
Anna Zaks14189512012-03-13 19:32:00 +0000691void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
Anna Zaks5d484782012-12-07 21:51:47 +0000692 ExprEngine::InliningModes IMode,
Anna Zaks8e078522012-04-12 22:36:48 +0000693 SetOfConstDecls *VisitedCallees) {
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000694 if (!D->hasBody())
695 return;
Jordan Rosed8665b32012-10-10 17:55:40 +0000696 Mode = getModeForDecl(D, Mode);
697 if (Mode == AM_None)
Mike Stump11289f42009-09-09 15:08:12 +0000698 return;
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000699
Alexander Shaposhnikova1fead22016-09-23 20:49:01 +0000700 // Clear the AnalysisManager of old AnalysisDeclContexts.
701 Mgr->ClearContexts();
702 // Ignore autosynthesized code.
703 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
704 return;
705
Anna Zakse9eb13a2013-02-02 00:30:02 +0000706 DisplayFunction(D, Mode, IMode);
Anna Zaks40b87fc2012-07-05 20:44:02 +0000707 CFG *DeclCFG = Mgr->getCFG(D);
Craig Topper704b4fb2017-05-18 01:11:52 +0000708 if (DeclCFG)
709 MaxCFGSize.updateMax(DeclCFG->size());
Anna Zaks40b87fc2012-07-05 20:44:02 +0000710
Argyrios Kyrtzidis24ffc082011-02-17 21:39:24 +0000711 BugReporter BR(*Mgr);
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000712
713 if (Mode & AM_Syntax)
714 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
715 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
716 RunPathSensitiveChecks(D, IMode, VisitedCallees);
Anna Zaksb13d21b2013-03-26 18:57:58 +0000717 if (IMode != ExprEngine::Inline_Minimal)
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000718 NumFunctionsAnalyzed++;
719 }
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000720}
721
722//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6a1c7602011-02-28 19:49:17 +0000723// Path-sensitive checking.
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000724//===----------------------------------------------------------------------===//
725
George Karpenkovc82d4572018-09-28 18:49:41 +0000726void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
727 ExprEngine::InliningModes IMode,
728 SetOfConstDecls *VisitedCallees) {
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000729 // Construct the analysis engine. First check if the CFG is valid.
Ted Kremenek1e7f9882009-09-18 22:29:35 +0000730 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
Anna Zaks394d07e2012-03-09 21:14:01 +0000731 if (!Mgr->getCFG(D))
Ted Kremenek39df94b2010-02-14 19:08:51 +0000732 return;
Anna Zaks394d07e2012-03-09 21:14:01 +0000733
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000734 // See if the LiveVariables analysis scales.
735 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
736 return;
737
George Karpenkovc82d4572018-09-28 18:49:41 +0000738 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
Ted Kremenek39df94b2010-02-14 19:08:51 +0000739
Ted Kremenek8e631a02008-07-02 00:44:58 +0000740 // Execute the worklist algorithm.
Jordy Rose4f8198e2012-04-28 01:58:08 +0000741 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
Anna Zaksc84d1512013-01-30 19:12:39 +0000742 Mgr->options.getMaxNodesPerTopLevelFunction());
Mike Stump11289f42009-09-09 15:08:12 +0000743
George Karpenkovc704f4f2018-09-28 18:49:21 +0000744 if (!Mgr->options.DumpExplodedGraphTo.empty())
745 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
746
Ted Kremenek71ac8322008-07-02 16:49:11 +0000747 // Visualize the exploded graph.
Ted Kremenekb8f8b352012-08-30 19:26:53 +0000748 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
Ted Kremenek8756c4a2012-08-30 19:26:43 +0000749 Eng.ViewGraph(Mgr->options.TrimGraph);
Mike Stump11289f42009-09-09 15:08:12 +0000750
Ted Kremenek39df18f2009-03-11 01:42:29 +0000751 // Display warnings.
752 Eng.getBugReporter().FlushReports();
Ted Kremenekbecec2c2008-07-02 16:35:50 +0000753}
754
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000755//===----------------------------------------------------------------------===//
756// AnalysisConsumer creation.
757//===----------------------------------------------------------------------===//
758
David Blaikie6beb6aa2014-08-10 19:56:51 +0000759std::unique_ptr<AnalysisASTConsumer>
Ted Kremenekeeccb302014-08-27 15:14:15 +0000760ento::CreateAnalysisConsumer(CompilerInstance &CI) {
Jordy Rose59cce712011-08-16 21:24:21 +0000761 // Disable the effects of '-Werror' when using the AnalysisConsumer.
Ted Kremenekeeccb302014-08-27 15:14:15 +0000762 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
Ted Kremenekb5351812009-02-17 04:27:41 +0000763
Ted Kremenekeeccb302014-08-27 15:14:15 +0000764 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
765 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
766
767 return llvm::make_unique<AnalysisConsumer>(
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000768 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
Ted Kremenekeeccb302014-08-27 15:14:15 +0000769 CI.getFrontendOpts().Plugins,
770 hasModelPath ? new ModelInjector(CI) : nullptr);
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000771}