blob: 77da2427c0fcbc2a6ccb15b66f2e820119ca2ff2 [file] [log] [blame]
Ted Kremenek6f342132011-03-15 03:17:07 +00001//==- UninitializedValues.cpp - Find Uninitialized Values -------*- C++ --*-==//
Ted Kremenek610068c2011-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
Ted Kremenek13bd4232011-01-20 17:37:17 +000014#include <utility>
Ted Kremenek610068c2011-01-15 02:58:47 +000015#include "llvm/ADT/Optional.h"
16#include "llvm/ADT/SmallVector.h"
Argyrios Kyrtzidis049f6d02011-05-31 03:56:09 +000017#include "llvm/ADT/PackedVector.h"
Ted Kremenek610068c2011-01-15 02:58:47 +000018#include "llvm/ADT/DenseMap.h"
19#include "clang/AST/Decl.h"
20#include "clang/Analysis/CFG.h"
Ted Kremeneka8c17a52011-01-25 19:13:48 +000021#include "clang/Analysis/AnalysisContext.h"
Ted Kremenek610068c2011-01-15 02:58:47 +000022#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000023#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekc21fed32011-01-18 21:18:58 +000024#include "clang/Analysis/Support/SaveAndRestore.h"
Ted Kremenek610068c2011-01-15 02:58:47 +000025
26using namespace clang;
27
Ted Kremenek40900ee2011-01-27 02:29:34 +000028static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) {
Ted Kremenek1cbc3152011-03-17 03:06:11 +000029 if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() &&
Ted Kremeneka21612f2011-04-07 20:02:56 +000030 !vd->isExceptionVariable() &&
Ted Kremenek1cbc3152011-03-17 03:06:11 +000031 vd->getDeclContext() == dc) {
32 QualType ty = vd->getType();
33 return ty->isScalarType() || ty->isVectorType();
34 }
35 return false;
Ted Kremenekc104e532011-01-18 04:53:25 +000036}
37
Ted Kremenek610068c2011-01-15 02:58:47 +000038//------------------------------------------------------------------------====//
Ted Kremenek136f8f22011-03-15 04:57:27 +000039// DeclToIndex: a mapping from Decls we track to value indices.
Ted Kremenek610068c2011-01-15 02:58:47 +000040//====------------------------------------------------------------------------//
41
42namespace {
Ted Kremenek136f8f22011-03-15 04:57:27 +000043class DeclToIndex {
Ted Kremenek610068c2011-01-15 02:58:47 +000044 llvm::DenseMap<const VarDecl *, unsigned> map;
45public:
Ted Kremenek136f8f22011-03-15 04:57:27 +000046 DeclToIndex() {}
Ted Kremenek610068c2011-01-15 02:58:47 +000047
48 /// Compute the actual mapping from declarations to bits.
49 void computeMap(const DeclContext &dc);
50
51 /// Return the number of declarations in the map.
52 unsigned size() const { return map.size(); }
53
54 /// Returns the bit vector index for a given declaration.
Ted Kremenekb831c672011-03-29 01:40:00 +000055 llvm::Optional<unsigned> getValueIndex(const VarDecl *d) const;
Ted Kremenek610068c2011-01-15 02:58:47 +000056};
57}
58
Ted Kremenek136f8f22011-03-15 04:57:27 +000059void DeclToIndex::computeMap(const DeclContext &dc) {
Ted Kremenek610068c2011-01-15 02:58:47 +000060 unsigned count = 0;
61 DeclContext::specific_decl_iterator<VarDecl> I(dc.decls_begin()),
62 E(dc.decls_end());
63 for ( ; I != E; ++I) {
64 const VarDecl *vd = *I;
Ted Kremenek40900ee2011-01-27 02:29:34 +000065 if (isTrackedVar(vd, &dc))
Ted Kremenek610068c2011-01-15 02:58:47 +000066 map[vd] = count++;
67 }
68}
69
Ted Kremenekb831c672011-03-29 01:40:00 +000070llvm::Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const {
71 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d);
Ted Kremenek610068c2011-01-15 02:58:47 +000072 if (I == map.end())
73 return llvm::Optional<unsigned>();
74 return I->second;
75}
76
77//------------------------------------------------------------------------====//
78// CFGBlockValues: dataflow values for CFG blocks.
79//====------------------------------------------------------------------------//
80
Ted Kremenekf7bafc72011-03-15 04:57:38 +000081// These values are defined in such a way that a merge can be done using
82// a bitwise OR.
83enum Value { Unknown = 0x0, /* 00 */
84 Initialized = 0x1, /* 01 */
85 Uninitialized = 0x2, /* 10 */
86 MayUninitialized = 0x3 /* 11 */ };
87
88static bool isUninitialized(const Value v) {
89 return v >= Uninitialized;
90}
91static bool isAlwaysUninit(const Value v) {
92 return v == Uninitialized;
93}
Ted Kremenekafb10c42011-03-15 04:57:29 +000094
Benjamin Kramerda57f3e2011-03-26 12:38:21 +000095namespace {
Ted Kremenek496398d2011-03-15 04:57:32 +000096
Argyrios Kyrtzidis049f6d02011-05-31 03:56:09 +000097typedef llvm::PackedVector<Value, 2> ValueVector;
Ted Kremenek136f8f22011-03-15 04:57:27 +000098typedef std::pair<ValueVector *, ValueVector *> BVPair;
Ted Kremenek13bd4232011-01-20 17:37:17 +000099
Ted Kremenek610068c2011-01-15 02:58:47 +0000100class CFGBlockValues {
101 const CFG &cfg;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000102 BVPair *vals;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000103 ValueVector scratch;
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000104 DeclToIndex declToIndex;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000105
Ted Kremenek136f8f22011-03-15 04:57:27 +0000106 ValueVector &lazyCreate(ValueVector *&bv);
Ted Kremenek610068c2011-01-15 02:58:47 +0000107public:
108 CFGBlockValues(const CFG &cfg);
109 ~CFGBlockValues();
110
Ted Kremenekd40066b2011-04-04 23:29:12 +0000111 unsigned getNumEntries() const { return declToIndex.size(); }
112
Ted Kremenek610068c2011-01-15 02:58:47 +0000113 void computeSetOfDeclarations(const DeclContext &dc);
Ted Kremenek136f8f22011-03-15 04:57:27 +0000114 ValueVector &getValueVector(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000115 const CFGBlock *dstBlock);
116
Ted Kremenek136f8f22011-03-15 04:57:27 +0000117 BVPair &getValueVectors(const CFGBlock *block, bool shouldLazyCreate);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000118
Ted Kremenek136f8f22011-03-15 04:57:27 +0000119 void mergeIntoScratch(ValueVector const &source, bool isFirst);
120 bool updateValueVectorWithScratch(const CFGBlock *block);
121 bool updateValueVectors(const CFGBlock *block, const BVPair &newVals);
Ted Kremenek610068c2011-01-15 02:58:47 +0000122
123 bool hasNoDeclarations() const {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000124 return declToIndex.size() == 0;
Ted Kremenek610068c2011-01-15 02:58:47 +0000125 }
Ted Kremeneke0e29332011-08-20 01:15:28 +0000126
Ted Kremenek610068c2011-01-15 02:58:47 +0000127 void resetScratch();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000128 ValueVector &getScratch() { return scratch; }
Ted Kremenek13bd4232011-01-20 17:37:17 +0000129
Ted Kremenek136f8f22011-03-15 04:57:27 +0000130 ValueVector::reference operator[](const VarDecl *vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000131};
Benjamin Kramerda57f3e2011-03-26 12:38:21 +0000132} // end anonymous namespace
Ted Kremenek610068c2011-01-15 02:58:47 +0000133
134CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {
135 unsigned n = cfg.getNumBlockIDs();
136 if (!n)
137 return;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000138 vals = new std::pair<ValueVector*, ValueVector*>[n];
Chandler Carruth75c40642011-04-28 08:19:45 +0000139 memset((void*)vals, 0, sizeof(*vals) * n);
Ted Kremenek610068c2011-01-15 02:58:47 +0000140}
141
142CFGBlockValues::~CFGBlockValues() {
143 unsigned n = cfg.getNumBlockIDs();
144 if (n == 0)
145 return;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000146 for (unsigned i = 0; i < n; ++i) {
147 delete vals[i].first;
148 delete vals[i].second;
149 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000150 delete [] vals;
151}
152
153void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000154 declToIndex.computeMap(dc);
155 scratch.resize(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000156}
157
Ted Kremenek136f8f22011-03-15 04:57:27 +0000158ValueVector &CFGBlockValues::lazyCreate(ValueVector *&bv) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000159 if (!bv)
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000160 bv = new ValueVector(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000161 return *bv;
162}
163
Ted Kremenek13bd4232011-01-20 17:37:17 +0000164/// This function pattern matches for a '&&' or '||' that appears at
165/// the beginning of a CFGBlock that also (1) has a terminator and
166/// (2) has no other elements. If such an expression is found, it is returned.
167static BinaryOperator *getLogicalOperatorInChain(const CFGBlock *block) {
168 if (block->empty())
169 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000170
Ted Kremenek3c0349e2011-03-01 03:15:10 +0000171 const CFGStmt *cstmt = block->front().getAs<CFGStmt>();
Ted Kremenek76709bf2011-03-15 05:22:28 +0000172 if (!cstmt)
173 return 0;
174
Chris Lattner5f9e2722011-07-23 10:55:15 +0000175 BinaryOperator *b = dyn_cast_or_null<BinaryOperator>(cstmt->getStmt());
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000176
177 if (!b || !b->isLogicalOp())
Ted Kremenek13bd4232011-01-20 17:37:17 +0000178 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000179
Ted Kremeneke6c28032011-05-10 22:10:35 +0000180 if (block->pred_size() == 2) {
181 if (block->getTerminatorCondition() == b) {
182 if (block->succ_size() == 2)
183 return b;
184 }
185 else if (block->size() == 1)
186 return b;
187 }
188
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000189 return 0;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000190}
191
Ted Kremenek136f8f22011-03-15 04:57:27 +0000192ValueVector &CFGBlockValues::getValueVector(const CFGBlock *block,
193 const CFGBlock *dstBlock) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000194 unsigned idx = block->getBlockID();
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000195 if (dstBlock && getLogicalOperatorInChain(block)) {
196 if (*block->succ_begin() == dstBlock)
197 return lazyCreate(vals[idx].first);
198 assert(*(block->succ_begin()+1) == dstBlock);
199 return lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000200 }
201
202 assert(vals[idx].second == 0);
203 return lazyCreate(vals[idx].first);
204}
205
Ted Kremenek136f8f22011-03-15 04:57:27 +0000206BVPair &CFGBlockValues::getValueVectors(const clang::CFGBlock *block,
207 bool shouldLazyCreate) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000208 unsigned idx = block->getBlockID();
209 lazyCreate(vals[idx].first);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000210 if (shouldLazyCreate)
211 lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000212 return vals[idx];
213}
214
Ted Kremenek136f8f22011-03-15 04:57:27 +0000215void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
Ted Kremenek610068c2011-01-15 02:58:47 +0000216 bool isFirst) {
217 if (isFirst)
218 scratch = source;
219 else
Argyrios Kyrtzidis049f6d02011-05-31 03:56:09 +0000220 scratch |= source;
Ted Kremenek610068c2011-01-15 02:58:47 +0000221}
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000222#if 0
Ted Kremenek136f8f22011-03-15 04:57:27 +0000223static void printVector(const CFGBlock *block, ValueVector &bv,
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000224 unsigned num) {
225
226 llvm::errs() << block->getBlockID() << " :";
227 for (unsigned i = 0; i < bv.size(); ++i) {
228 llvm::errs() << ' ' << bv[i];
229 }
230 llvm::errs() << " : " << num << '\n';
231}
232#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000233
Ted Kremenek136f8f22011-03-15 04:57:27 +0000234bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
235 ValueVector &dst = getValueVector(block, 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000236 bool changed = (dst != scratch);
237 if (changed)
238 dst = scratch;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000239#if 0
240 printVector(block, scratch, 0);
241#endif
Ted Kremenek13bd4232011-01-20 17:37:17 +0000242 return changed;
243}
244
Ted Kremenek136f8f22011-03-15 04:57:27 +0000245bool CFGBlockValues::updateValueVectors(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000246 const BVPair &newVals) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000247 BVPair &vals = getValueVectors(block, true);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000248 bool changed = *newVals.first != *vals.first ||
249 *newVals.second != *vals.second;
250 *vals.first = *newVals.first;
251 *vals.second = *newVals.second;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000252#if 0
253 printVector(block, *vals.first, 1);
254 printVector(block, *vals.second, 2);
255#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000256 return changed;
257}
258
259void CFGBlockValues::resetScratch() {
260 scratch.reset();
261}
262
Ted Kremenek136f8f22011-03-15 04:57:27 +0000263ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000264 const llvm::Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000265 assert(idx.hasValue());
266 return scratch[idx.getValue()];
267}
268
269//------------------------------------------------------------------------====//
270// Worklist: worklist for dataflow analysis.
271//====------------------------------------------------------------------------//
272
273namespace {
274class DataflowWorklist {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000275 SmallVector<const CFGBlock *, 20> worklist;
Ted Kremenek496398d2011-03-15 04:57:32 +0000276 llvm::BitVector enqueuedBlocks;
Ted Kremenek610068c2011-01-15 02:58:47 +0000277public:
278 DataflowWorklist(const CFG &cfg) : enqueuedBlocks(cfg.getNumBlockIDs()) {}
279
Ted Kremenek610068c2011-01-15 02:58:47 +0000280 void enqueueSuccessors(const CFGBlock *block);
281 const CFGBlock *dequeue();
Ted Kremenek610068c2011-01-15 02:58:47 +0000282};
283}
284
Ted Kremenek610068c2011-01-15 02:58:47 +0000285void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
Chandler Carruth80520502011-07-08 11:19:06 +0000286 unsigned OldWorklistSize = worklist.size();
Ted Kremenek610068c2011-01-15 02:58:47 +0000287 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
288 E = block->succ_end(); I != E; ++I) {
Chandler Carruth80520502011-07-08 11:19:06 +0000289 const CFGBlock *Successor = *I;
290 if (!Successor || enqueuedBlocks[Successor->getBlockID()])
291 continue;
292 worklist.push_back(Successor);
293 enqueuedBlocks[Successor->getBlockID()] = true;
Ted Kremenek610068c2011-01-15 02:58:47 +0000294 }
Chandler Carruth80520502011-07-08 11:19:06 +0000295 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
296 return;
297
298 // Rotate the newly added blocks to the start of the worklist so that it forms
299 // a proper queue when we pop off the end of the worklist.
300 std::rotate(worklist.begin(), worklist.begin() + OldWorklistSize,
301 worklist.end());
Ted Kremenek610068c2011-01-15 02:58:47 +0000302}
303
304const CFGBlock *DataflowWorklist::dequeue() {
305 if (worklist.empty())
306 return 0;
307 const CFGBlock *b = worklist.back();
308 worklist.pop_back();
309 enqueuedBlocks[b->getBlockID()] = false;
310 return b;
311}
312
313//------------------------------------------------------------------------====//
314// Transfer function for uninitialized values analysis.
315//====------------------------------------------------------------------------//
316
Ted Kremenek610068c2011-01-15 02:58:47 +0000317namespace {
318class FindVarResult {
319 const VarDecl *vd;
320 const DeclRefExpr *dr;
321public:
322 FindVarResult(VarDecl *vd, DeclRefExpr *dr) : vd(vd), dr(dr) {}
323
324 const DeclRefExpr *getDeclRefExpr() const { return dr; }
325 const VarDecl *getDecl() const { return vd; }
326};
327
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000328class TransferFunctions : public StmtVisitor<TransferFunctions> {
Ted Kremenek610068c2011-01-15 02:58:47 +0000329 CFGBlockValues &vals;
330 const CFG &cfg;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000331 AnalysisContext &ac;
Ted Kremenek610068c2011-01-15 02:58:47 +0000332 UninitVariablesHandler *handler;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000333 const bool flagBlockUses;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000334
335 /// The last DeclRefExpr seen when analyzing a block. Used to
336 /// cheat when detecting cases when the address of a variable is taken.
337 DeclRefExpr *lastDR;
338
339 /// The last lvalue-to-rvalue conversion of a variable whose value
340 /// was uninitialized. Normally this results in a warning, but it is
341 /// possible to either silence the warning in some cases, or we
342 /// propagate the uninitialized value.
343 CastExpr *lastLoad;
Ted Kremenek57fb5912011-08-04 22:40:57 +0000344
345 /// For some expressions, we want to ignore any post-processing after
346 /// visitation.
347 bool skipProcessUses;
348
Ted Kremenek610068c2011-01-15 02:58:47 +0000349public:
350 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000351 AnalysisContext &ac,
352 UninitVariablesHandler *handler,
353 bool flagBlockUses)
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000354 : vals(vals), cfg(cfg), ac(ac), handler(handler),
Ted Kremenek57fb5912011-08-04 22:40:57 +0000355 flagBlockUses(flagBlockUses), lastDR(0), lastLoad(0),
356 skipProcessUses(false) {}
Ted Kremenek610068c2011-01-15 02:58:47 +0000357
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000358 void reportUninit(const DeclRefExpr *ex, const VarDecl *vd,
359 bool isAlwaysUninit);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000360
361 void VisitBlockExpr(BlockExpr *be);
Ted Kremenek610068c2011-01-15 02:58:47 +0000362 void VisitDeclStmt(DeclStmt *ds);
Ted Kremenekc21fed32011-01-18 21:18:58 +0000363 void VisitDeclRefExpr(DeclRefExpr *dr);
Ted Kremenek610068c2011-01-15 02:58:47 +0000364 void VisitUnaryOperator(UnaryOperator *uo);
365 void VisitBinaryOperator(BinaryOperator *bo);
366 void VisitCastExpr(CastExpr *ce);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000367 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs);
368 void Visit(Stmt *s);
Ted Kremenek40900ee2011-01-27 02:29:34 +0000369
370 bool isTrackedVar(const VarDecl *vd) {
371 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
372 }
373
374 FindVarResult findBlockVarDecl(Expr *ex);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000375
376 void ProcessUses(Stmt *s = 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000377};
378}
379
Ted Kremenekde091ae2011-08-08 21:43:08 +0000380static const Expr *stripCasts(ASTContext &C, const Expr *Ex) {
381 while (Ex) {
382 Ex = Ex->IgnoreParenNoopCasts(C);
383 if (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
384 if (CE->getCastKind() == CK_LValueBitCast) {
385 Ex = CE->getSubExpr();
386 continue;
387 }
388 }
389 break;
390 }
391 return Ex;
392}
393
Ted Kremenek610068c2011-01-15 02:58:47 +0000394void TransferFunctions::reportUninit(const DeclRefExpr *ex,
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000395 const VarDecl *vd, bool isAlwaysUnit) {
396 if (handler) handler->handleUseOfUninitVariable(ex, vd, isAlwaysUnit);
Ted Kremenek610068c2011-01-15 02:58:47 +0000397}
398
Ted Kremenek9c378f72011-08-12 23:37:29 +0000399FindVarResult TransferFunctions::findBlockVarDecl(Expr *ex) {
400 if (DeclRefExpr *dr = dyn_cast<DeclRefExpr>(ex->IgnoreParenCasts()))
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000401 if (VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
402 if (isTrackedVar(vd))
Ted Kremenek40900ee2011-01-27 02:29:34 +0000403 return FindVarResult(vd, dr);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000404 return FindVarResult(0, 0);
405}
406
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000407void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000408 // This represents an initialization of the 'element' value.
409 Stmt *element = fs->getElement();
Ted Kremenek9c378f72011-08-12 23:37:29 +0000410 const VarDecl *vd = 0;
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000411
Ted Kremenek9c378f72011-08-12 23:37:29 +0000412 if (DeclStmt *ds = dyn_cast<DeclStmt>(element)) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000413 vd = cast<VarDecl>(ds->getSingleDecl());
414 if (!isTrackedVar(vd))
415 vd = 0;
Chad Rosier30601782011-08-17 23:08:45 +0000416 } else {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000417 // Initialize the value of the reference variable.
418 const FindVarResult &res = findBlockVarDecl(cast<Expr>(element));
419 vd = res.getDecl();
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000420 }
421
422 if (vd)
423 vals[vd] = Initialized;
424}
425
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000426void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
427 if (!flagBlockUses || !handler)
428 return;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000429 const BlockDecl *bd = be->getBlockDecl();
430 for (BlockDecl::capture_const_iterator i = bd->capture_begin(),
431 e = bd->capture_end() ; i != e; ++i) {
432 const VarDecl *vd = i->getVariable();
433 if (!vd->hasLocalStorage())
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000434 continue;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000435 if (!isTrackedVar(vd))
436 continue;
437 if (i->isByRef()) {
438 vals[vd] = Initialized;
439 continue;
440 }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000441 Value v = vals[vd];
442 if (isUninitialized(v))
443 handler->handleUseOfUninitVariable(be, vd, isAlwaysUninit(v));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000444 }
445}
446
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000447void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
448 // Record the last DeclRefExpr seen. This is an lvalue computation.
449 // We use this value to later detect if a variable "escapes" the analysis.
450 if (const VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000451 if (isTrackedVar(vd)) {
452 ProcessUses();
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000453 lastDR = dr;
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000454 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000455}
456
Ted Kremenek610068c2011-01-15 02:58:47 +0000457void TransferFunctions::VisitDeclStmt(DeclStmt *ds) {
458 for (DeclStmt::decl_iterator DI = ds->decl_begin(), DE = ds->decl_end();
459 DI != DE; ++DI) {
460 if (VarDecl *vd = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek4dccb902011-01-18 05:00:42 +0000461 if (isTrackedVar(vd)) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000462 if (Expr *init = vd->getInit()) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000463 // If the initializer consists solely of a reference to itself, we
464 // explicitly mark the variable as uninitialized. This allows code
465 // like the following:
466 //
467 // int x = x;
468 //
469 // to deliberately leave a variable uninitialized. Different analysis
470 // clients can detect this pattern and adjust their reporting
471 // appropriately, but we need to continue to analyze subsequent uses
472 // of the variable.
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000473 if (init == lastLoad) {
Ted Kremenekde091ae2011-08-08 21:43:08 +0000474 const DeclRefExpr *DR
475 = cast<DeclRefExpr>(stripCasts(ac.getASTContext(),
476 lastLoad->getSubExpr()));
Ted Kremenek62d126e2011-07-19 21:41:51 +0000477 if (DR->getDecl() == vd) {
478 // int x = x;
479 // Propagate uninitialized value, but don't immediately report
480 // a problem.
481 vals[vd] = Uninitialized;
482 lastLoad = 0;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000483 lastDR = 0;
Ted Kremenek62d126e2011-07-19 21:41:51 +0000484 return;
485 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000486 }
Ted Kremenek62d126e2011-07-19 21:41:51 +0000487
488 // All other cases: treat the new variable as initialized.
489 vals[vd] = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000490 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000491 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000492 }
493 }
494}
495
Ted Kremenek610068c2011-01-15 02:58:47 +0000496void TransferFunctions::VisitBinaryOperator(clang::BinaryOperator *bo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000497 if (bo->isAssignmentOp()) {
498 const FindVarResult &res = findBlockVarDecl(bo->getLHS());
Ted Kremenek9c378f72011-08-12 23:37:29 +0000499 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek496398d2011-03-15 04:57:32 +0000500 ValueVector::reference val = vals[vd];
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000501 if (isUninitialized(val)) {
Chandler Carruth84350692011-07-16 22:27:02 +0000502 if (bo->getOpcode() != BO_Assign)
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000503 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000504 else
505 val = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000506 }
507 }
508 }
509}
510
511void TransferFunctions::VisitUnaryOperator(clang::UnaryOperator *uo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000512 switch (uo->getOpcode()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000513 case clang::UO_PostDec:
514 case clang::UO_PostInc:
515 case clang::UO_PreDec:
516 case clang::UO_PreInc: {
517 const FindVarResult &res = findBlockVarDecl(uo->getSubExpr());
518 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000519 assert(res.getDeclRefExpr() == lastDR);
520 // We null out lastDR to indicate we have fully processed it
521 // and we don't want the auto-value setting in Visit().
522 lastDR = 0;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000523
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000524 ValueVector::reference val = vals[vd];
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000525 if (isUninitialized(val))
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000526 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Ted Kremenek610068c2011-01-15 02:58:47 +0000527 }
528 break;
529 }
530 default:
531 break;
532 }
533}
534
535void TransferFunctions::VisitCastExpr(clang::CastExpr *ce) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000536 if (ce->getCastKind() == CK_LValueToRValue) {
537 const FindVarResult &res = findBlockVarDecl(ce->getSubExpr());
Ted Kremenekc21fed32011-01-18 21:18:58 +0000538 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000539 assert(res.getDeclRefExpr() == lastDR);
540 if (isUninitialized(vals[vd])) {
541 // Record this load of an uninitialized value. Normally this
542 // results in a warning, but we delay reporting the issue
543 // in case it is wrapped in a void cast, etc.
544 lastLoad = ce;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000545 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000546 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000547 }
Ted Kremenekde091ae2011-08-08 21:43:08 +0000548 else if (ce->getCastKind() == CK_NoOp ||
549 ce->getCastKind() == CK_LValueBitCast) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000550 skipProcessUses = true;
551 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000552 else if (CStyleCastExpr *cse = dyn_cast<CStyleCastExpr>(ce)) {
553 if (cse->getType()->isVoidType()) {
554 // e.g. (void) x;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000555 if (lastLoad == cse->getSubExpr()) {
556 // Squelch any detected load of an uninitialized value if
557 // we cast it to void.
558 lastLoad = 0;
559 lastDR = 0;
560 }
561 }
562 }
563}
564
565void TransferFunctions::Visit(clang::Stmt *s) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000566 skipProcessUses = false;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000567 StmtVisitor<TransferFunctions>::Visit(s);
Ted Kremenek57fb5912011-08-04 22:40:57 +0000568 if (!skipProcessUses)
569 ProcessUses(s);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000570}
571
572void TransferFunctions::ProcessUses(Stmt *s) {
573 // This method is typically called after visiting a CFGElement statement
574 // in the CFG. We delay processing of reporting many loads of uninitialized
575 // values until here.
576 if (lastLoad) {
577 // If we just visited the lvalue-to-rvalue cast, there is nothing
578 // left to do.
579 if (lastLoad == s)
580 return;
581
582 // If we reach here, we have seen a load of an uninitialized value
583 // and it hasn't been casted to void or otherwise handled. In this
584 // situation, report the incident.
Ted Kremenekde091ae2011-08-08 21:43:08 +0000585 const DeclRefExpr *DR =
586 cast<DeclRefExpr>(stripCasts(ac.getASTContext(),
587 lastLoad->getSubExpr()));
588 const VarDecl *VD = cast<VarDecl>(DR->getDecl());
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000589 reportUninit(DR, VD, isAlwaysUninit(vals[VD]));
590 lastLoad = 0;
591
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000592 if (DR == lastDR) {
593 lastDR = 0;
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000594 return;
595 }
596 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000597
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000598 // Any other uses of 'lastDR' involve taking an lvalue of variable.
599 // In this case, it "escapes" the analysis.
600 if (lastDR && lastDR != s) {
601 vals[cast<VarDecl>(lastDR->getDecl())] = Initialized;
602 lastDR = 0;
Chandler Carruth86684942011-04-13 08:18:42 +0000603 }
604}
605
Ted Kremenek610068c2011-01-15 02:58:47 +0000606//------------------------------------------------------------------------====//
607// High-level "driver" logic for uninitialized values analysis.
608//====------------------------------------------------------------------------//
609
Ted Kremenek13bd4232011-01-20 17:37:17 +0000610static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000611 AnalysisContext &ac, CFGBlockValues &vals,
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000612 llvm::BitVector &wasAnalyzed,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000613 UninitVariablesHandler *handler = 0,
614 bool flagBlockUses = false) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000615
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000616 wasAnalyzed[block->getBlockID()] = true;
617
Ted Kremenek13bd4232011-01-20 17:37:17 +0000618 if (const BinaryOperator *b = getLogicalOperatorInChain(block)) {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000619 CFGBlock::const_pred_iterator itr = block->pred_begin();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000620 BVPair vA = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000621 ++itr;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000622 BVPair vB = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000623
624 BVPair valsAB;
625
626 if (b->getOpcode() == BO_LAnd) {
627 // Merge the 'F' bits from the first and second.
628 vals.mergeIntoScratch(*(vA.second ? vA.second : vA.first), true);
629 vals.mergeIntoScratch(*(vB.second ? vB.second : vB.first), false);
630 valsAB.first = vA.first;
Ted Kremenek2d4bed12011-01-20 21:25:31 +0000631 valsAB.second = &vals.getScratch();
Chad Rosier30601782011-08-17 23:08:45 +0000632 } else {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000633 // Merge the 'T' bits from the first and second.
634 assert(b->getOpcode() == BO_LOr);
635 vals.mergeIntoScratch(*vA.first, true);
636 vals.mergeIntoScratch(*vB.first, false);
637 valsAB.first = &vals.getScratch();
638 valsAB.second = vA.second ? vA.second : vA.first;
639 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000640 return vals.updateValueVectors(block, valsAB);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000641 }
642
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000643 // Default behavior: merge in values of predecessor blocks.
Ted Kremenek610068c2011-01-15 02:58:47 +0000644 vals.resetScratch();
645 bool isFirst = true;
646 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
647 E = block->pred_end(); I != E; ++I) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000648 vals.mergeIntoScratch(vals.getValueVector(*I, block), isFirst);
Ted Kremenek610068c2011-01-15 02:58:47 +0000649 isFirst = false;
650 }
651 // Apply the transfer function.
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000652 TransferFunctions tf(vals, cfg, ac, handler, flagBlockUses);
Ted Kremenek610068c2011-01-15 02:58:47 +0000653 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
654 I != E; ++I) {
655 if (const CFGStmt *cs = dyn_cast<CFGStmt>(&*I)) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000656 tf.Visit(cs->getStmt());
Ted Kremenek610068c2011-01-15 02:58:47 +0000657 }
658 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000659 tf.ProcessUses();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000660 return vals.updateValueVectorWithScratch(block);
Ted Kremenek610068c2011-01-15 02:58:47 +0000661}
662
Chandler Carruth5d989942011-07-06 16:21:37 +0000663void clang::runUninitializedVariablesAnalysis(
664 const DeclContext &dc,
665 const CFG &cfg,
666 AnalysisContext &ac,
667 UninitVariablesHandler &handler,
668 UninitVariablesAnalysisStats &stats) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000669 CFGBlockValues vals(cfg);
670 vals.computeSetOfDeclarations(dc);
671 if (vals.hasNoDeclarations())
672 return;
Ted Kremenekd40066b2011-04-04 23:29:12 +0000673
Chandler Carruth5d989942011-07-06 16:21:37 +0000674 stats.NumVariablesAnalyzed = vals.getNumEntries();
675
Ted Kremenekd40066b2011-04-04 23:29:12 +0000676 // Mark all variables uninitialized at the entry.
677 const CFGBlock &entry = cfg.getEntry();
678 for (CFGBlock::const_succ_iterator i = entry.succ_begin(),
679 e = entry.succ_end(); i != e; ++i) {
680 if (const CFGBlock *succ = *i) {
681 ValueVector &vec = vals.getValueVector(&entry, succ);
682 const unsigned n = vals.getNumEntries();
683 for (unsigned j = 0; j < n ; ++j) {
684 vec[j] = Uninitialized;
685 }
686 }
687 }
688
689 // Proceed with the workist.
Ted Kremenek610068c2011-01-15 02:58:47 +0000690 DataflowWorklist worklist(cfg);
Ted Kremenek496398d2011-03-15 04:57:32 +0000691 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
Ted Kremenek610068c2011-01-15 02:58:47 +0000692 worklist.enqueueSuccessors(&cfg.getEntry());
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000693 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
Ted Kremenek610068c2011-01-15 02:58:47 +0000694
695 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000696 // Did the block change?
Chandler Carruth5d989942011-07-06 16:21:37 +0000697 bool changed = runOnBlock(block, cfg, ac, vals, wasAnalyzed);
698 ++stats.NumBlockVisits;
Ted Kremenek610068c2011-01-15 02:58:47 +0000699 if (changed || !previouslyVisited[block->getBlockID()])
700 worklist.enqueueSuccessors(block);
701 previouslyVisited[block->getBlockID()] = true;
702 }
703
704 // Run through the blocks one more time, and report uninitialized variabes.
705 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
Chandler Carruth5d989942011-07-06 16:21:37 +0000706 if (wasAnalyzed[(*BI)->getBlockID()]) {
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000707 runOnBlock(*BI, cfg, ac, vals, wasAnalyzed, &handler,
708 /* flagBlockUses */ true);
Chandler Carruth5d989942011-07-06 16:21:37 +0000709 ++stats.NumBlockVisits;
710 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000711 }
712}
713
714UninitVariablesHandler::~UninitVariablesHandler() {}