blob: 81f694368613a5340d2937a6e1ca4aa54ac62cf9 [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
David Blaikiea48a53c2014-09-05 00:14:57 +000053static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz();
Zhongxing Xu5b0ae812008-12-22 01:52:37 +000054
Anna Zaks394d07e2012-03-09 21:14:01 +000055STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
Anna Zaks5d484782012-12-07 21:51:47 +000056STATISTIC(NumFunctionsAnalyzed,
Anna Zaksad3704c2012-12-17 20:08:54 +000057 "The # of functions and blocks analyzed (as top level "
58 "with inlining turned on).");
Anna Zakscc24e452012-04-03 02:05:47 +000059STATISTIC(NumBlocksInAnalyzedFunctions,
Anna Zaksad3704c2012-12-17 20:08:54 +000060 "The # of basic blocks in the analyzed functions.");
George Karpenkov2a639852018-02-09 23:37:47 +000061STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
62 "The # of visited basic blocks in the analyzed functions.");
Anna Zakscc24e452012-04-03 02:05:47 +000063STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
Anna Zaks40b87fc2012-07-05 20:44:02 +000064STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
Anna Zakseee91102012-03-08 23:16:38 +000065
Ted Kremenekb5351812009-02-17 04:27:41 +000066//===----------------------------------------------------------------------===//
David Blaikie0cc49432011-09-27 01:43:33 +000067// Special PathDiagnosticConsumers.
Ted Kremenek04ade6f2009-07-27 22:13:39 +000068//===----------------------------------------------------------------------===//
69
Jordan Rose367843a2013-08-16 01:06:30 +000070void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
71 PathDiagnosticConsumers &C,
72 const std::string &prefix,
73 const Preprocessor &PP) {
Ted Kremenek3a081a02012-12-19 01:35:35 +000074 createHTMLDiagnosticConsumer(AnalyzerOpts, C,
75 llvm::sys::path::parent_path(prefix), PP);
Artem Dergachev21948342018-05-16 00:11:24 +000076 createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
Ted Kremenek04ade6f2009-07-27 22:13:39 +000077}
78
Jordan Rose367843a2013-08-16 01:06:30 +000079void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
80 PathDiagnosticConsumers &C,
81 const std::string &Prefix,
82 const clang::Preprocessor &PP) {
83 llvm_unreachable("'text' consumer should be enabled on ClangDiags");
84}
85
Ted Kremenek9bf9af92012-08-16 17:45:23 +000086namespace {
87class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
88 DiagnosticsEngine &Diag;
Jordan Rose367843a2013-08-16 01:06:30 +000089 bool IncludePath;
Ted Kremenek9bf9af92012-08-16 17:45:23 +000090public:
Jordan Rose367843a2013-08-16 01:06:30 +000091 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
92 : Diag(Diag), IncludePath(false) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000093 ~ClangDiagPathDiagConsumer() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +000094 StringRef getName() const override { return "ClangDiags"; }
Jordan Rose367843a2013-08-16 01:06:30 +000095
Craig Topperfb6b25b2014-03-15 04:29:04 +000096 bool supportsLogicalOpControlFlow() const override { return true; }
97 bool supportsCrossFileDiagnostics() const override { return true; }
Jordan Rose367843a2013-08-16 01:06:30 +000098
Craig Topperfb6b25b2014-03-15 04:29:04 +000099 PathGenerationScheme getGenerationScheme() const override {
Jordan Rose367843a2013-08-16 01:06:30 +0000100 return IncludePath ? Minimal : None;
101 }
102
103 void enablePaths() {
104 IncludePath = true;
105 }
106
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000107 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000108 FilesMade *filesMade) override {
Alp Toker5c494cb2013-12-23 17:59:59 +0000109 unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
110 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
111
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000112 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
113 E = Diags.end(); I != E; ++I) {
114 const PathDiagnostic *PD = *I;
Alp Toker5c494cb2013-12-23 17:59:59 +0000115 SourceLocation WarnLoc = PD->getLocation().asLocation();
Alexander Kornienkoa74979d2014-03-06 13:23:30 +0000116 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
117 << PD->path.back()->getRanges();
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000118
Artem Dergachevb1991c52016-10-07 19:25:10 +0000119 // First, add extra notes, even if paths should not be included.
120 for (const auto &Piece : PD->path) {
121 if (!isa<PathDiagnosticNotePiece>(Piece.get()))
122 continue;
123
124 SourceLocation NoteLoc = Piece->getLocation().asLocation();
125 Diag.Report(NoteLoc, NoteID) << Piece->getString()
126 << Piece->getRanges();
127 }
128
Jordan Rose367843a2013-08-16 01:06:30 +0000129 if (!IncludePath)
130 continue;
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000131
Artem Dergachevb1991c52016-10-07 19:25:10 +0000132 // Then, add the path notes if necessary.
Jordan Rose367843a2013-08-16 01:06:30 +0000133 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
Artem Dergachevb1991c52016-10-07 19:25:10 +0000134 for (const auto &Piece : FlatPath) {
135 if (isa<PathDiagnosticNotePiece>(Piece.get()))
136 continue;
137
138 SourceLocation NoteLoc = Piece->getLocation().asLocation();
139 Diag.Report(NoteLoc, NoteID) << Piece->getString()
140 << Piece->getRanges();
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000141 }
142 }
143 }
144};
145} // end anonymous namespace
146
Ted Kremenek04ade6f2009-07-27 22:13:39 +0000147//===----------------------------------------------------------------------===//
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000148// AnalysisConsumer declaration.
149//===----------------------------------------------------------------------===//
150
151namespace {
152
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000153class AnalysisConsumer : public AnalysisASTConsumer,
Richard Smith50668452015-11-24 03:55:01 +0000154 public RecursiveASTVisitor<AnalysisConsumer> {
Jordan Rosed8665b32012-10-10 17:55:40 +0000155 enum {
156 AM_None = 0,
157 AM_Syntax = 0x1,
158 AM_Path = 0x2
Anna Zaks14189512012-03-13 19:32:00 +0000159 };
Jordan Rosed8665b32012-10-10 17:55:40 +0000160 typedef unsigned AnalysisMode;
Anna Zaks14189512012-03-13 19:32:00 +0000161
162 /// Mode of the analyzes while recursively visiting Decls.
163 AnalysisMode RecVisitorMode;
164 /// Bug Reporter to use while recursively visiting Decls.
165 BugReporter *RecVisitorBR;
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;
David Blaikie53dd8fe2014-08-29 20:11:03 +0000296 checkerMgr = createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
297 PP.getDiagnostics());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000298
David Blaikie53dd8fe2014-08-29 20:11:03 +0000299 Mgr = llvm::make_unique<AnalysisManager>(
300 *Ctx, PP.getDiagnostics(), PP.getLangOpts(), PathConsumers,
301 CreateStoreMgr, 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 Zaks8e078522012-04-12 22:36:48 +0000334 void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
Anna Zaks5d484782012-12-07 21:51:47 +0000335 ExprEngine::InliningModes IMode,
Anna Zaks8e078522012-04-12 22:36:48 +0000336 SetOfConstDecls *VisitedCallees);
Anna Zaks14189512012-03-13 19:32:00 +0000337
338 /// Visitors for the RecursiveASTVisitor.
Anna Zakse7e7c9e2012-05-11 23:15:18 +0000339 bool shouldWalkTypesOfTypeLocs() const { return false; }
Anna Zaks14189512012-03-13 19:32:00 +0000340
341 /// Handle callbacks for arbitrary Decls.
342 bool VisitDecl(Decl *D) {
Jordan Rosed8665b32012-10-10 17:55:40 +0000343 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
344 if (Mode & AM_Syntax)
345 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
Anna Zaks14189512012-03-13 19:32:00 +0000346 return true;
347 }
348
349 bool VisitFunctionDecl(FunctionDecl *FD) {
350 IdentifierInfo *II = FD->getIdentifier();
351 if (II && II->getName().startswith("__inline"))
352 return true;
353
354 // We skip function template definitions, as their semantics is
355 // only determined when they are instantiated.
356 if (FD->isThisDeclarationADefinition() &&
357 !FD->isDependentContext()) {
Anna Zaks5d484782012-12-07 21:51:47 +0000358 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Anna Zaks14189512012-03-13 19:32:00 +0000359 HandleCode(FD, RecVisitorMode);
360 }
361 return true;
362 }
363
364 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
Anna Zaks5d484782012-12-07 21:51:47 +0000365 if (MD->isThisDeclarationADefinition()) {
366 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Anna Zaks14189512012-03-13 19:32:00 +0000367 HandleCode(MD, RecVisitorMode);
Anna Zaks5d484782012-12-07 21:51:47 +0000368 }
Anna Zaks14189512012-03-13 19:32:00 +0000369 return true;
370 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000371
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000372 bool VisitBlockDecl(BlockDecl *BD) {
373 if (BD->hasBody()) {
374 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Devin Coughlin6e644ab2015-11-18 22:46:52 +0000375 // Since we skip function template definitions, we should skip blocks
376 // declared in those functions as well.
377 if (!BD->isDependentContext()) {
378 HandleCode(BD, RecVisitorMode);
379 }
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000380 }
381 return true;
382 }
Anna Zaks8e078522012-04-12 22:36:48 +0000383
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000384 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000385 PathConsumers.push_back(Consumer);
386 }
387
Anna Zaks8e078522012-04-12 22:36:48 +0000388private:
389 void storeTopLevelDecls(DeclGroupRef DG);
Artem Dergachev6a76a162016-08-08 16:01:02 +0000390 std::string getFunctionName(const Decl *D);
Anna Zaks8e078522012-04-12 22:36:48 +0000391
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000392 /// Check if we should skip (not analyze) the given function.
Jordan Rosed8665b32012-10-10 17:55:40 +0000393 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000394 void runAnalysisOnTranslationUnit(ASTContext &C);
Anna Zaks8e078522012-04-12 22:36:48 +0000395
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000396 /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
397 void reportAnalyzerProgress(StringRef S);
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000398};
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000399} // end anonymous namespace
400
Anna Zaks14189512012-03-13 19:32:00 +0000401
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000402//===----------------------------------------------------------------------===//
403// AnalysisConsumer implementation.
404//===----------------------------------------------------------------------===//
Anna Zaks8e078522012-04-12 22:36:48 +0000405bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
406 storeTopLevelDecls(DG);
407 return true;
408}
409
410void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
411 storeTopLevelDecls(DG);
412}
413
414void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
415 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
416
417 // Skip ObjCMethodDecl, wait for the objc container to avoid
418 // analyzing twice.
419 if (isa<ObjCMethodDecl>(*I))
420 continue;
421
Ted Kremenek2964aac2012-04-27 04:54:28 +0000422 LocalTUDecls.push_back(*I);
Anna Zaks8e078522012-04-12 22:36:48 +0000423 }
424}
425
Anna Zaks5f2af812012-12-14 19:08:17 +0000426static bool shouldSkipFunction(const Decl *D,
Alexander Kornienkofe659982014-04-23 16:39:41 +0000427 const SetOfConstDecls &Visited,
428 const SetOfConstDecls &VisitedAsTopLevel) {
Anna Zaks5f2af812012-12-14 19:08:17 +0000429 if (VisitedAsTopLevel.count(D))
Anna Zaks5d484782012-12-07 21:51:47 +0000430 return true;
431
432 // We want to re-analyse the functions as top level in the following cases:
Anna Zaksa8017ec2012-08-30 23:42:02 +0000433 // - The 'init' methods should be reanalyzed because
434 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
Anna Zaks5d484782012-12-07 21:51:47 +0000435 // 'nil' and unless we analyze the 'init' functions as top level, we will
436 // not catch errors within defensive code.
Anna Zaksa8017ec2012-08-30 23:42:02 +0000437 // - We want to reanalyze all ObjC methods as top level to report Retain
438 // Count naming convention errors more aggressively.
Anna Zaks5f2af812012-12-14 19:08:17 +0000439 if (isa<ObjCMethodDecl>(D))
Anna Zaksa8017ec2012-08-30 23:42:02 +0000440 return false;
Devin Coughlinf57f90d2016-07-21 23:42:31 +0000441 // We also want to reanalyze all C++ copy and move assignment operators to
442 // separately check the two cases where 'this' aliases with the parameter and
443 // where it may not. (cplusplus.SelfAssignmentChecker)
444 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
445 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
446 return false;
447 }
Anna Zaksa8017ec2012-08-30 23:42:02 +0000448
449 // Otherwise, if we visited the function before, do not reanalyze it.
Anna Zaks5f2af812012-12-14 19:08:17 +0000450 return Visited.count(D);
Anna Zaksa8017ec2012-08-30 23:42:02 +0000451}
452
Anna Zaks5d484782012-12-07 21:51:47 +0000453ExprEngine::InliningModes
Anna Zaks5f2af812012-12-14 19:08:17 +0000454AnalysisConsumer::getInliningModeForFunction(const Decl *D,
Alexander Kornienkofe659982014-04-23 16:39:41 +0000455 const SetOfConstDecls &Visited) {
Anna Zaks5d484782012-12-07 21:51:47 +0000456 // We want to reanalyze all ObjC methods as top level to report Retain
Anna Zaksb13d21b2013-03-26 18:57:58 +0000457 // Count naming convention errors more aggressively. But we should tune down
Anna Zaks5d484782012-12-07 21:51:47 +0000458 // inlining when reanalyzing an already inlined function.
Devin Coughlinf57f90d2016-07-21 23:42:31 +0000459 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
Anna Zaks5f2af812012-12-14 19:08:17 +0000460 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
Anna Zaks5d484782012-12-07 21:51:47 +0000461 if (ObjCM->getMethodFamily() != OMF_init)
Anna Zaksb13d21b2013-03-26 18:57:58 +0000462 return ExprEngine::Inline_Minimal;
Anna Zaks5d484782012-12-07 21:51:47 +0000463 }
464
Anna Zaksb13d21b2013-03-26 18:57:58 +0000465 return ExprEngine::Inline_Regular;
Anna Zaks5d484782012-12-07 21:51:47 +0000466}
467
Jordan Rose85c8c812012-10-10 17:55:37 +0000468void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
Anna Zaks1ee76c12012-12-21 17:27:01 +0000469 // Build the Call Graph by adding all the top level declarations to the graph.
Anna Zaks2774f992012-05-31 18:07:55 +0000470 // Note: CallGraph can trigger deserialization of more items from a pch
471 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
472 // We rely on random access to add the initially processed Decls to CG.
Anna Zaks1ee76c12012-12-21 17:27:01 +0000473 CallGraph CG;
Anna Zaks2774f992012-05-31 18:07:55 +0000474 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
Anna Zaks34d89b72012-05-30 23:14:48 +0000475 CG.addToCallGraph(LocalTUDecls[i]);
476 }
Anna Zakseee91102012-03-08 23:16:38 +0000477
Anna Zaks1ee76c12012-12-21 17:27:01 +0000478 // Walk over all of the call graph nodes in topological order, so that we
479 // analyze parents before the children. Skip the functions inlined into
480 // the previously processed functions. Use external Visited set to identify
481 // inlined functions. The topological order allows the "do not reanalyze
482 // previously inlined function" performance heuristic to be triggered more
483 // often.
Anna Zaks5f2af812012-12-14 19:08:17 +0000484 SetOfConstDecls Visited;
485 SetOfConstDecls VisitedAsTopLevel;
Anna Zaks1ee76c12012-12-21 17:27:01 +0000486 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
487 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
488 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
489 NumFunctionTopLevel++;
Anna Zaksca70ed52012-03-13 19:32:13 +0000490
Anna Zaks1ee76c12012-12-21 17:27:01 +0000491 CallGraphNode *N = *I;
Anna Zaks5f2af812012-12-14 19:08:17 +0000492 Decl *D = N->getDecl();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000493
Anna Zaks1ee76c12012-12-21 17:27:01 +0000494 // Skip the abstract root node.
495 if (!D)
496 continue;
Anna Zaks5f2af812012-12-14 19:08:17 +0000497
Anna Zaksca70ed52012-03-13 19:32:13 +0000498 // Skip the functions which have been processed already or previously
499 // inlined.
Anna Zaks5f2af812012-12-14 19:08:17 +0000500 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
Anna Zaksca70ed52012-03-13 19:32:13 +0000501 continue;
502
503 // Analyze the function.
Anna Zaks8e078522012-04-12 22:36:48 +0000504 SetOfConstDecls VisitedCallees;
Anna Zaks5d484782012-12-07 21:51:47 +0000505
Anna Zaks5f2af812012-12-14 19:08:17 +0000506 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
Craig Topper0dbb7832014-05-27 02:45:47 +0000507 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
Anna Zaksca70ed52012-03-13 19:32:13 +0000508
509 // Add the visited callees to the global visited set.
Yury Gribov054873b2016-01-11 09:38:48 +0000510 for (const Decl *Callee : VisitedCallees)
511 // Decls from CallGraph are already canonical. But Decls coming from
512 // CallExprs may be not. We should canonicalize them manually.
513 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
514 : Callee->getCanonicalDecl());
Anna Zaks5f2af812012-12-14 19:08:17 +0000515 VisitedAsTopLevel.insert(D);
Anna Zakseee91102012-03-08 23:16:38 +0000516 }
Ted Kremenek60120fb2011-08-27 21:28:09 +0000517}
518
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000519static bool isBisonFile(ASTContext &C) {
520 const SourceManager &SM = C.getSourceManager();
521 FileID FID = SM.getMainFileID();
522 StringRef Buffer = SM.getBuffer(FID)->getBuffer();
523 if (Buffer.startswith("/* A Bison parser, made by"))
524 return true;
525 return false;
526}
527
528void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
529 BugReporter BR(*Mgr);
530 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
531 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
532
533 // Run the AST-only checks using the order in which functions are defined.
534 // If inlining is not turned on, use the simplest function order for path
535 // sensitive analyzes as well.
536 RecVisitorMode = AM_Syntax;
537 if (!Mgr->shouldInlineCall())
538 RecVisitorMode |= AM_Path;
539 RecVisitorBR = &BR;
540
541 // Process all the top level declarations.
542 //
543 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
544 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
545 // random access. By doing so, we automatically compensate for iterators
546 // possibly being invalidated, although this is a bit slower.
547 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
548 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
549 TraverseDecl(LocalTUDecls[i]);
550 }
551
552 if (Mgr->shouldInlineCall())
553 HandleDeclsCallGraph(LocalTUDeclsSize);
554
555 // After all decls handled, run checkers on the entire TranslationUnit.
556 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
557
558 RecVisitorBR = nullptr;
559}
560
561void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
562 if (Opts->AnalyzerDisplayProgress)
563 llvm::errs() << S;
564}
565
Ted Kremeneka1ec4f32011-01-20 17:09:48 +0000566void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000567
Anna Zaks14189512012-03-13 19:32:00 +0000568 // Don't run the actions if an error has occurred with parsing the file.
569 DiagnosticsEngine &Diags = PP.getDiagnostics();
570 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
571 return;
572
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000573 if (TUTotalTimer) TUTotalTimer->startTimer();
Anna Zaksd5478fd2014-08-29 20:01:38 +0000574
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000575 if (isBisonFile(C)) {
576 reportAnalyzerProgress("Skipping bison-generated file\n");
577 } else if (Opts->DisableAllChecks) {
Anna Zaks9bd4be92012-03-05 20:53:59 +0000578
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000579 // Don't analyze if the user explicitly asked for no checks to be performed
580 // on this file.
581 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
582 } else {
583 // Otherwise, just run the analysis.
584 runAnalysisOnTranslationUnit(C);
Anna Zaks17f57b02012-01-07 16:49:46 +0000585 }
Ted Kremeneke69ab052011-05-05 03:41:17 +0000586
Anna Zaks9bd4be92012-03-05 20:53:59 +0000587 if (TUTotalTimer) TUTotalTimer->stopTimer();
Anna Zaks8382e452012-04-05 02:10:21 +0000588
589 // Count how many basic blocks we have not covered.
590 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
George Karpenkov2a639852018-02-09 23:37:47 +0000591 NumVisitedBlocksInAnalyzedFunctions =
592 FunctionSummaries.getTotalNumVisitedBasicBlocks();
Anna Zaks8382e452012-04-05 02:10:21 +0000593 if (NumBlocksInAnalyzedFunctions > 0)
594 PercentReachableBlocks =
595 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
596 NumBlocksInAnalyzedFunctions;
597
George Karpenkov5a755b32018-02-10 01:49:20 +0000598 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
599 // FIXME: This should be replaced with something that doesn't rely on
600 // side-effects in PathDiagnosticConsumer's destructor. This is required when
601 // used with option -disable-free.
602 Mgr.reset();
Ted Kremenek0e7d2522008-07-03 04:29:21 +0000603}
604
Artem Dergachev6a76a162016-08-08 16:01:02 +0000605std::string AnalysisConsumer::getFunctionName(const Decl *D) {
606 std::string Str;
607 llvm::raw_string_ostream OS(Str);
608
609 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
610 OS << FD->getQualifiedNameAsString();
611
612 // In C++, there are overloads.
613 if (Ctx->getLangOpts().CPlusPlus) {
614 OS << '(';
615 for (const auto &P : FD->parameters()) {
616 if (P != *FD->param_begin())
617 OS << ", ";
618 OS << P->getType().getAsString();
619 }
620 OS << ')';
621 }
622
623 } else if (isa<BlockDecl>(D)) {
624 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
625
626 if (Loc.isValid()) {
627 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
628 << ')';
629 }
630
631 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
632
633 // FIXME: copy-pasted from CGDebugInfo.cpp.
634 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
635 const DeclContext *DC = OMD->getDeclContext();
636 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
637 OS << OID->getName();
638 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
639 OS << OID->getName();
640 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
641 if (OC->IsClassExtension()) {
642 OS << OC->getClassInterface()->getName();
643 } else {
644 OS << OC->getIdentifier()->getNameStart() << '('
645 << OC->getIdentifier()->getNameStart() << ')';
646 }
647 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +0000648 OS << OCD->getClassInterface()->getName() << '('
649 << OCD->getName() << ')';
Artem Dergachev6a76a162016-08-08 16:01:02 +0000650 } else if (isa<ObjCProtocolDecl>(DC)) {
651 // We can extract the type of the class from the self pointer.
652 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
653 QualType ClassTy =
654 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
655 ClassTy.print(OS, PrintingPolicy(LangOptions()));
656 }
657 }
658 OS << ' ' << OMD->getSelector().getAsString() << ']';
659
Anna Zakseee91102012-03-08 23:16:38 +0000660 }
Artem Dergachev6a76a162016-08-08 16:01:02 +0000661
662 return OS.str();
Anna Zakseee91102012-03-08 23:16:38 +0000663}
664
Jordan Rosed8665b32012-10-10 17:55:40 +0000665AnalysisConsumer::AnalysisMode
666AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000667 if (!Opts->AnalyzeSpecificFunction.empty() &&
668 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
Jordan Rosed8665b32012-10-10 17:55:40 +0000669 return AM_None;
Mike Stump11289f42009-09-09 15:08:12 +0000670
Jordan Rosed8665b32012-10-10 17:55:40 +0000671 // Unless -analyze-all is specified, treat decls differently depending on
672 // where they came from:
673 // - Main source file: run both path-sensitive and non-path-sensitive checks.
674 // - Header files: run non-path-sensitive checks only.
675 // - System headers: don't run any checks.
Ted Kremenek4c721bf2010-06-15 00:55:40 +0000676 SourceManager &SM = Ctx->getSourceManager();
Aaron Ballman65693872015-08-20 21:27:35 +0000677 const Stmt *Body = D->getBody();
678 SourceLocation SL = Body ? Body->getLocStart() : D->getLocation();
Anna Zaks3849dea2015-06-26 17:42:58 +0000679 SL = SM.getExpansionLoc(SL);
680
Artem Dergachev516837f2018-04-25 21:51:26 +0000681 if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
Jordan Rosed8665b32012-10-10 17:55:40 +0000682 if (SL.isInvalid() || SM.isInSystemHeader(SL))
683 return AM_None;
684 return Mode & ~AM_Path;
685 }
Anna Zaksaa19abe2012-03-13 19:31:54 +0000686
Jordan Rosed8665b32012-10-10 17:55:40 +0000687 return Mode;
Anna Zaksaa19abe2012-03-13 19:31:54 +0000688}
689
Anna Zaks14189512012-03-13 19:32:00 +0000690void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
Anna Zaks5d484782012-12-07 21:51:47 +0000691 ExprEngine::InliningModes IMode,
Anna Zaks8e078522012-04-12 22:36:48 +0000692 SetOfConstDecls *VisitedCallees) {
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000693 if (!D->hasBody())
694 return;
Jordan Rosed8665b32012-10-10 17:55:40 +0000695 Mode = getModeForDecl(D, Mode);
696 if (Mode == AM_None)
Mike Stump11289f42009-09-09 15:08:12 +0000697 return;
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000698
Alexander Shaposhnikova1fead22016-09-23 20:49:01 +0000699 // Clear the AnalysisManager of old AnalysisDeclContexts.
700 Mgr->ClearContexts();
701 // Ignore autosynthesized code.
702 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
703 return;
704
Anna Zakse9eb13a2013-02-02 00:30:02 +0000705 DisplayFunction(D, Mode, IMode);
Anna Zaks40b87fc2012-07-05 20:44:02 +0000706 CFG *DeclCFG = Mgr->getCFG(D);
Craig Topper704b4fb2017-05-18 01:11:52 +0000707 if (DeclCFG)
708 MaxCFGSize.updateMax(DeclCFG->size());
Anna Zaks40b87fc2012-07-05 20:44:02 +0000709
Argyrios Kyrtzidis24ffc082011-02-17 21:39:24 +0000710 BugReporter BR(*Mgr);
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000711
712 if (Mode & AM_Syntax)
713 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
714 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
715 RunPathSensitiveChecks(D, IMode, VisitedCallees);
Anna Zaksb13d21b2013-03-26 18:57:58 +0000716 if (IMode != ExprEngine::Inline_Minimal)
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000717 NumFunctionsAnalyzed++;
718 }
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000719}
720
721//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6a1c7602011-02-28 19:49:17 +0000722// Path-sensitive checking.
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000723//===----------------------------------------------------------------------===//
724
Anna Zaks394d07e2012-03-09 21:14:01 +0000725void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
Anna Zaks5d484782012-12-07 21:51:47 +0000726 ExprEngine::InliningModes IMode,
Anna Zaks8e078522012-04-12 22:36:48 +0000727 SetOfConstDecls *VisitedCallees) {
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000728 // Construct the analysis engine. First check if the CFG is valid.
Ted Kremenek1e7f9882009-09-18 22:29:35 +0000729 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
Anna Zaks394d07e2012-03-09 21:14:01 +0000730 if (!Mgr->getCFG(D))
Ted Kremenek39df94b2010-02-14 19:08:51 +0000731 return;
Anna Zaks394d07e2012-03-09 21:14:01 +0000732
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000733 // See if the LiveVariables analysis scales.
734 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
735 return;
736
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000737 ExprEngine Eng(CTU, *Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,
738 IMode);
Ted Kremenek39df94b2010-02-14 19:08:51 +0000739
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000740 // Set the graph auditor.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000741 std::unique_ptr<ExplodedNode::Auditor> Auditor;
Ted Kremenekb8f8b352012-08-30 19:26:53 +0000742 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
David Blaikiea48a53c2014-09-05 00:14:57 +0000743 Auditor = CreateUbiViz();
Zhongxing Xu20227f72009-08-06 01:32:16 +0000744 ExplodedNode::SetAuditor(Auditor.get());
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000745 }
Mike Stump11289f42009-09-09 15:08:12 +0000746
Ted Kremenek8e631a02008-07-02 00:44:58 +0000747 // Execute the worklist algorithm.
Jordy Rose4f8198e2012-04-28 01:58:08 +0000748 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
Anna Zaksc84d1512013-01-30 19:12:39 +0000749 Mgr->options.getMaxNodesPerTopLevelFunction());
Mike Stump11289f42009-09-09 15:08:12 +0000750
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000751 // Release the auditor (if any) so that it doesn't monitor the graph
752 // created BugReporter.
Craig Topper0dbb7832014-05-27 02:45:47 +0000753 ExplodedNode::SetAuditor(nullptr);
Ted Kremenek39df18f2009-03-11 01:42:29 +0000754
Ted Kremenek71ac8322008-07-02 16:49:11 +0000755 // Visualize the exploded graph.
Ted Kremenekb8f8b352012-08-30 19:26:53 +0000756 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
Ted Kremenek8756c4a2012-08-30 19:26:43 +0000757 Eng.ViewGraph(Mgr->options.TrimGraph);
Mike Stump11289f42009-09-09 15:08:12 +0000758
Ted Kremenek39df18f2009-03-11 01:42:29 +0000759 // Display warnings.
760 Eng.getBugReporter().FlushReports();
Ted Kremenekbecec2c2008-07-02 16:35:50 +0000761}
762
Anna Zaks8e078522012-04-12 22:36:48 +0000763void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
Anna Zaks5d484782012-12-07 21:51:47 +0000764 ExprEngine::InliningModes IMode,
Anna Zaks8e078522012-04-12 22:36:48 +0000765 SetOfConstDecls *Visited) {
Mike Stump11289f42009-09-09 15:08:12 +0000766
David Blaikiebbafb8a2012-03-11 07:00:24 +0000767 switch (Mgr->getLangOpts().getGC()) {
Jordy Rosec49ec532011-09-02 05:55:19 +0000768 case LangOptions::NonGC:
Anna Zaks5d484782012-12-07 21:51:47 +0000769 ActionExprEngine(D, false, IMode, Visited);
Jordy Rosec49ec532011-09-02 05:55:19 +0000770 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000771
Jordy Rosec49ec532011-09-02 05:55:19 +0000772 case LangOptions::GCOnly:
Anna Zaks5d484782012-12-07 21:51:47 +0000773 ActionExprEngine(D, true, IMode, Visited);
Jordy Rosec49ec532011-09-02 05:55:19 +0000774 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000775
Jordy Rosec49ec532011-09-02 05:55:19 +0000776 case LangOptions::HybridGC:
Anna Zaks5d484782012-12-07 21:51:47 +0000777 ActionExprEngine(D, false, IMode, Visited);
778 ActionExprEngine(D, true, IMode, Visited);
Jordy Rosec49ec532011-09-02 05:55:19 +0000779 break;
780 }
Ted Kremenek8e631a02008-07-02 00:44:58 +0000781}
782
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000783//===----------------------------------------------------------------------===//
784// AnalysisConsumer creation.
785//===----------------------------------------------------------------------===//
786
David Blaikie6beb6aa2014-08-10 19:56:51 +0000787std::unique_ptr<AnalysisASTConsumer>
Ted Kremenekeeccb302014-08-27 15:14:15 +0000788ento::CreateAnalysisConsumer(CompilerInstance &CI) {
Jordy Rose59cce712011-08-16 21:24:21 +0000789 // Disable the effects of '-Werror' when using the AnalysisConsumer.
Ted Kremenekeeccb302014-08-27 15:14:15 +0000790 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
Ted Kremenekb5351812009-02-17 04:27:41 +0000791
Ted Kremenekeeccb302014-08-27 15:14:15 +0000792 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
793 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
794
795 return llvm::make_unique<AnalysisConsumer>(
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000796 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
Ted Kremenekeeccb302014-08-27 15:14:15 +0000797 CI.getFrontendOpts().Plugins,
798 hasModelPath ? new ModelInjector(CI) : nullptr);
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000799}
800
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000801//===----------------------------------------------------------------------===//
802// Ubigraph Visualization. FIXME: Move to separate file.
803//===----------------------------------------------------------------------===//
804
805namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000806
Zhongxing Xu20227f72009-08-06 01:32:16 +0000807class UbigraphViz : public ExplodedNode::Auditor {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000808 std::unique_ptr<raw_ostream> Out;
Rafael Espindola32e3e7c2013-06-26 14:33:23 +0000809 std::string Filename;
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000810 unsigned Cntr;
811
812 typedef llvm::DenseMap<void*,unsigned> VMap;
813 VMap M;
Mike Stump11289f42009-09-09 15:08:12 +0000814
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000815public:
David Blaikie3875a822014-07-19 01:06:45 +0000816 UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000818 ~UbigraphViz() override;
Mike Stump11289f42009-09-09 15:08:12 +0000819
Craig Topperfb6b25b2014-03-15 04:29:04 +0000820 void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) override;
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000821};
Mike Stump11289f42009-09-09 15:08:12 +0000822
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000823} // end anonymous namespace
824
David Blaikiea48a53c2014-09-05 00:14:57 +0000825static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz() {
Rafael Espindola4168ee72013-06-26 06:13:06 +0000826 SmallString<128> P;
827 int FD;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +0000828 llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P);
Yaron Keren09fb7c62015-03-10 07:33:23 +0000829 llvm::errs() << "Writing '" << P << "'.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000830
David Blaikie3875a822014-07-19 01:06:45 +0000831 auto Stream = llvm::make_unique<llvm::raw_fd_ostream>(FD, true);
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000832
David Blaikiea48a53c2014-09-05 00:14:57 +0000833 return llvm::make_unique<UbigraphViz>(std::move(Stream), P);
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000834}
835
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000836void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
Mike Stump11289f42009-09-09 15:08:12 +0000837
Ted Kremenek2eb49f22008-08-28 18:34:41 +0000838 assert (Src != Dst && "Self-edges are not allowed.");
Mike Stump11289f42009-09-09 15:08:12 +0000839
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000840 // Lookup the Src. If it is a new node, it's a root.
841 VMap::iterator SrcI= M.find(Src);
842 unsigned SrcID;
Mike Stump11289f42009-09-09 15:08:12 +0000843
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000844 if (SrcI == M.end()) {
845 M[Src] = SrcID = Cntr++;
846 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
847 }
848 else
849 SrcID = SrcI->second;
Mike Stump11289f42009-09-09 15:08:12 +0000850
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000851 // Lookup the Dst.
852 VMap::iterator DstI= M.find(Dst);
853 unsigned DstID;
854
855 if (DstI == M.end()) {
856 M[Dst] = DstID = Cntr++;
857 *Out << "('vertex', " << DstID << ")\n";
858 }
Ted Kremenek803e7e12008-08-28 05:02:09 +0000859 else {
860 // We have hit DstID before. Change its style to reflect a cache hit.
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000861 DstID = DstI->second;
Ted Kremenek803e7e12008-08-28 05:02:09 +0000862 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
863 }
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000864
865 // Add the edge.
Mike Stump11289f42009-09-09 15:08:12 +0000866 *Out << "('edge', " << SrcID << ", " << DstID
Ted Kremenekc8288b42008-08-27 22:46:55 +0000867 << ", ('arrow','true'), ('oriented', 'true'))\n";
Ted Kremenekd461d7a2008-08-27 22:31:43 +0000868}
869
Ismail Pazarbasid347e7a2015-09-18 21:54:47 +0000870UbigraphViz::UbigraphViz(std::unique_ptr<raw_ostream> OutStream,
871 StringRef Filename)
872 : Out(std::move(OutStream)), Filename(Filename), Cntr(0) {
Ted Kremenek803e7e12008-08-28 05:02:09 +0000873
874 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
875 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
876 " ('size', '1.5'))\n";
877}
878
Ted Kremenek266ec3f2008-08-28 03:54:51 +0000879UbigraphViz::~UbigraphViz() {
David Blaikie3875a822014-07-19 01:06:45 +0000880 Out.reset();
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000881 llvm::errs() << "Running 'ubiviz' program... ";
Ted Kremenek266ec3f2008-08-28 03:54:51 +0000882 std::string ErrMsg;
Michael J. Spencer04162ea2014-11-04 01:30:55 +0000883 std::string Ubiviz;
884 if (auto Path = llvm::sys::findProgramByName("ubiviz"))
885 Ubiviz = *Path;
Fangrui Song8b4b82e2018-06-12 20:44:11 +0000886 std::array<StringRef, 2> Args{{Ubiviz, Filename}};
Mike Stump11289f42009-09-09 15:08:12 +0000887
Zachary Turner08426e12018-06-12 17:43:52 +0000888 if (llvm::sys::ExecuteAndWait(Ubiviz, Args, llvm::None, {}, 0, 0, &ErrMsg)) {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000889 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
Ted Kremenek266ec3f2008-08-28 03:54:51 +0000890 }
Mike Stump11289f42009-09-09 15:08:12 +0000891
Rafael Espindola32e3e7c2013-06-26 14:33:23 +0000892 // Delete the file.
893 llvm::sys::fs::remove(Filename);
Daniel Dunbar9a0ea042008-08-29 03:45:59 +0000894}