blob: ef2cf36f3ca47123f06eb8928c459ec9b6a8a836 [file] [log] [blame]
Ted Kremeneka0a5ca12011-03-15 03:17:07 +00001//==- UninitializedValues.cpp - Find Uninitialized Values -------*- C++ --*-==//
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002//
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// This file implements uninitialized values analysis for source-level CFGs.
11//
12//===----------------------------------------------------------------------===//
13
Richard Smith130b8d42012-07-13 23:33:44 +000014#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000015#include "clang/AST/Attr.h"
Ted Kremenekb749a6d2011-01-15 02:58:47 +000016#include "clang/AST/Decl.h"
Jordan Rosea7f94ce2013-05-15 23:22:55 +000017#include "clang/AST/StmtVisitor.h"
Artyom Skrobov12ce6d92014-07-28 08:47:38 +000018#include "clang/Analysis/Analyses/DataflowWorklist.h"
Ted Kremeneka0a5ca12011-03-15 03:17:07 +000019#include "clang/Analysis/Analyses/UninitializedValues.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/Analysis/AnalysisContext.h"
21#include "clang/Analysis/CFG.h"
Ted Kremenekedf22ed2012-09-13 00:21:35 +000022#include "clang/Analysis/DomainSpecific/ObjCNoReturn.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/PackedVector.h"
26#include "llvm/ADT/SmallBitVector.h"
27#include "llvm/ADT/SmallVector.h"
Argyrios Kyrtzidis981a9612012-03-01 19:45:56 +000028#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include <utility>
Ted Kremenekb749a6d2011-01-15 02:58:47 +000030
31using namespace clang;
32
Richard Smith130b8d42012-07-13 23:33:44 +000033#define DEBUG_LOGGING 0
34
Ted Kremenek93a31382011-01-27 02:29:34 +000035static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) {
Ted Kremenekc15a4e42011-03-17 03:06:11 +000036 if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() &&
Richard Smithd88b44d2014-06-11 00:31:00 +000037 !vd->isExceptionVariable() && !vd->isInitCapture() &&
Ted Kremenekc15a4e42011-03-17 03:06:11 +000038 vd->getDeclContext() == dc) {
39 QualType ty = vd->getType();
40 return ty->isScalarType() || ty->isVectorType();
41 }
42 return false;
Ted Kremenekcab479f2011-01-18 04:53:25 +000043}
44
Ted Kremenekb749a6d2011-01-15 02:58:47 +000045//------------------------------------------------------------------------====//
Ted Kremeneka895fe92011-03-15 04:57:27 +000046// DeclToIndex: a mapping from Decls we track to value indices.
Ted Kremenekb749a6d2011-01-15 02:58:47 +000047//====------------------------------------------------------------------------//
48
49namespace {
Ted Kremeneka895fe92011-03-15 04:57:27 +000050class DeclToIndex {
Ted Kremenekb749a6d2011-01-15 02:58:47 +000051 llvm::DenseMap<const VarDecl *, unsigned> map;
52public:
Ted Kremeneka895fe92011-03-15 04:57:27 +000053 DeclToIndex() {}
Ted Kremenekb749a6d2011-01-15 02:58:47 +000054
55 /// Compute the actual mapping from declarations to bits.
56 void computeMap(const DeclContext &dc);
57
58 /// Return the number of declarations in the map.
59 unsigned size() const { return map.size(); }
60
61 /// Returns the bit vector index for a given declaration.
David Blaikie05785d12013-02-20 22:23:23 +000062 Optional<unsigned> getValueIndex(const VarDecl *d) const;
Ted Kremenekb749a6d2011-01-15 02:58:47 +000063};
64}
65
Ted Kremeneka895fe92011-03-15 04:57:27 +000066void DeclToIndex::computeMap(const DeclContext &dc) {
Ted Kremenekb749a6d2011-01-15 02:58:47 +000067 unsigned count = 0;
68 DeclContext::specific_decl_iterator<VarDecl> I(dc.decls_begin()),
69 E(dc.decls_end());
70 for ( ; I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +000071 const VarDecl *vd = *I;
Ted Kremenek93a31382011-01-27 02:29:34 +000072 if (isTrackedVar(vd, &dc))
Ted Kremenekb749a6d2011-01-15 02:58:47 +000073 map[vd] = count++;
74 }
75}
76
David Blaikie05785d12013-02-20 22:23:23 +000077Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const {
Ted Kremenek03325c42011-03-29 01:40:00 +000078 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d);
Ted Kremenekb749a6d2011-01-15 02:58:47 +000079 if (I == map.end())
David Blaikie7a30dc52013-02-21 01:47:18 +000080 return None;
Ted Kremenekb749a6d2011-01-15 02:58:47 +000081 return I->second;
82}
83
84//------------------------------------------------------------------------====//
85// CFGBlockValues: dataflow values for CFG blocks.
86//====------------------------------------------------------------------------//
87
Ted Kremenekc8c4e5f2011-03-15 04:57:38 +000088// These values are defined in such a way that a merge can be done using
89// a bitwise OR.
90enum Value { Unknown = 0x0, /* 00 */
91 Initialized = 0x1, /* 01 */
92 Uninitialized = 0x2, /* 10 */
93 MayUninitialized = 0x3 /* 11 */ };
94
95static bool isUninitialized(const Value v) {
96 return v >= Uninitialized;
97}
98static bool isAlwaysUninit(const Value v) {
99 return v == Uninitialized;
100}
Ted Kremenekd3def382011-03-15 04:57:29 +0000101
Benjamin Kramer8aef5962011-03-26 12:38:21 +0000102namespace {
Ted Kremenek9b15c962011-03-15 04:57:32 +0000103
Benjamin Kramer5721daa2012-09-28 16:44:29 +0000104typedef llvm::PackedVector<Value, 2, llvm::SmallBitVector> ValueVector;
Ted Kremenekb82ddd62011-01-20 17:37:17 +0000105
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000106class CFGBlockValues {
107 const CFG &cfg;
Benjamin Kramer5721daa2012-09-28 16:44:29 +0000108 SmallVector<ValueVector, 8> vals;
Ted Kremeneka895fe92011-03-15 04:57:27 +0000109 ValueVector scratch;
Ted Kremeneke3ae0a42011-03-15 05:30:12 +0000110 DeclToIndex declToIndex;
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000111public:
112 CFGBlockValues(const CFG &cfg);
Ted Kremenek6080d322012-07-19 04:59:05 +0000113
Ted Kremenek37881932011-04-04 23:29:12 +0000114 unsigned getNumEntries() const { return declToIndex.size(); }
115
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000116 void computeSetOfDeclarations(const DeclContext &dc);
Ted Kremenek6080d322012-07-19 04:59:05 +0000117 ValueVector &getValueVector(const CFGBlock *block) {
Benjamin Kramer5721daa2012-09-28 16:44:29 +0000118 return vals[block->getBlockID()];
Ted Kremenek6080d322012-07-19 04:59:05 +0000119 }
Ted Kremenekb82ddd62011-01-20 17:37:17 +0000120
Richard Smithb721e302012-07-02 23:23:04 +0000121 void setAllScratchValues(Value V);
Ted Kremeneka895fe92011-03-15 04:57:27 +0000122 void mergeIntoScratch(ValueVector const &source, bool isFirst);
123 bool updateValueVectorWithScratch(const CFGBlock *block);
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000124
125 bool hasNoDeclarations() const {
Ted Kremeneke3ae0a42011-03-15 05:30:12 +0000126 return declToIndex.size() == 0;
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000127 }
Ted Kremenek417d5662011-08-20 01:15:28 +0000128
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000129 void resetScratch();
Ted Kremenekb82ddd62011-01-20 17:37:17 +0000130
Ted Kremeneka895fe92011-03-15 04:57:27 +0000131 ValueVector::reference operator[](const VarDecl *vd);
Richard Smith4323bf82012-05-25 02:17:09 +0000132
133 Value getValue(const CFGBlock *block, const CFGBlock *dstBlock,
134 const VarDecl *vd) {
David Blaikie05785d12013-02-20 22:23:23 +0000135 const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
Richard Smith4323bf82012-05-25 02:17:09 +0000136 assert(idx.hasValue());
Ted Kremenek6080d322012-07-19 04:59:05 +0000137 return getValueVector(block)[idx.getValue()];
Richard Smith4323bf82012-05-25 02:17:09 +0000138 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000139};
Benjamin Kramer8aef5962011-03-26 12:38:21 +0000140} // end anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000141
Ted Kremenek6080d322012-07-19 04:59:05 +0000142CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {}
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000143
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000144void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
Ted Kremeneke3ae0a42011-03-15 05:30:12 +0000145 declToIndex.computeMap(dc);
Ted Kremenek6080d322012-07-19 04:59:05 +0000146 unsigned decls = declToIndex.size();
147 scratch.resize(decls);
148 unsigned n = cfg.getNumBlockIDs();
149 if (!n)
150 return;
151 vals.resize(n);
152 for (unsigned i = 0; i < n; ++i)
Benjamin Kramer5721daa2012-09-28 16:44:29 +0000153 vals[i].resize(decls);
Ted Kremenekb82ddd62011-01-20 17:37:17 +0000154}
155
Richard Smith130b8d42012-07-13 23:33:44 +0000156#if DEBUG_LOGGING
Ted Kremeneka895fe92011-03-15 04:57:27 +0000157static void printVector(const CFGBlock *block, ValueVector &bv,
Ted Kremenekba357292011-02-01 17:43:18 +0000158 unsigned num) {
Ted Kremenekba357292011-02-01 17:43:18 +0000159 llvm::errs() << block->getBlockID() << " :";
160 for (unsigned i = 0; i < bv.size(); ++i) {
161 llvm::errs() << ' ' << bv[i];
162 }
163 llvm::errs() << " : " << num << '\n';
164}
165#endif
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000166
Richard Smithb721e302012-07-02 23:23:04 +0000167void CFGBlockValues::setAllScratchValues(Value V) {
168 for (unsigned I = 0, E = scratch.size(); I != E; ++I)
169 scratch[I] = V;
170}
171
Ted Kremenekf8fd4d42011-10-07 00:42:48 +0000172void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
173 bool isFirst) {
174 if (isFirst)
175 scratch = source;
176 else
177 scratch |= source;
178}
179
Ted Kremeneka895fe92011-03-15 04:57:27 +0000180bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
Ted Kremenek6080d322012-07-19 04:59:05 +0000181 ValueVector &dst = getValueVector(block);
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000182 bool changed = (dst != scratch);
183 if (changed)
184 dst = scratch;
Richard Smith130b8d42012-07-13 23:33:44 +0000185#if DEBUG_LOGGING
Ted Kremenekba357292011-02-01 17:43:18 +0000186 printVector(block, scratch, 0);
187#endif
Ted Kremenekb82ddd62011-01-20 17:37:17 +0000188 return changed;
189}
190
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000191void CFGBlockValues::resetScratch() {
192 scratch.reset();
193}
194
Ted Kremeneka895fe92011-03-15 04:57:27 +0000195ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
David Blaikie05785d12013-02-20 22:23:23 +0000196 const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000197 assert(idx.hasValue());
198 return scratch[idx.getValue()];
199}
200
201//------------------------------------------------------------------------====//
Richard Smith6376d1f2012-07-17 00:06:14 +0000202// Classification of DeclRefExprs as use or initialization.
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000203//====------------------------------------------------------------------------//
204
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000205namespace {
206class FindVarResult {
207 const VarDecl *vd;
208 const DeclRefExpr *dr;
209public:
Richard Smith6376d1f2012-07-17 00:06:14 +0000210 FindVarResult(const VarDecl *vd, const DeclRefExpr *dr) : vd(vd), dr(dr) {}
211
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000212 const DeclRefExpr *getDeclRefExpr() const { return dr; }
213 const VarDecl *getDecl() const { return vd; }
214};
Richard Smith6376d1f2012-07-17 00:06:14 +0000215
216static const Expr *stripCasts(ASTContext &C, const Expr *Ex) {
217 while (Ex) {
218 Ex = Ex->IgnoreParenNoopCasts(C);
219 if (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
220 if (CE->getCastKind() == CK_LValueBitCast) {
221 Ex = CE->getSubExpr();
222 continue;
223 }
224 }
225 break;
226 }
227 return Ex;
228}
229
230/// If E is an expression comprising a reference to a single variable, find that
231/// variable.
232static FindVarResult findVar(const Expr *E, const DeclContext *DC) {
233 if (const DeclRefExpr *DRE =
234 dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E)))
235 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
236 if (isTrackedVar(VD, DC))
237 return FindVarResult(VD, DRE);
Craig Topper25542942014-05-20 04:30:07 +0000238 return FindVarResult(nullptr, nullptr);
Richard Smith6376d1f2012-07-17 00:06:14 +0000239}
240
241/// \brief Classify each DeclRefExpr as an initialization or a use. Any
242/// DeclRefExpr which isn't explicitly classified will be assumed to have
243/// escaped the analysis and will be treated as an initialization.
244class ClassifyRefs : public StmtVisitor<ClassifyRefs> {
245public:
246 enum Class {
247 Init,
248 Use,
249 SelfInit,
250 Ignore
251 };
252
253private:
254 const DeclContext *DC;
255 llvm::DenseMap<const DeclRefExpr*, Class> Classification;
256
257 bool isTrackedVar(const VarDecl *VD) const {
258 return ::isTrackedVar(VD, DC);
259 }
260
261 void classify(const Expr *E, Class C);
262
263public:
264 ClassifyRefs(AnalysisDeclContext &AC) : DC(cast<DeclContext>(AC.getDecl())) {}
265
266 void VisitDeclStmt(DeclStmt *DS);
267 void VisitUnaryOperator(UnaryOperator *UO);
268 void VisitBinaryOperator(BinaryOperator *BO);
269 void VisitCallExpr(CallExpr *CE);
270 void VisitCastExpr(CastExpr *CE);
271
272 void operator()(Stmt *S) { Visit(S); }
273
274 Class get(const DeclRefExpr *DRE) const {
275 llvm::DenseMap<const DeclRefExpr*, Class>::const_iterator I
276 = Classification.find(DRE);
277 if (I != Classification.end())
278 return I->second;
279
280 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
281 if (!VD || !isTrackedVar(VD))
282 return Ignore;
283
284 return Init;
285 }
286};
287}
288
289static const DeclRefExpr *getSelfInitExpr(VarDecl *VD) {
290 if (Expr *Init = VD->getInit()) {
291 const DeclRefExpr *DRE
292 = dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init));
293 if (DRE && DRE->getDecl() == VD)
294 return DRE;
295 }
Craig Topper25542942014-05-20 04:30:07 +0000296 return nullptr;
Richard Smith6376d1f2012-07-17 00:06:14 +0000297}
298
299void ClassifyRefs::classify(const Expr *E, Class C) {
Ted Kremenek7ba78c62013-01-19 00:25:06 +0000300 // The result of a ?: could also be an lvalue.
301 E = E->IgnoreParens();
302 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieuabf6ec42014-08-27 22:15:10 +0000303 classify(CO->getTrueExpr(), C);
Ted Kremenek7ba78c62013-01-19 00:25:06 +0000304 classify(CO->getFalseExpr(), C);
305 return;
306 }
307
Richard Trieuabf6ec42014-08-27 22:15:10 +0000308 if (const BinaryConditionalOperator *BCO =
309 dyn_cast<BinaryConditionalOperator>(E)) {
310 classify(BCO->getFalseExpr(), C);
311 return;
312 }
313
314 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
315 classify(OVE->getSourceExpr(), C);
316 return;
317 }
318
319 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
320 if (BO->getOpcode() == BO_Comma)
321 classify(BO->getRHS(), C);
322 return;
323 }
324
Richard Smith6376d1f2012-07-17 00:06:14 +0000325 FindVarResult Var = findVar(E, DC);
326 if (const DeclRefExpr *DRE = Var.getDeclRefExpr())
327 Classification[DRE] = std::max(Classification[DRE], C);
328}
329
330void ClassifyRefs::VisitDeclStmt(DeclStmt *DS) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000331 for (auto *DI : DS->decls()) {
332 VarDecl *VD = dyn_cast<VarDecl>(DI);
Richard Smith6376d1f2012-07-17 00:06:14 +0000333 if (VD && isTrackedVar(VD))
334 if (const DeclRefExpr *DRE = getSelfInitExpr(VD))
335 Classification[DRE] = SelfInit;
336 }
337}
338
339void ClassifyRefs::VisitBinaryOperator(BinaryOperator *BO) {
340 // Ignore the evaluation of a DeclRefExpr on the LHS of an assignment. If this
341 // is not a compound-assignment, we will treat it as initializing the variable
342 // when TransferFunctions visits it. A compound-assignment does not affect
343 // whether a variable is uninitialized, and there's no point counting it as a
344 // use.
Richard Smithb21dd022012-07-17 01:27:33 +0000345 if (BO->isCompoundAssignmentOp())
346 classify(BO->getLHS(), Use);
347 else if (BO->getOpcode() == BO_Assign)
Richard Smith6376d1f2012-07-17 00:06:14 +0000348 classify(BO->getLHS(), Ignore);
349}
350
351void ClassifyRefs::VisitUnaryOperator(UnaryOperator *UO) {
352 // Increment and decrement are uses despite there being no lvalue-to-rvalue
353 // conversion.
354 if (UO->isIncrementDecrementOp())
355 classify(UO->getSubExpr(), Use);
356}
357
358void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
Richard Trieu11fd0792014-08-26 04:30:55 +0000359 // Classify arguments to std::move as used.
360 if (CE->getNumArgs() == 1) {
361 if (FunctionDecl *FD = CE->getDirectCallee()) {
362 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
363 classify(CE->getArg(0), Use);
364 return;
365 }
366 }
367 }
368
Richard Smith6376d1f2012-07-17 00:06:14 +0000369 // If a value is passed by const reference to a function, we should not assume
370 // that it is initialized by the call, and we conservatively do not assume
371 // that it is used.
372 for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end();
373 I != E; ++I)
374 if ((*I)->getType().isConstQualified() && (*I)->isGLValue())
375 classify(*I, Ignore);
376}
377
378void ClassifyRefs::VisitCastExpr(CastExpr *CE) {
379 if (CE->getCastKind() == CK_LValueToRValue)
380 classify(CE->getSubExpr(), Use);
381 else if (CStyleCastExpr *CSE = dyn_cast<CStyleCastExpr>(CE)) {
382 if (CSE->getType()->isVoidType()) {
383 // Squelch any detected load of an uninitialized value if
384 // we cast it to void.
385 // e.g. (void) x;
386 classify(CSE->getSubExpr(), Ignore);
387 }
388 }
389}
390
391//------------------------------------------------------------------------====//
392// Transfer function for uninitialized values analysis.
393//====------------------------------------------------------------------------//
394
395namespace {
Ted Kremenek9e100ea2011-07-19 14:18:48 +0000396class TransferFunctions : public StmtVisitor<TransferFunctions> {
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000397 CFGBlockValues &vals;
398 const CFG &cfg;
Richard Smith4323bf82012-05-25 02:17:09 +0000399 const CFGBlock *block;
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000400 AnalysisDeclContext &ac;
Richard Smith6376d1f2012-07-17 00:06:14 +0000401 const ClassifyRefs &classification;
Ted Kremenekedf22ed2012-09-13 00:21:35 +0000402 ObjCNoReturn objCNoRet;
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000403 UninitVariablesHandler &handler;
Richard Smith6376d1f2012-07-17 00:06:14 +0000404
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000405public:
406 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
Richard Smith4323bf82012-05-25 02:17:09 +0000407 const CFGBlock *block, AnalysisDeclContext &ac,
Richard Smith6376d1f2012-07-17 00:06:14 +0000408 const ClassifyRefs &classification,
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000409 UninitVariablesHandler &handler)
Richard Smith6376d1f2012-07-17 00:06:14 +0000410 : vals(vals), cfg(cfg), block(block), ac(ac),
Ted Kremenekedf22ed2012-09-13 00:21:35 +0000411 classification(classification), objCNoRet(ac.getASTContext()),
412 handler(handler) {}
Richard Smith6376d1f2012-07-17 00:06:14 +0000413
Richard Smith3d31e8b2012-05-24 23:45:35 +0000414 void reportUse(const Expr *ex, const VarDecl *vd);
Ted Kremenekbcf848f2011-01-25 19:13:48 +0000415
Ted Kremenekedf22ed2012-09-13 00:21:35 +0000416 void VisitBinaryOperator(BinaryOperator *bo);
Ted Kremenekbcf848f2011-01-25 19:13:48 +0000417 void VisitBlockExpr(BlockExpr *be);
Richard Smithb721e302012-07-02 23:23:04 +0000418 void VisitCallExpr(CallExpr *ce);
Ted Kremenekb63931e2011-01-18 21:18:58 +0000419 void VisitDeclRefExpr(DeclRefExpr *dr);
Ted Kremenekedf22ed2012-09-13 00:21:35 +0000420 void VisitDeclStmt(DeclStmt *ds);
421 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS);
422 void VisitObjCMessageExpr(ObjCMessageExpr *ME);
Richard Smith4323bf82012-05-25 02:17:09 +0000423
Ted Kremenek93a31382011-01-27 02:29:34 +0000424 bool isTrackedVar(const VarDecl *vd) {
425 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
426 }
Richard Smith4323bf82012-05-25 02:17:09 +0000427
Richard Smith6376d1f2012-07-17 00:06:14 +0000428 FindVarResult findVar(const Expr *ex) {
429 return ::findVar(ex, cast<DeclContext>(ac.getDecl()));
430 }
431
Richard Smith4323bf82012-05-25 02:17:09 +0000432 UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) {
433 UninitUse Use(ex, isAlwaysUninit(v));
434
435 assert(isUninitialized(v));
436 if (Use.getKind() == UninitUse::Always)
437 return Use;
438
439 // If an edge which leads unconditionally to this use did not initialize
440 // the variable, we can say something stronger than 'may be uninitialized':
441 // we can say 'either it's used uninitialized or you have dead code'.
442 //
443 // We track the number of successors of a node which have been visited, and
444 // visit a node once we have visited all of its successors. Only edges where
445 // the variable might still be uninitialized are followed. Since a variable
446 // can't transfer from being initialized to being uninitialized, this will
447 // trace out the subgraph which inevitably leads to the use and does not
448 // initialize the variable. We do not want to skip past loops, since their
449 // non-termination might be correlated with the initialization condition.
450 //
451 // For example:
452 //
453 // void f(bool a, bool b) {
454 // block1: int n;
455 // if (a) {
456 // block2: if (b)
457 // block3: n = 1;
458 // block4: } else if (b) {
459 // block5: while (!a) {
460 // block6: do_work(&a);
461 // n = 2;
462 // }
463 // }
464 // block7: if (a)
465 // block8: g();
466 // block9: return n;
467 // }
468 //
469 // Starting from the maybe-uninitialized use in block 9:
470 // * Block 7 is not visited because we have only visited one of its two
471 // successors.
472 // * Block 8 is visited because we've visited its only successor.
473 // From block 8:
474 // * Block 7 is visited because we've now visited both of its successors.
475 // From block 7:
476 // * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all
477 // of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively).
478 // * Block 3 is not visited because it initializes 'n'.
479 // Now the algorithm terminates, having visited blocks 7 and 8, and having
480 // found the frontier is blocks 2, 4, and 5.
481 //
482 // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2
483 // and 4), so we report that any time either of those edges is taken (in
484 // each case when 'b == false'), 'n' is used uninitialized.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000485 SmallVector<const CFGBlock*, 32> Queue;
486 SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0);
Richard Smith4323bf82012-05-25 02:17:09 +0000487 Queue.push_back(block);
488 // Specify that we've already visited all successors of the starting block.
489 // This has the dual purpose of ensuring we never add it to the queue, and
490 // of marking it as not being a candidate element of the frontier.
491 SuccsVisited[block->getBlockID()] = block->succ_size();
492 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000493 const CFGBlock *B = Queue.pop_back_val();
Richard Smithba8071e2013-09-12 18:49:10 +0000494
495 // If the use is always reached from the entry block, make a note of that.
496 if (B == &cfg.getEntry())
497 Use.setUninitAfterCall();
498
Richard Smith4323bf82012-05-25 02:17:09 +0000499 for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end();
500 I != E; ++I) {
501 const CFGBlock *Pred = *I;
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000502 if (!Pred)
503 continue;
504
Richard Smithba8071e2013-09-12 18:49:10 +0000505 Value AtPredExit = vals.getValue(Pred, B, vd);
506 if (AtPredExit == Initialized)
Richard Smith4323bf82012-05-25 02:17:09 +0000507 // This block initializes the variable.
508 continue;
Richard Smithba8071e2013-09-12 18:49:10 +0000509 if (AtPredExit == MayUninitialized &&
Craig Topper25542942014-05-20 04:30:07 +0000510 vals.getValue(B, nullptr, vd) == Uninitialized) {
Richard Smithba8071e2013-09-12 18:49:10 +0000511 // This block declares the variable (uninitialized), and is reachable
512 // from a block that initializes the variable. We can't guarantee to
513 // give an earlier location for the diagnostic (and it appears that
514 // this code is intended to be reachable) so give a diagnostic here
515 // and go no further down this path.
516 Use.setUninitAfterDecl();
517 continue;
518 }
Richard Smith4323bf82012-05-25 02:17:09 +0000519
Richard Smith130b8d42012-07-13 23:33:44 +0000520 unsigned &SV = SuccsVisited[Pred->getBlockID()];
521 if (!SV) {
522 // When visiting the first successor of a block, mark all NULL
523 // successors as having been visited.
524 for (CFGBlock::const_succ_iterator SI = Pred->succ_begin(),
525 SE = Pred->succ_end();
526 SI != SE; ++SI)
527 if (!*SI)
528 ++SV;
529 }
530
531 if (++SV == Pred->succ_size())
Richard Smith4323bf82012-05-25 02:17:09 +0000532 // All paths from this block lead to the use and don't initialize the
533 // variable.
534 Queue.push_back(Pred);
535 }
536 }
537
538 // Scan the frontier, looking for blocks where the variable was
539 // uninitialized.
540 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
541 const CFGBlock *Block = *BI;
542 unsigned BlockID = Block->getBlockID();
543 const Stmt *Term = Block->getTerminator();
544 if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() &&
545 Term) {
546 // This block inevitably leads to the use. If we have an edge from here
547 // to a post-dominator block, and the variable is uninitialized on that
548 // edge, we have found a bug.
549 for (CFGBlock::const_succ_iterator I = Block->succ_begin(),
550 E = Block->succ_end(); I != E; ++I) {
551 const CFGBlock *Succ = *I;
552 if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() &&
553 vals.getValue(Block, Succ, vd) == Uninitialized) {
554 // Switch cases are a special case: report the label to the caller
555 // as the 'terminator', not the switch statement itself. Suppress
556 // situations where no label matched: we can't be sure that's
557 // possible.
558 if (isa<SwitchStmt>(Term)) {
559 const Stmt *Label = Succ->getLabel();
560 if (!Label || !isa<SwitchCase>(Label))
561 // Might not be possible.
562 continue;
563 UninitUse::Branch Branch;
564 Branch.Terminator = Label;
565 Branch.Output = 0; // Ignored.
566 Use.addUninitBranch(Branch);
567 } else {
568 UninitUse::Branch Branch;
569 Branch.Terminator = Term;
570 Branch.Output = I - Block->succ_begin();
571 Use.addUninitBranch(Branch);
572 }
573 }
574 }
575 }
576 }
577
578 return Use;
579 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000580};
581}
582
Richard Smith3d31e8b2012-05-24 23:45:35 +0000583void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) {
Richard Smith3d31e8b2012-05-24 23:45:35 +0000584 Value v = vals[vd];
585 if (isUninitialized(v))
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000586 handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v));
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000587}
588
Richard Smith6376d1f2012-07-17 00:06:14 +0000589void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) {
Ted Kremenek4058d872011-01-27 02:01:31 +0000590 // This represents an initialization of the 'element' value.
Richard Smith6376d1f2012-07-17 00:06:14 +0000591 if (DeclStmt *DS = dyn_cast<DeclStmt>(FS->getElement())) {
592 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
593 if (isTrackedVar(VD))
594 vals[VD] = Initialized;
Ted Kremenek4058d872011-01-27 02:01:31 +0000595 }
Ted Kremenek4058d872011-01-27 02:01:31 +0000596}
597
Ted Kremenekbcf848f2011-01-25 19:13:48 +0000598void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
Ted Kremenek77361762011-03-31 22:32:41 +0000599 const BlockDecl *bd = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000600 for (const auto &I : bd->captures()) {
601 const VarDecl *vd = I.getVariable();
Ted Kremenek77361762011-03-31 22:32:41 +0000602 if (!isTrackedVar(vd))
603 continue;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000604 if (I.isByRef()) {
Ted Kremenek77361762011-03-31 22:32:41 +0000605 vals[vd] = Initialized;
606 continue;
607 }
Richard Smith3d31e8b2012-05-24 23:45:35 +0000608 reportUse(be, vd);
Ted Kremenekbcf848f2011-01-25 19:13:48 +0000609 }
610}
611
Richard Smithb721e302012-07-02 23:23:04 +0000612void TransferFunctions::VisitCallExpr(CallExpr *ce) {
Ted Kremenek7979ccf2012-09-12 05:53:43 +0000613 if (Decl *Callee = ce->getCalleeDecl()) {
614 if (Callee->hasAttr<ReturnsTwiceAttr>()) {
615 // After a call to a function like setjmp or vfork, any variable which is
616 // initialized anywhere within this function may now be initialized. For
617 // now, just assume such a call initializes all variables. FIXME: Only
618 // mark variables as initialized if they have an initializer which is
619 // reachable from here.
620 vals.setAllScratchValues(Initialized);
621 }
622 else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) {
623 // Functions labeled like "analyzer_noreturn" are often used to denote
624 // "panic" functions that in special debug situations can still return,
625 // but for the most part should not be treated as returning. This is a
626 // useful annotation borrowed from the static analyzer that is useful for
627 // suppressing branch-specific false positives when we call one of these
628 // functions but keep pretending the path continues (when in reality the
629 // user doesn't care).
630 vals.setAllScratchValues(Unknown);
631 }
632 }
Richard Smithb721e302012-07-02 23:23:04 +0000633}
634
Ted Kremenek9e100ea2011-07-19 14:18:48 +0000635void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
Richard Smith6376d1f2012-07-17 00:06:14 +0000636 switch (classification.get(dr)) {
637 case ClassifyRefs::Ignore:
638 break;
639 case ClassifyRefs::Use:
640 reportUse(dr, cast<VarDecl>(dr->getDecl()));
641 break;
642 case ClassifyRefs::Init:
643 vals[cast<VarDecl>(dr->getDecl())] = Initialized;
644 break;
645 case ClassifyRefs::SelfInit:
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000646 handler.handleSelfInit(cast<VarDecl>(dr->getDecl()));
Richard Smith6376d1f2012-07-17 00:06:14 +0000647 break;
648 }
Ted Kremenek9e100ea2011-07-19 14:18:48 +0000649}
650
Richard Smith6376d1f2012-07-17 00:06:14 +0000651void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) {
652 if (BO->getOpcode() == BO_Assign) {
653 FindVarResult Var = findVar(BO->getLHS());
654 if (const VarDecl *VD = Var.getDecl())
655 vals[VD] = Initialized;
656 }
657}
658
659void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000660 for (auto *DI : DS->decls()) {
661 VarDecl *VD = dyn_cast<VarDecl>(DI);
Richard Smith6376d1f2012-07-17 00:06:14 +0000662 if (VD && isTrackedVar(VD)) {
663 if (getSelfInitExpr(VD)) {
664 // If the initializer consists solely of a reference to itself, we
665 // explicitly mark the variable as uninitialized. This allows code
666 // like the following:
667 //
668 // int x = x;
669 //
670 // to deliberately leave a variable uninitialized. Different analysis
671 // clients can detect this pattern and adjust their reporting
672 // appropriately, but we need to continue to analyze subsequent uses
673 // of the variable.
674 vals[VD] = Uninitialized;
675 } else if (VD->getInit()) {
676 // Treat the new variable as initialized.
677 vals[VD] = Initialized;
678 } else {
679 // No initializer: the variable is now uninitialized. This matters
680 // for cases like:
681 // while (...) {
682 // int n;
683 // use(n);
684 // n = 0;
685 // }
686 // FIXME: Mark the variable as uninitialized whenever its scope is
687 // left, since its scope could be re-entered by a jump over the
688 // declaration.
689 vals[VD] = Uninitialized;
Ted Kremenekb63931e2011-01-18 21:18:58 +0000690 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000691 }
692 }
693}
694
Ted Kremenekedf22ed2012-09-13 00:21:35 +0000695void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) {
696 // If the Objective-C message expression is an implicit no-return that
697 // is not modeled in the CFG, set the tracked dataflow values to Unknown.
698 if (objCNoRet.isImplicitNoReturn(ME)) {
699 vals.setAllScratchValues(Unknown);
700 }
701}
702
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000703//------------------------------------------------------------------------====//
704// High-level "driver" logic for uninitialized values analysis.
705//====------------------------------------------------------------------------//
706
Ted Kremenekb82ddd62011-01-20 17:37:17 +0000707static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000708 AnalysisDeclContext &ac, CFGBlockValues &vals,
Richard Smith6376d1f2012-07-17 00:06:14 +0000709 const ClassifyRefs &classification,
Ted Kremenek352a7082011-04-04 20:30:58 +0000710 llvm::BitVector &wasAnalyzed,
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000711 UninitVariablesHandler &handler) {
Ted Kremenek352a7082011-04-04 20:30:58 +0000712 wasAnalyzed[block->getBlockID()] = true;
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000713 vals.resetScratch();
Ted Kremenek6080d322012-07-19 04:59:05 +0000714 // Merge in values of predecessor blocks.
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000715 bool isFirst = true;
716 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
717 E = block->pred_end(); I != E; ++I) {
Ted Kremenekaed46772011-09-02 19:39:26 +0000718 const CFGBlock *pred = *I;
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000719 if (!pred)
720 continue;
Ted Kremenekaed46772011-09-02 19:39:26 +0000721 if (wasAnalyzed[pred->getBlockID()]) {
Ted Kremenek6080d322012-07-19 04:59:05 +0000722 vals.mergeIntoScratch(vals.getValueVector(pred), isFirst);
Ted Kremenekaed46772011-09-02 19:39:26 +0000723 isFirst = false;
724 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000725 }
726 // Apply the transfer function.
Richard Smith6376d1f2012-07-17 00:06:14 +0000727 TransferFunctions tf(vals, cfg, block, ac, classification, handler);
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000728 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
729 I != E; ++I) {
David Blaikie00be69a2013-02-23 00:29:34 +0000730 if (Optional<CFGStmt> cs = I->getAs<CFGStmt>())
731 tf.Visit(const_cast<Stmt*>(cs->getStmt()));
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000732 }
Ted Kremeneka895fe92011-03-15 04:57:27 +0000733 return vals.updateValueVectorWithScratch(block);
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000734}
735
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000736/// PruneBlocksHandler is a special UninitVariablesHandler that is used
737/// to detect when a CFGBlock has any *potential* use of an uninitialized
738/// variable. It is mainly used to prune out work during the final
739/// reporting pass.
740namespace {
741struct PruneBlocksHandler : public UninitVariablesHandler {
742 PruneBlocksHandler(unsigned numBlocks)
743 : hadUse(numBlocks, false), hadAnyUse(false),
744 currentBlock(0) {}
745
746 virtual ~PruneBlocksHandler() {}
747
748 /// Records if a CFGBlock had a potential use of an uninitialized variable.
749 llvm::BitVector hadUse;
750
751 /// Records if any CFGBlock had a potential use of an uninitialized variable.
752 bool hadAnyUse;
753
754 /// The current block to scribble use information.
755 unsigned currentBlock;
756
Craig Topperb45acb82014-03-14 06:02:07 +0000757 void handleUseOfUninitVariable(const VarDecl *vd,
758 const UninitUse &use) override {
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000759 hadUse[currentBlock] = true;
760 hadAnyUse = true;
761 }
762
763 /// Called when the uninitialized variable analysis detects the
764 /// idiom 'int x = x'. All other uses of 'x' within the initializer
765 /// are handled by handleUseOfUninitVariable.
Craig Topperb45acb82014-03-14 06:02:07 +0000766 void handleSelfInit(const VarDecl *vd) override {
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000767 hadUse[currentBlock] = true;
768 hadAnyUse = true;
769 }
770};
771}
772
Chandler Carruthb4836ea2011-07-06 16:21:37 +0000773void clang::runUninitializedVariablesAnalysis(
774 const DeclContext &dc,
775 const CFG &cfg,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000776 AnalysisDeclContext &ac,
Chandler Carruthb4836ea2011-07-06 16:21:37 +0000777 UninitVariablesHandler &handler,
778 UninitVariablesAnalysisStats &stats) {
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000779 CFGBlockValues vals(cfg);
780 vals.computeSetOfDeclarations(dc);
781 if (vals.hasNoDeclarations())
782 return;
Ted Kremenek37881932011-04-04 23:29:12 +0000783
Chandler Carruthb4836ea2011-07-06 16:21:37 +0000784 stats.NumVariablesAnalyzed = vals.getNumEntries();
785
Richard Smith6376d1f2012-07-17 00:06:14 +0000786 // Precompute which expressions are uses and which are initializations.
787 ClassifyRefs classification(ac);
788 cfg.VisitBlockStmts(classification);
789
Ted Kremenek37881932011-04-04 23:29:12 +0000790 // Mark all variables uninitialized at the entry.
791 const CFGBlock &entry = cfg.getEntry();
Ted Kremenek6080d322012-07-19 04:59:05 +0000792 ValueVector &vec = vals.getValueVector(&entry);
793 const unsigned n = vals.getNumEntries();
794 for (unsigned j = 0; j < n ; ++j) {
795 vec[j] = Uninitialized;
Ted Kremenek37881932011-04-04 23:29:12 +0000796 }
797
798 // Proceed with the workist.
Artyom Skrobova208a732014-08-14 16:04:47 +0000799 ForwardDataflowWorklist worklist(cfg, ac);
Ted Kremenek9b15c962011-03-15 04:57:32 +0000800 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000801 worklist.enqueueSuccessors(&cfg.getEntry());
Ted Kremenek352a7082011-04-04 20:30:58 +0000802 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
Ted Kremenekaed46772011-09-02 19:39:26 +0000803 wasAnalyzed[cfg.getEntry().getBlockID()] = true;
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000804 PruneBlocksHandler PBH(cfg.getNumBlockIDs());
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000805
806 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000807 PBH.currentBlock = block->getBlockID();
808
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000809 // Did the block change?
Richard Smith6376d1f2012-07-17 00:06:14 +0000810 bool changed = runOnBlock(block, cfg, ac, vals,
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000811 classification, wasAnalyzed, PBH);
Chandler Carruthb4836ea2011-07-06 16:21:37 +0000812 ++stats.NumBlockVisits;
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000813 if (changed || !previouslyVisited[block->getBlockID()])
814 worklist.enqueueSuccessors(block);
815 previouslyVisited[block->getBlockID()] = true;
816 }
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000817
818 if (!PBH.hadAnyUse)
819 return;
820
Enea Zaffanella392291f2013-01-11 11:37:08 +0000821 // Run through the blocks one more time, and report uninitialized variables.
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000822 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
Ted Kremenekaed46772011-09-02 19:39:26 +0000823 const CFGBlock *block = *BI;
Ted Kremenek778a6ed2012-11-17 07:18:30 +0000824 if (PBH.hadUse[block->getBlockID()]) {
825 runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler);
Chandler Carruthb4836ea2011-07-06 16:21:37 +0000826 ++stats.NumBlockVisits;
827 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000828 }
829}
830
831UninitVariablesHandler::~UninitVariablesHandler() {}