blob: 009922ae92c4a22a8fcb4e0c44d1640ead9c4261 [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 }
126
Ted Kremenekb831c672011-03-29 01:40:00 +0000127 bool hasEntry(const VarDecl *vd) const {
128 return declToIndex.getValueIndex(vd).hasValue();
129 }
130
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000131 bool hasValues(const CFGBlock *block);
132
Ted Kremenek610068c2011-01-15 02:58:47 +0000133 void resetScratch();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000134 ValueVector &getScratch() { return scratch; }
Ted Kremenek13bd4232011-01-20 17:37:17 +0000135
Ted Kremenek136f8f22011-03-15 04:57:27 +0000136 ValueVector::reference operator[](const VarDecl *vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000137};
Benjamin Kramerda57f3e2011-03-26 12:38:21 +0000138} // end anonymous namespace
Ted Kremenek610068c2011-01-15 02:58:47 +0000139
140CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {
141 unsigned n = cfg.getNumBlockIDs();
142 if (!n)
143 return;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000144 vals = new std::pair<ValueVector*, ValueVector*>[n];
Chandler Carruth75c40642011-04-28 08:19:45 +0000145 memset((void*)vals, 0, sizeof(*vals) * n);
Ted Kremenek610068c2011-01-15 02:58:47 +0000146}
147
148CFGBlockValues::~CFGBlockValues() {
149 unsigned n = cfg.getNumBlockIDs();
150 if (n == 0)
151 return;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000152 for (unsigned i = 0; i < n; ++i) {
153 delete vals[i].first;
154 delete vals[i].second;
155 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000156 delete [] vals;
157}
158
159void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000160 declToIndex.computeMap(dc);
161 scratch.resize(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000162}
163
Ted Kremenek136f8f22011-03-15 04:57:27 +0000164ValueVector &CFGBlockValues::lazyCreate(ValueVector *&bv) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000165 if (!bv)
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000166 bv = new ValueVector(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000167 return *bv;
168}
169
Ted Kremenek13bd4232011-01-20 17:37:17 +0000170/// This function pattern matches for a '&&' or '||' that appears at
171/// the beginning of a CFGBlock that also (1) has a terminator and
172/// (2) has no other elements. If such an expression is found, it is returned.
173static BinaryOperator *getLogicalOperatorInChain(const CFGBlock *block) {
174 if (block->empty())
175 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000176
Ted Kremenek3c0349e2011-03-01 03:15:10 +0000177 const CFGStmt *cstmt = block->front().getAs<CFGStmt>();
Ted Kremenek76709bf2011-03-15 05:22:28 +0000178 if (!cstmt)
179 return 0;
180
Chris Lattner5f9e2722011-07-23 10:55:15 +0000181 BinaryOperator *b = dyn_cast_or_null<BinaryOperator>(cstmt->getStmt());
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000182
183 if (!b || !b->isLogicalOp())
Ted Kremenek13bd4232011-01-20 17:37:17 +0000184 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000185
Ted Kremeneke6c28032011-05-10 22:10:35 +0000186 if (block->pred_size() == 2) {
187 if (block->getTerminatorCondition() == b) {
188 if (block->succ_size() == 2)
189 return b;
190 }
191 else if (block->size() == 1)
192 return b;
193 }
194
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000195 return 0;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000196}
197
Ted Kremenek136f8f22011-03-15 04:57:27 +0000198ValueVector &CFGBlockValues::getValueVector(const CFGBlock *block,
199 const CFGBlock *dstBlock) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000200 unsigned idx = block->getBlockID();
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000201 if (dstBlock && getLogicalOperatorInChain(block)) {
202 if (*block->succ_begin() == dstBlock)
203 return lazyCreate(vals[idx].first);
204 assert(*(block->succ_begin()+1) == dstBlock);
205 return lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000206 }
207
208 assert(vals[idx].second == 0);
209 return lazyCreate(vals[idx].first);
210}
211
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000212bool CFGBlockValues::hasValues(const CFGBlock *block) {
213 unsigned idx = block->getBlockID();
214 return vals[idx].second != 0;
215}
216
Ted Kremenek136f8f22011-03-15 04:57:27 +0000217BVPair &CFGBlockValues::getValueVectors(const clang::CFGBlock *block,
218 bool shouldLazyCreate) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000219 unsigned idx = block->getBlockID();
220 lazyCreate(vals[idx].first);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000221 if (shouldLazyCreate)
222 lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000223 return vals[idx];
224}
225
Ted Kremenek136f8f22011-03-15 04:57:27 +0000226void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
Ted Kremenek610068c2011-01-15 02:58:47 +0000227 bool isFirst) {
228 if (isFirst)
229 scratch = source;
230 else
Argyrios Kyrtzidis049f6d02011-05-31 03:56:09 +0000231 scratch |= source;
Ted Kremenek610068c2011-01-15 02:58:47 +0000232}
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000233#if 0
Ted Kremenek136f8f22011-03-15 04:57:27 +0000234static void printVector(const CFGBlock *block, ValueVector &bv,
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000235 unsigned num) {
236
237 llvm::errs() << block->getBlockID() << " :";
238 for (unsigned i = 0; i < bv.size(); ++i) {
239 llvm::errs() << ' ' << bv[i];
240 }
241 llvm::errs() << " : " << num << '\n';
242}
243#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000244
Ted Kremenek136f8f22011-03-15 04:57:27 +0000245bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
246 ValueVector &dst = getValueVector(block, 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000247 bool changed = (dst != scratch);
248 if (changed)
249 dst = scratch;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000250#if 0
251 printVector(block, scratch, 0);
252#endif
Ted Kremenek13bd4232011-01-20 17:37:17 +0000253 return changed;
254}
255
Ted Kremenek136f8f22011-03-15 04:57:27 +0000256bool CFGBlockValues::updateValueVectors(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000257 const BVPair &newVals) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000258 BVPair &vals = getValueVectors(block, true);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000259 bool changed = *newVals.first != *vals.first ||
260 *newVals.second != *vals.second;
261 *vals.first = *newVals.first;
262 *vals.second = *newVals.second;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000263#if 0
264 printVector(block, *vals.first, 1);
265 printVector(block, *vals.second, 2);
266#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000267 return changed;
268}
269
270void CFGBlockValues::resetScratch() {
271 scratch.reset();
272}
273
Ted Kremenek136f8f22011-03-15 04:57:27 +0000274ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000275 const llvm::Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000276 assert(idx.hasValue());
277 return scratch[idx.getValue()];
278}
279
280//------------------------------------------------------------------------====//
281// Worklist: worklist for dataflow analysis.
282//====------------------------------------------------------------------------//
283
284namespace {
285class DataflowWorklist {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000286 SmallVector<const CFGBlock *, 20> worklist;
Ted Kremenek496398d2011-03-15 04:57:32 +0000287 llvm::BitVector enqueuedBlocks;
Ted Kremenek610068c2011-01-15 02:58:47 +0000288public:
289 DataflowWorklist(const CFG &cfg) : enqueuedBlocks(cfg.getNumBlockIDs()) {}
290
Ted Kremenek610068c2011-01-15 02:58:47 +0000291 void enqueueSuccessors(const CFGBlock *block);
292 const CFGBlock *dequeue();
Ted Kremenek610068c2011-01-15 02:58:47 +0000293};
294}
295
Ted Kremenek610068c2011-01-15 02:58:47 +0000296void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
Chandler Carruth80520502011-07-08 11:19:06 +0000297 unsigned OldWorklistSize = worklist.size();
Ted Kremenek610068c2011-01-15 02:58:47 +0000298 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
299 E = block->succ_end(); I != E; ++I) {
Chandler Carruth80520502011-07-08 11:19:06 +0000300 const CFGBlock *Successor = *I;
301 if (!Successor || enqueuedBlocks[Successor->getBlockID()])
302 continue;
303 worklist.push_back(Successor);
304 enqueuedBlocks[Successor->getBlockID()] = true;
Ted Kremenek610068c2011-01-15 02:58:47 +0000305 }
Chandler Carruth80520502011-07-08 11:19:06 +0000306 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
307 return;
308
309 // Rotate the newly added blocks to the start of the worklist so that it forms
310 // a proper queue when we pop off the end of the worklist.
311 std::rotate(worklist.begin(), worklist.begin() + OldWorklistSize,
312 worklist.end());
Ted Kremenek610068c2011-01-15 02:58:47 +0000313}
314
315const CFGBlock *DataflowWorklist::dequeue() {
316 if (worklist.empty())
317 return 0;
318 const CFGBlock *b = worklist.back();
319 worklist.pop_back();
320 enqueuedBlocks[b->getBlockID()] = false;
321 return b;
322}
323
324//------------------------------------------------------------------------====//
325// Transfer function for uninitialized values analysis.
326//====------------------------------------------------------------------------//
327
Ted Kremenek610068c2011-01-15 02:58:47 +0000328namespace {
329class FindVarResult {
330 const VarDecl *vd;
331 const DeclRefExpr *dr;
332public:
333 FindVarResult(VarDecl *vd, DeclRefExpr *dr) : vd(vd), dr(dr) {}
334
335 const DeclRefExpr *getDeclRefExpr() const { return dr; }
336 const VarDecl *getDecl() const { return vd; }
337};
338
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000339class TransferFunctions : public StmtVisitor<TransferFunctions> {
Ted Kremenek610068c2011-01-15 02:58:47 +0000340 CFGBlockValues &vals;
341 const CFG &cfg;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000342 AnalysisContext &ac;
Ted Kremenek610068c2011-01-15 02:58:47 +0000343 UninitVariablesHandler *handler;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000344 const bool flagBlockUses;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000345
346 /// The last DeclRefExpr seen when analyzing a block. Used to
347 /// cheat when detecting cases when the address of a variable is taken.
348 DeclRefExpr *lastDR;
349
350 /// The last lvalue-to-rvalue conversion of a variable whose value
351 /// was uninitialized. Normally this results in a warning, but it is
352 /// possible to either silence the warning in some cases, or we
353 /// propagate the uninitialized value.
354 CastExpr *lastLoad;
Ted Kremenek57fb5912011-08-04 22:40:57 +0000355
356 /// For some expressions, we want to ignore any post-processing after
357 /// visitation.
358 bool skipProcessUses;
359
Ted Kremenek610068c2011-01-15 02:58:47 +0000360public:
361 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000362 AnalysisContext &ac,
363 UninitVariablesHandler *handler,
364 bool flagBlockUses)
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000365 : vals(vals), cfg(cfg), ac(ac), handler(handler),
Ted Kremenek57fb5912011-08-04 22:40:57 +0000366 flagBlockUses(flagBlockUses), lastDR(0), lastLoad(0),
367 skipProcessUses(false) {}
Ted Kremenek610068c2011-01-15 02:58:47 +0000368
369 const CFG &getCFG() { return cfg; }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000370 void reportUninit(const DeclRefExpr *ex, const VarDecl *vd,
371 bool isAlwaysUninit);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000372
373 void VisitBlockExpr(BlockExpr *be);
Ted Kremenek610068c2011-01-15 02:58:47 +0000374 void VisitDeclStmt(DeclStmt *ds);
Ted Kremenekc21fed32011-01-18 21:18:58 +0000375 void VisitDeclRefExpr(DeclRefExpr *dr);
Ted Kremenek610068c2011-01-15 02:58:47 +0000376 void VisitUnaryOperator(UnaryOperator *uo);
377 void VisitBinaryOperator(BinaryOperator *bo);
378 void VisitCastExpr(CastExpr *ce);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000379 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs);
380 void Visit(Stmt *s);
Ted Kremenek40900ee2011-01-27 02:29:34 +0000381
382 bool isTrackedVar(const VarDecl *vd) {
383 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
384 }
385
386 FindVarResult findBlockVarDecl(Expr *ex);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000387
388 void ProcessUses(Stmt *s = 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000389};
390}
391
392void TransferFunctions::reportUninit(const DeclRefExpr *ex,
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000393 const VarDecl *vd, bool isAlwaysUnit) {
394 if (handler) handler->handleUseOfUninitVariable(ex, vd, isAlwaysUnit);
Ted Kremenek610068c2011-01-15 02:58:47 +0000395}
396
Ted Kremenek40900ee2011-01-27 02:29:34 +0000397FindVarResult TransferFunctions::findBlockVarDecl(Expr* ex) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000398 if (DeclRefExpr* dr = dyn_cast<DeclRefExpr>(ex->IgnoreParenCasts()))
399 if (VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
400 if (isTrackedVar(vd))
Ted Kremenek40900ee2011-01-27 02:29:34 +0000401 return FindVarResult(vd, dr);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000402 return FindVarResult(0, 0);
403}
404
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000405void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000406 // This represents an initialization of the 'element' value.
407 Stmt *element = fs->getElement();
408 const VarDecl* vd = 0;
409
410 if (DeclStmt* ds = dyn_cast<DeclStmt>(element)) {
411 vd = cast<VarDecl>(ds->getSingleDecl());
412 if (!isTrackedVar(vd))
413 vd = 0;
414 }
415 else {
416 // Initialize the value of the reference variable.
417 const FindVarResult &res = findBlockVarDecl(cast<Expr>(element));
418 vd = res.getDecl();
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000419 }
420
421 if (vd)
422 vals[vd] = Initialized;
423}
424
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000425void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
426 if (!flagBlockUses || !handler)
427 return;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000428 const BlockDecl *bd = be->getBlockDecl();
429 for (BlockDecl::capture_const_iterator i = bd->capture_begin(),
430 e = bd->capture_end() ; i != e; ++i) {
431 const VarDecl *vd = i->getVariable();
432 if (!vd->hasLocalStorage())
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000433 continue;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000434 if (!isTrackedVar(vd))
435 continue;
436 if (i->isByRef()) {
437 vals[vd] = Initialized;
438 continue;
439 }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000440 Value v = vals[vd];
441 if (isUninitialized(v))
442 handler->handleUseOfUninitVariable(be, vd, isAlwaysUninit(v));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000443 }
444}
445
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000446void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
447 // Record the last DeclRefExpr seen. This is an lvalue computation.
448 // We use this value to later detect if a variable "escapes" the analysis.
449 if (const VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000450 if (isTrackedVar(vd)) {
451 ProcessUses();
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000452 lastDR = dr;
Ted Kremenekdd4286b2011-07-20 19:49:47 +0000453 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000454}
455
Ted Kremenek610068c2011-01-15 02:58:47 +0000456void TransferFunctions::VisitDeclStmt(DeclStmt *ds) {
457 for (DeclStmt::decl_iterator DI = ds->decl_begin(), DE = ds->decl_end();
458 DI != DE; ++DI) {
459 if (VarDecl *vd = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek4dccb902011-01-18 05:00:42 +0000460 if (isTrackedVar(vd)) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000461 if (Expr *init = vd->getInit()) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000462 // If the initializer consists solely of a reference to itself, we
463 // explicitly mark the variable as uninitialized. This allows code
464 // like the following:
465 //
466 // int x = x;
467 //
468 // to deliberately leave a variable uninitialized. Different analysis
469 // clients can detect this pattern and adjust their reporting
470 // appropriately, but we need to continue to analyze subsequent uses
471 // of the variable.
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000472 if (init == lastLoad) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000473 DeclRefExpr *DR
474 = cast<DeclRefExpr>(lastLoad->
475 getSubExpr()->IgnoreParenNoopCasts(ac.getASTContext()));
Ted Kremenek62d126e2011-07-19 21:41:51 +0000476 if (DR->getDecl() == vd) {
477 // int x = x;
478 // Propagate uninitialized value, but don't immediately report
479 // a problem.
480 vals[vd] = Uninitialized;
481 lastLoad = 0;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000482 lastDR = 0;
Ted Kremenek62d126e2011-07-19 21:41:51 +0000483 return;
484 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000485 }
Ted Kremenek62d126e2011-07-19 21:41:51 +0000486
487 // All other cases: treat the new variable as initialized.
488 vals[vd] = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000489 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000490 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000491 }
492 }
493}
494
Ted Kremenek610068c2011-01-15 02:58:47 +0000495void TransferFunctions::VisitBinaryOperator(clang::BinaryOperator *bo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000496 if (bo->isAssignmentOp()) {
497 const FindVarResult &res = findBlockVarDecl(bo->getLHS());
498 if (const VarDecl* vd = res.getDecl()) {
Ted Kremenek496398d2011-03-15 04:57:32 +0000499 ValueVector::reference val = vals[vd];
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000500 if (isUninitialized(val)) {
Chandler Carruth84350692011-07-16 22:27:02 +0000501 if (bo->getOpcode() != BO_Assign)
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000502 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000503 else
504 val = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000505 }
506 }
507 }
508}
509
510void TransferFunctions::VisitUnaryOperator(clang::UnaryOperator *uo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000511 switch (uo->getOpcode()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000512 case clang::UO_PostDec:
513 case clang::UO_PostInc:
514 case clang::UO_PreDec:
515 case clang::UO_PreInc: {
516 const FindVarResult &res = findBlockVarDecl(uo->getSubExpr());
517 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000518 assert(res.getDeclRefExpr() == lastDR);
519 // We null out lastDR to indicate we have fully processed it
520 // and we don't want the auto-value setting in Visit().
521 lastDR = 0;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000522
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000523 ValueVector::reference val = vals[vd];
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000524 if (isUninitialized(val))
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000525 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Ted Kremenek610068c2011-01-15 02:58:47 +0000526 }
527 break;
528 }
529 default:
530 break;
531 }
532}
533
534void TransferFunctions::VisitCastExpr(clang::CastExpr *ce) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000535 if (ce->getCastKind() == CK_LValueToRValue) {
536 const FindVarResult &res = findBlockVarDecl(ce->getSubExpr());
Ted Kremenekc21fed32011-01-18 21:18:58 +0000537 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000538 assert(res.getDeclRefExpr() == lastDR);
539 if (isUninitialized(vals[vd])) {
540 // Record this load of an uninitialized value. Normally this
541 // results in a warning, but we delay reporting the issue
542 // in case it is wrapped in a void cast, etc.
543 lastLoad = ce;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000544 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000545 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000546 }
Ted Kremenek57fb5912011-08-04 22:40:57 +0000547 else if (ce->getCastKind() == CK_NoOp) {
548 skipProcessUses = true;
549 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000550 else if (CStyleCastExpr *cse = dyn_cast<CStyleCastExpr>(ce)) {
551 if (cse->getType()->isVoidType()) {
552 // e.g. (void) x;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000553 if (lastLoad == cse->getSubExpr()) {
554 // Squelch any detected load of an uninitialized value if
555 // we cast it to void.
556 lastLoad = 0;
557 lastDR = 0;
558 }
559 }
560 }
561}
562
563void TransferFunctions::Visit(clang::Stmt *s) {
Ted Kremenek57fb5912011-08-04 22:40:57 +0000564 skipProcessUses = false;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000565 StmtVisitor<TransferFunctions>::Visit(s);
Ted Kremenek57fb5912011-08-04 22:40:57 +0000566 if (!skipProcessUses)
567 ProcessUses(s);
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000568}
569
570void TransferFunctions::ProcessUses(Stmt *s) {
571 // This method is typically called after visiting a CFGElement statement
572 // in the CFG. We delay processing of reporting many loads of uninitialized
573 // values until here.
574 if (lastLoad) {
575 // If we just visited the lvalue-to-rvalue cast, there is nothing
576 // left to do.
577 if (lastLoad == s)
578 return;
579
580 // If we reach here, we have seen a load of an uninitialized value
581 // and it hasn't been casted to void or otherwise handled. In this
582 // situation, report the incident.
Ted Kremenek57fb5912011-08-04 22:40:57 +0000583 DeclRefExpr *DR =
584 cast<DeclRefExpr>(lastLoad->getSubExpr()->
585 IgnoreParenNoopCasts(ac.getASTContext()));
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000586 VarDecl *VD = cast<VarDecl>(DR->getDecl());
587 reportUninit(DR, VD, isAlwaysUninit(vals[VD]));
588 lastLoad = 0;
589
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000590 if (DR == lastDR) {
591 lastDR = 0;
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000592 return;
593 }
594 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000595
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000596 // Any other uses of 'lastDR' involve taking an lvalue of variable.
597 // In this case, it "escapes" the analysis.
598 if (lastDR && lastDR != s) {
599 vals[cast<VarDecl>(lastDR->getDecl())] = Initialized;
600 lastDR = 0;
Chandler Carruth86684942011-04-13 08:18:42 +0000601 }
602}
603
Ted Kremenek610068c2011-01-15 02:58:47 +0000604//------------------------------------------------------------------------====//
605// High-level "driver" logic for uninitialized values analysis.
606//====------------------------------------------------------------------------//
607
Ted Kremenek13bd4232011-01-20 17:37:17 +0000608static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000609 AnalysisContext &ac, CFGBlockValues &vals,
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000610 llvm::BitVector &wasAnalyzed,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000611 UninitVariablesHandler *handler = 0,
612 bool flagBlockUses = false) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000613
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000614 wasAnalyzed[block->getBlockID()] = true;
615
Ted Kremenek13bd4232011-01-20 17:37:17 +0000616 if (const BinaryOperator *b = getLogicalOperatorInChain(block)) {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000617 CFGBlock::const_pred_iterator itr = block->pred_begin();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000618 BVPair vA = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000619 ++itr;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000620 BVPair vB = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000621
622 BVPair valsAB;
623
624 if (b->getOpcode() == BO_LAnd) {
625 // Merge the 'F' bits from the first and second.
626 vals.mergeIntoScratch(*(vA.second ? vA.second : vA.first), true);
627 vals.mergeIntoScratch(*(vB.second ? vB.second : vB.first), false);
628 valsAB.first = vA.first;
Ted Kremenek2d4bed12011-01-20 21:25:31 +0000629 valsAB.second = &vals.getScratch();
Ted Kremenek13bd4232011-01-20 17:37:17 +0000630 }
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000631 else {
632 // Merge the 'T' bits from the first and second.
633 assert(b->getOpcode() == BO_LOr);
634 vals.mergeIntoScratch(*vA.first, true);
635 vals.mergeIntoScratch(*vB.first, false);
636 valsAB.first = &vals.getScratch();
637 valsAB.second = vA.second ? vA.second : vA.first;
638 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000639 return vals.updateValueVectors(block, valsAB);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000640 }
641
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000642 // Default behavior: merge in values of predecessor blocks.
Ted Kremenek610068c2011-01-15 02:58:47 +0000643 vals.resetScratch();
644 bool isFirst = true;
645 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
646 E = block->pred_end(); I != E; ++I) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000647 vals.mergeIntoScratch(vals.getValueVector(*I, block), isFirst);
Ted Kremenek610068c2011-01-15 02:58:47 +0000648 isFirst = false;
649 }
650 // Apply the transfer function.
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000651 TransferFunctions tf(vals, cfg, ac, handler, flagBlockUses);
Ted Kremenek610068c2011-01-15 02:58:47 +0000652 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
653 I != E; ++I) {
654 if (const CFGStmt *cs = dyn_cast<CFGStmt>(&*I)) {
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000655 tf.Visit(cs->getStmt());
Ted Kremenek610068c2011-01-15 02:58:47 +0000656 }
657 }
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000658 tf.ProcessUses();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000659 return vals.updateValueVectorWithScratch(block);
Ted Kremenek610068c2011-01-15 02:58:47 +0000660}
661
Chandler Carruth5d989942011-07-06 16:21:37 +0000662void clang::runUninitializedVariablesAnalysis(
663 const DeclContext &dc,
664 const CFG &cfg,
665 AnalysisContext &ac,
666 UninitVariablesHandler &handler,
667 UninitVariablesAnalysisStats &stats) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000668 CFGBlockValues vals(cfg);
669 vals.computeSetOfDeclarations(dc);
670 if (vals.hasNoDeclarations())
671 return;
Ted Kremenekd40066b2011-04-04 23:29:12 +0000672
Chandler Carruth5d989942011-07-06 16:21:37 +0000673 stats.NumVariablesAnalyzed = vals.getNumEntries();
674
Ted Kremenekd40066b2011-04-04 23:29:12 +0000675 // Mark all variables uninitialized at the entry.
676 const CFGBlock &entry = cfg.getEntry();
677 for (CFGBlock::const_succ_iterator i = entry.succ_begin(),
678 e = entry.succ_end(); i != e; ++i) {
679 if (const CFGBlock *succ = *i) {
680 ValueVector &vec = vals.getValueVector(&entry, succ);
681 const unsigned n = vals.getNumEntries();
682 for (unsigned j = 0; j < n ; ++j) {
683 vec[j] = Uninitialized;
684 }
685 }
686 }
687
688 // Proceed with the workist.
Ted Kremenek610068c2011-01-15 02:58:47 +0000689 DataflowWorklist worklist(cfg);
Ted Kremenek496398d2011-03-15 04:57:32 +0000690 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
Ted Kremenek610068c2011-01-15 02:58:47 +0000691 worklist.enqueueSuccessors(&cfg.getEntry());
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000692 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
Ted Kremenek610068c2011-01-15 02:58:47 +0000693
694 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000695 // Did the block change?
Chandler Carruth5d989942011-07-06 16:21:37 +0000696 bool changed = runOnBlock(block, cfg, ac, vals, wasAnalyzed);
697 ++stats.NumBlockVisits;
Ted Kremenek610068c2011-01-15 02:58:47 +0000698 if (changed || !previouslyVisited[block->getBlockID()])
699 worklist.enqueueSuccessors(block);
700 previouslyVisited[block->getBlockID()] = true;
701 }
702
703 // Run through the blocks one more time, and report uninitialized variabes.
704 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
Chandler Carruth5d989942011-07-06 16:21:37 +0000705 if (wasAnalyzed[(*BI)->getBlockID()]) {
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000706 runOnBlock(*BI, cfg, ac, vals, wasAnalyzed, &handler,
707 /* flagBlockUses */ true);
Chandler Carruth5d989942011-07-06 16:21:37 +0000708 ++stats.NumBlockVisits;
709 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000710 }
711}
712
713UninitVariablesHandler::~UninitVariablesHandler() {}