blob: d2eaff29ac7ca3f7094eac42a7f6d46180b40d97 [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"
17#include "llvm/ADT/BitVector.h"
18#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 Kremenekafb10c42011-03-15 04:57:29 +000096class ValueVector {
97 llvm::BitVector vec;
98public:
99 ValueVector() {}
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000100 ValueVector(unsigned size) : vec(size << 1) {}
101 void resize(unsigned n) { vec.resize(n << 1); }
Ted Kremenekafb10c42011-03-15 04:57:29 +0000102 void merge(const ValueVector &rhs) { vec |= rhs.vec; }
103 bool operator!=(const ValueVector &rhs) const { return vec != rhs.vec; }
Ted Kremenekafb10c42011-03-15 04:57:29 +0000104 void reset() { vec.reset(); }
Ted Kremenek496398d2011-03-15 04:57:32 +0000105
106 class reference {
107 ValueVector &vv;
108 const unsigned idx;
109
110 reference(); // Undefined
111 public:
112 reference(ValueVector &vv, unsigned idx) : vv(vv), idx(idx) {}
113 ~reference() {}
114
115 reference &operator=(Value v) {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000116 vv.vec[idx << 1] = (((unsigned) v) & 0x1) ? true : false;
117 vv.vec[(idx << 1) | 1] = (((unsigned) v) & 0x2) ? true : false;
Ted Kremenek496398d2011-03-15 04:57:32 +0000118 return *this;
119 }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000120 operator Value() {
121 unsigned x = (vv.vec[idx << 1] ? 1 : 0) | (vv.vec[(idx << 1) | 1] ? 2 :0);
122 return (Value) x;
123 }
Ted Kremenek496398d2011-03-15 04:57:32 +0000124 };
125
126 reference operator[](unsigned idx) { return reference(*this, idx); }
Ted Kremenekafb10c42011-03-15 04:57:29 +0000127};
128
Ted Kremenek136f8f22011-03-15 04:57:27 +0000129typedef std::pair<ValueVector *, ValueVector *> BVPair;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000130
Ted Kremenek610068c2011-01-15 02:58:47 +0000131class CFGBlockValues {
132 const CFG &cfg;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000133 BVPair *vals;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000134 ValueVector scratch;
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000135 DeclToIndex declToIndex;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000136
Ted Kremenek136f8f22011-03-15 04:57:27 +0000137 ValueVector &lazyCreate(ValueVector *&bv);
Ted Kremenek610068c2011-01-15 02:58:47 +0000138public:
139 CFGBlockValues(const CFG &cfg);
140 ~CFGBlockValues();
141
Ted Kremenekd40066b2011-04-04 23:29:12 +0000142 unsigned getNumEntries() const { return declToIndex.size(); }
143
Ted Kremenek610068c2011-01-15 02:58:47 +0000144 void computeSetOfDeclarations(const DeclContext &dc);
Ted Kremenek136f8f22011-03-15 04:57:27 +0000145 ValueVector &getValueVector(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000146 const CFGBlock *dstBlock);
147
Ted Kremenek136f8f22011-03-15 04:57:27 +0000148 BVPair &getValueVectors(const CFGBlock *block, bool shouldLazyCreate);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000149
Ted Kremenek136f8f22011-03-15 04:57:27 +0000150 void mergeIntoScratch(ValueVector const &source, bool isFirst);
151 bool updateValueVectorWithScratch(const CFGBlock *block);
152 bool updateValueVectors(const CFGBlock *block, const BVPair &newVals);
Ted Kremenek610068c2011-01-15 02:58:47 +0000153
154 bool hasNoDeclarations() const {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000155 return declToIndex.size() == 0;
Ted Kremenek610068c2011-01-15 02:58:47 +0000156 }
157
Ted Kremenekb831c672011-03-29 01:40:00 +0000158 bool hasEntry(const VarDecl *vd) const {
159 return declToIndex.getValueIndex(vd).hasValue();
160 }
161
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000162 bool hasValues(const CFGBlock *block);
163
Ted Kremenek610068c2011-01-15 02:58:47 +0000164 void resetScratch();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000165 ValueVector &getScratch() { return scratch; }
Ted Kremenek13bd4232011-01-20 17:37:17 +0000166
Ted Kremenek136f8f22011-03-15 04:57:27 +0000167 ValueVector::reference operator[](const VarDecl *vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000168};
Benjamin Kramerda57f3e2011-03-26 12:38:21 +0000169} // end anonymous namespace
Ted Kremenek610068c2011-01-15 02:58:47 +0000170
171CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {
172 unsigned n = cfg.getNumBlockIDs();
173 if (!n)
174 return;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000175 vals = new std::pair<ValueVector*, ValueVector*>[n];
Francois Pichet2d78c372011-01-15 13:27:47 +0000176 memset(vals, 0, sizeof(*vals) * n);
Ted Kremenek610068c2011-01-15 02:58:47 +0000177}
178
179CFGBlockValues::~CFGBlockValues() {
180 unsigned n = cfg.getNumBlockIDs();
181 if (n == 0)
182 return;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000183 for (unsigned i = 0; i < n; ++i) {
184 delete vals[i].first;
185 delete vals[i].second;
186 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000187 delete [] vals;
188}
189
190void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000191 declToIndex.computeMap(dc);
192 scratch.resize(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000193}
194
Ted Kremenek136f8f22011-03-15 04:57:27 +0000195ValueVector &CFGBlockValues::lazyCreate(ValueVector *&bv) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000196 if (!bv)
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000197 bv = new ValueVector(declToIndex.size());
Ted Kremenek610068c2011-01-15 02:58:47 +0000198 return *bv;
199}
200
Ted Kremenek13bd4232011-01-20 17:37:17 +0000201/// This function pattern matches for a '&&' or '||' that appears at
202/// the beginning of a CFGBlock that also (1) has a terminator and
203/// (2) has no other elements. If such an expression is found, it is returned.
204static BinaryOperator *getLogicalOperatorInChain(const CFGBlock *block) {
205 if (block->empty())
206 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000207
Ted Kremenek3c0349e2011-03-01 03:15:10 +0000208 const CFGStmt *cstmt = block->front().getAs<CFGStmt>();
Ted Kremenek76709bf2011-03-15 05:22:28 +0000209 if (!cstmt)
210 return 0;
211
Ted Kremenek3c0349e2011-03-01 03:15:10 +0000212 BinaryOperator *b = llvm::dyn_cast_or_null<BinaryOperator>(cstmt->getStmt());
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000213
214 if (!b || !b->isLogicalOp())
Ted Kremenek13bd4232011-01-20 17:37:17 +0000215 return 0;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000216
217 if (block->pred_size() == 2 &&
218 ((block->succ_size() == 2 && block->getTerminatorCondition() == b) ||
219 block->size() == 1))
220 return b;
221
222 return 0;
Ted Kremenek13bd4232011-01-20 17:37:17 +0000223}
224
Ted Kremenek136f8f22011-03-15 04:57:27 +0000225ValueVector &CFGBlockValues::getValueVector(const CFGBlock *block,
226 const CFGBlock *dstBlock) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000227 unsigned idx = block->getBlockID();
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000228 if (dstBlock && getLogicalOperatorInChain(block)) {
229 if (*block->succ_begin() == dstBlock)
230 return lazyCreate(vals[idx].first);
231 assert(*(block->succ_begin()+1) == dstBlock);
232 return lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000233 }
234
235 assert(vals[idx].second == 0);
236 return lazyCreate(vals[idx].first);
237}
238
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000239bool CFGBlockValues::hasValues(const CFGBlock *block) {
240 unsigned idx = block->getBlockID();
241 return vals[idx].second != 0;
242}
243
Ted Kremenek136f8f22011-03-15 04:57:27 +0000244BVPair &CFGBlockValues::getValueVectors(const clang::CFGBlock *block,
245 bool shouldLazyCreate) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000246 unsigned idx = block->getBlockID();
247 lazyCreate(vals[idx].first);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000248 if (shouldLazyCreate)
249 lazyCreate(vals[idx].second);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000250 return vals[idx];
251}
252
Ted Kremenek136f8f22011-03-15 04:57:27 +0000253void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
Ted Kremenek610068c2011-01-15 02:58:47 +0000254 bool isFirst) {
255 if (isFirst)
256 scratch = source;
257 else
Ted Kremenekafb10c42011-03-15 04:57:29 +0000258 scratch.merge(source);
Ted Kremenek610068c2011-01-15 02:58:47 +0000259}
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000260#if 0
Ted Kremenek136f8f22011-03-15 04:57:27 +0000261static void printVector(const CFGBlock *block, ValueVector &bv,
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000262 unsigned num) {
263
264 llvm::errs() << block->getBlockID() << " :";
265 for (unsigned i = 0; i < bv.size(); ++i) {
266 llvm::errs() << ' ' << bv[i];
267 }
268 llvm::errs() << " : " << num << '\n';
269}
270#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000271
Ted Kremenek136f8f22011-03-15 04:57:27 +0000272bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
273 ValueVector &dst = getValueVector(block, 0);
Ted Kremenek610068c2011-01-15 02:58:47 +0000274 bool changed = (dst != scratch);
275 if (changed)
276 dst = scratch;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000277#if 0
278 printVector(block, scratch, 0);
279#endif
Ted Kremenek13bd4232011-01-20 17:37:17 +0000280 return changed;
281}
282
Ted Kremenek136f8f22011-03-15 04:57:27 +0000283bool CFGBlockValues::updateValueVectors(const CFGBlock *block,
Ted Kremenek13bd4232011-01-20 17:37:17 +0000284 const BVPair &newVals) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000285 BVPair &vals = getValueVectors(block, true);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000286 bool changed = *newVals.first != *vals.first ||
287 *newVals.second != *vals.second;
288 *vals.first = *newVals.first;
289 *vals.second = *newVals.second;
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000290#if 0
291 printVector(block, *vals.first, 1);
292 printVector(block, *vals.second, 2);
293#endif
Ted Kremenek610068c2011-01-15 02:58:47 +0000294 return changed;
295}
296
297void CFGBlockValues::resetScratch() {
298 scratch.reset();
299}
300
Ted Kremenek136f8f22011-03-15 04:57:27 +0000301ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
Ted Kremenek4ddb3872011-03-15 05:30:12 +0000302 const llvm::Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
Ted Kremenek610068c2011-01-15 02:58:47 +0000303 assert(idx.hasValue());
304 return scratch[idx.getValue()];
305}
306
307//------------------------------------------------------------------------====//
308// Worklist: worklist for dataflow analysis.
309//====------------------------------------------------------------------------//
310
311namespace {
312class DataflowWorklist {
313 llvm::SmallVector<const CFGBlock *, 20> worklist;
Ted Kremenek496398d2011-03-15 04:57:32 +0000314 llvm::BitVector enqueuedBlocks;
Ted Kremenek610068c2011-01-15 02:58:47 +0000315public:
316 DataflowWorklist(const CFG &cfg) : enqueuedBlocks(cfg.getNumBlockIDs()) {}
317
318 void enqueue(const CFGBlock *block);
319 void enqueueSuccessors(const CFGBlock *block);
320 const CFGBlock *dequeue();
321
322};
323}
324
325void DataflowWorklist::enqueue(const CFGBlock *block) {
Ted Kremenekc104e532011-01-18 04:53:25 +0000326 if (!block)
327 return;
Ted Kremenek610068c2011-01-15 02:58:47 +0000328 unsigned idx = block->getBlockID();
329 if (enqueuedBlocks[idx])
330 return;
331 worklist.push_back(block);
332 enqueuedBlocks[idx] = true;
333}
334
335void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
336 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
337 E = block->succ_end(); I != E; ++I) {
338 enqueue(*I);
339 }
340}
341
342const CFGBlock *DataflowWorklist::dequeue() {
343 if (worklist.empty())
344 return 0;
345 const CFGBlock *b = worklist.back();
346 worklist.pop_back();
347 enqueuedBlocks[b->getBlockID()] = false;
348 return b;
349}
350
351//------------------------------------------------------------------------====//
352// Transfer function for uninitialized values analysis.
353//====------------------------------------------------------------------------//
354
Ted Kremenek610068c2011-01-15 02:58:47 +0000355namespace {
356class FindVarResult {
357 const VarDecl *vd;
358 const DeclRefExpr *dr;
359public:
360 FindVarResult(VarDecl *vd, DeclRefExpr *dr) : vd(vd), dr(dr) {}
361
362 const DeclRefExpr *getDeclRefExpr() const { return dr; }
363 const VarDecl *getDecl() const { return vd; }
364};
365
366class TransferFunctions : public CFGRecStmtVisitor<TransferFunctions> {
367 CFGBlockValues &vals;
368 const CFG &cfg;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000369 AnalysisContext &ac;
Ted Kremenek610068c2011-01-15 02:58:47 +0000370 UninitVariablesHandler *handler;
Ted Kremenekc21fed32011-01-18 21:18:58 +0000371 const DeclRefExpr *currentDR;
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000372 const Expr *currentVoidCast;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000373 const bool flagBlockUses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000374public:
375 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000376 AnalysisContext &ac,
377 UninitVariablesHandler *handler,
378 bool flagBlockUses)
379 : vals(vals), cfg(cfg), ac(ac), handler(handler), currentDR(0),
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000380 currentVoidCast(0), flagBlockUses(flagBlockUses) {}
Ted Kremenek610068c2011-01-15 02:58:47 +0000381
382 const CFG &getCFG() { return cfg; }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000383 void reportUninit(const DeclRefExpr *ex, const VarDecl *vd,
384 bool isAlwaysUninit);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000385
386 void VisitBlockExpr(BlockExpr *be);
Ted Kremenek610068c2011-01-15 02:58:47 +0000387 void VisitDeclStmt(DeclStmt *ds);
Ted Kremenekc21fed32011-01-18 21:18:58 +0000388 void VisitDeclRefExpr(DeclRefExpr *dr);
Ted Kremenek610068c2011-01-15 02:58:47 +0000389 void VisitUnaryOperator(UnaryOperator *uo);
390 void VisitBinaryOperator(BinaryOperator *bo);
391 void VisitCastExpr(CastExpr *ce);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000392 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *se);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000393 void BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs);
Ted Kremenek40900ee2011-01-27 02:29:34 +0000394
395 bool isTrackedVar(const VarDecl *vd) {
Ted Kremenekb831c672011-03-29 01:40:00 +0000396#if 1
397 // FIXME: This is a temporary workaround to deal with the fact
398 // that DeclContext's do not always contain all of their variables!
399 return vals.hasEntry(vd);
400#else
Ted Kremenek40900ee2011-01-27 02:29:34 +0000401 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
Ted Kremenekb831c672011-03-29 01:40:00 +0000402#endif
Ted Kremenek40900ee2011-01-27 02:29:34 +0000403 }
404
405 FindVarResult findBlockVarDecl(Expr *ex);
Ted Kremenek610068c2011-01-15 02:58:47 +0000406};
407}
408
409void TransferFunctions::reportUninit(const DeclRefExpr *ex,
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000410 const VarDecl *vd, bool isAlwaysUnit) {
411 if (handler) handler->handleUseOfUninitVariable(ex, vd, isAlwaysUnit);
Ted Kremenek610068c2011-01-15 02:58:47 +0000412}
413
Ted Kremenek40900ee2011-01-27 02:29:34 +0000414FindVarResult TransferFunctions::findBlockVarDecl(Expr* ex) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000415 if (DeclRefExpr* dr = dyn_cast<DeclRefExpr>(ex->IgnoreParenCasts()))
416 if (VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
417 if (isTrackedVar(vd))
Ted Kremenek40900ee2011-01-27 02:29:34 +0000418 return FindVarResult(vd, dr);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000419 return FindVarResult(0, 0);
420}
421
422void TransferFunctions::BlockStmt_VisitObjCForCollectionStmt(
423 ObjCForCollectionStmt *fs) {
424
425 Visit(fs->getCollection());
426
427 // This represents an initialization of the 'element' value.
428 Stmt *element = fs->getElement();
429 const VarDecl* vd = 0;
430
431 if (DeclStmt* ds = dyn_cast<DeclStmt>(element)) {
432 vd = cast<VarDecl>(ds->getSingleDecl());
433 if (!isTrackedVar(vd))
434 vd = 0;
435 }
436 else {
437 // Initialize the value of the reference variable.
438 const FindVarResult &res = findBlockVarDecl(cast<Expr>(element));
439 vd = res.getDecl();
440 if (!vd) {
441 Visit(element);
442 return;
443 }
444 }
445
446 if (vd)
447 vals[vd] = Initialized;
448}
449
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000450void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
451 if (!flagBlockUses || !handler)
452 return;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000453 const BlockDecl *bd = be->getBlockDecl();
454 for (BlockDecl::capture_const_iterator i = bd->capture_begin(),
455 e = bd->capture_end() ; i != e; ++i) {
456 const VarDecl *vd = i->getVariable();
457 if (!vd->hasLocalStorage())
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000458 continue;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000459 if (!isTrackedVar(vd))
460 continue;
461 if (i->isByRef()) {
462 vals[vd] = Initialized;
463 continue;
464 }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000465 Value v = vals[vd];
466 if (isUninitialized(v))
467 handler->handleUseOfUninitVariable(be, vd, isAlwaysUninit(v));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000468 }
469}
470
Ted Kremenek610068c2011-01-15 02:58:47 +0000471void TransferFunctions::VisitDeclStmt(DeclStmt *ds) {
472 for (DeclStmt::decl_iterator DI = ds->decl_begin(), DE = ds->decl_end();
473 DI != DE; ++DI) {
474 if (VarDecl *vd = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek4dccb902011-01-18 05:00:42 +0000475 if (isTrackedVar(vd)) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000476 if (Expr *init = vd->getInit()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000477 Visit(init);
Chandler Carruthb88fb022011-04-05 21:36:30 +0000478
479 // If the initializer consists solely of a reference to itself, we
480 // explicitly mark the variable as uninitialized. This allows code
481 // like the following:
482 //
483 // int x = x;
484 //
485 // to deliberately leave a variable uninitialized. Different analysis
486 // clients can detect this pattern and adjust their reporting
487 // appropriately, but we need to continue to analyze subsequent uses
488 // of the variable.
489 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(init->IgnoreParenImpCasts());
490 vals[vd] = (DRE && DRE->getDecl() == vd) ? Uninitialized
491 : Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000492 }
Chandler Carruthb88fb022011-04-05 21:36:30 +0000493 } else if (Stmt *init = vd->getInit()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000494 Visit(init);
495 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000496 }
497 }
498}
499
Ted Kremenekc21fed32011-01-18 21:18:58 +0000500void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
501 // We assume that DeclRefExprs wrapped in an lvalue-to-rvalue cast
502 // cannot be block-level expressions. Therefore, we determine if
503 // a DeclRefExpr is involved in a "load" by comparing it to the current
504 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
505 // If a DeclRefExpr is not involved in a load, we are essentially computing
506 // its address, either for assignment to a reference or via the '&' operator.
507 // In such cases, treat the variable as being initialized, since this
508 // analysis isn't powerful enough to do alias tracking.
509 if (dr != currentDR)
510 if (const VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
511 if (isTrackedVar(vd))
512 vals[vd] = Initialized;
513}
514
Ted Kremenek610068c2011-01-15 02:58:47 +0000515void TransferFunctions::VisitBinaryOperator(clang::BinaryOperator *bo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000516 if (bo->isAssignmentOp()) {
517 const FindVarResult &res = findBlockVarDecl(bo->getLHS());
518 if (const VarDecl* vd = res.getDecl()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000519 // We assume that DeclRefExprs wrapped in a BinaryOperator "assignment"
520 // cannot be block-level expressions. Therefore, we determine if
521 // a DeclRefExpr is involved in a "load" by comparing it to the current
522 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
523 SaveAndRestore<const DeclRefExpr*> lastDR(currentDR,
524 res.getDeclRefExpr());
525 Visit(bo->getRHS());
526 Visit(bo->getLHS());
527
Ted Kremenek496398d2011-03-15 04:57:32 +0000528 ValueVector::reference val = vals[vd];
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000529 if (isUninitialized(val)) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000530 if (bo->getOpcode() != BO_Assign)
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000531 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Ted Kremenek496398d2011-03-15 04:57:32 +0000532 val = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000533 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000534 return;
Ted Kremenek610068c2011-01-15 02:58:47 +0000535 }
536 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000537 Visit(bo->getRHS());
538 Visit(bo->getLHS());
Ted Kremenek610068c2011-01-15 02:58:47 +0000539}
540
541void TransferFunctions::VisitUnaryOperator(clang::UnaryOperator *uo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000542 switch (uo->getOpcode()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000543 case clang::UO_PostDec:
544 case clang::UO_PostInc:
545 case clang::UO_PreDec:
546 case clang::UO_PreInc: {
547 const FindVarResult &res = findBlockVarDecl(uo->getSubExpr());
548 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000549 // We assume that DeclRefExprs wrapped in a unary operator ++/--
550 // cannot be block-level expressions. Therefore, we determine if
551 // a DeclRefExpr is involved in a "load" by comparing it to the current
552 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
553 SaveAndRestore<const DeclRefExpr*> lastDR(currentDR,
554 res.getDeclRefExpr());
555 Visit(uo->getSubExpr());
556
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000557 ValueVector::reference val = vals[vd];
558 if (isUninitialized(val)) {
559 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
560 // Don't cascade warnings.
561 val = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000562 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000563 return;
Ted Kremenek610068c2011-01-15 02:58:47 +0000564 }
565 break;
566 }
567 default:
568 break;
569 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000570 Visit(uo->getSubExpr());
Ted Kremenek610068c2011-01-15 02:58:47 +0000571}
572
573void TransferFunctions::VisitCastExpr(clang::CastExpr *ce) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000574 if (ce->getCastKind() == CK_LValueToRValue) {
575 const FindVarResult &res = findBlockVarDecl(ce->getSubExpr());
Ted Kremenekc21fed32011-01-18 21:18:58 +0000576 if (const VarDecl *vd = res.getDecl()) {
577 // We assume that DeclRefExprs wrapped in an lvalue-to-rvalue cast
578 // cannot be block-level expressions. Therefore, we determine if
579 // a DeclRefExpr is involved in a "load" by comparing it to the current
580 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
581 // Here we update 'currentDR' to be the one associated with this
582 // lvalue-to-rvalue cast. Then, when we analyze the DeclRefExpr, we
583 // will know that we are not computing its lvalue for other purposes
584 // than to perform a load.
585 SaveAndRestore<const DeclRefExpr*> lastDR(currentDR,
586 res.getDeclRefExpr());
587 Visit(ce->getSubExpr());
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000588 if (currentVoidCast != ce) {
589 Value val = vals[vd];
590 if (isUninitialized(val)) {
591 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
592 // Don't cascade warnings.
593 vals[vd] = Initialized;
594 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000595 }
596 return;
597 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000598 }
599 else if (CStyleCastExpr *cse = dyn_cast<CStyleCastExpr>(ce)) {
600 if (cse->getType()->isVoidType()) {
601 // e.g. (void) x;
602 SaveAndRestore<const Expr *>
603 lastVoidCast(currentVoidCast, cse->getSubExpr()->IgnoreParens());
604 Visit(cse->getSubExpr());
605 return;
606 }
607 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000608 Visit(ce->getSubExpr());
Ted Kremenek610068c2011-01-15 02:58:47 +0000609}
610
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000611void TransferFunctions::VisitUnaryExprOrTypeTraitExpr(
612 UnaryExprOrTypeTraitExpr *se) {
613 if (se->getKind() == UETT_SizeOf) {
Ted Kremenek96608032011-01-23 17:53:04 +0000614 if (se->getType()->isConstantSizeType())
615 return;
616 // Handle VLAs.
617 Visit(se->getArgumentExpr());
618 }
619}
620
Ted Kremenek610068c2011-01-15 02:58:47 +0000621//------------------------------------------------------------------------====//
622// High-level "driver" logic for uninitialized values analysis.
623//====------------------------------------------------------------------------//
624
Ted Kremenek13bd4232011-01-20 17:37:17 +0000625static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000626 AnalysisContext &ac, CFGBlockValues &vals,
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000627 llvm::BitVector &wasAnalyzed,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000628 UninitVariablesHandler *handler = 0,
629 bool flagBlockUses = false) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000630
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000631 wasAnalyzed[block->getBlockID()] = true;
632
Ted Kremenek13bd4232011-01-20 17:37:17 +0000633 if (const BinaryOperator *b = getLogicalOperatorInChain(block)) {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000634 CFGBlock::const_pred_iterator itr = block->pred_begin();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000635 BVPair vA = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000636 ++itr;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000637 BVPair vB = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000638
639 BVPair valsAB;
640
641 if (b->getOpcode() == BO_LAnd) {
642 // Merge the 'F' bits from the first and second.
643 vals.mergeIntoScratch(*(vA.second ? vA.second : vA.first), true);
644 vals.mergeIntoScratch(*(vB.second ? vB.second : vB.first), false);
645 valsAB.first = vA.first;
Ted Kremenek2d4bed12011-01-20 21:25:31 +0000646 valsAB.second = &vals.getScratch();
Ted Kremenek13bd4232011-01-20 17:37:17 +0000647 }
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000648 else {
649 // Merge the 'T' bits from the first and second.
650 assert(b->getOpcode() == BO_LOr);
651 vals.mergeIntoScratch(*vA.first, true);
652 vals.mergeIntoScratch(*vB.first, false);
653 valsAB.first = &vals.getScratch();
654 valsAB.second = vA.second ? vA.second : vA.first;
655 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000656 return vals.updateValueVectors(block, valsAB);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000657 }
658
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000659 // Default behavior: merge in values of predecessor blocks.
Ted Kremenek610068c2011-01-15 02:58:47 +0000660 vals.resetScratch();
661 bool isFirst = true;
662 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
663 E = block->pred_end(); I != E; ++I) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000664 vals.mergeIntoScratch(vals.getValueVector(*I, block), isFirst);
Ted Kremenek610068c2011-01-15 02:58:47 +0000665 isFirst = false;
666 }
667 // Apply the transfer function.
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000668 TransferFunctions tf(vals, cfg, ac, handler, flagBlockUses);
Ted Kremenek610068c2011-01-15 02:58:47 +0000669 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
670 I != E; ++I) {
671 if (const CFGStmt *cs = dyn_cast<CFGStmt>(&*I)) {
672 tf.BlockStmt_Visit(cs->getStmt());
673 }
674 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000675 return vals.updateValueVectorWithScratch(block);
Ted Kremenek610068c2011-01-15 02:58:47 +0000676}
677
678void clang::runUninitializedVariablesAnalysis(const DeclContext &dc,
679 const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000680 AnalysisContext &ac,
Ted Kremenek610068c2011-01-15 02:58:47 +0000681 UninitVariablesHandler &handler) {
682 CFGBlockValues vals(cfg);
683 vals.computeSetOfDeclarations(dc);
684 if (vals.hasNoDeclarations())
685 return;
Ted Kremenekd40066b2011-04-04 23:29:12 +0000686
687 // Mark all variables uninitialized at the entry.
688 const CFGBlock &entry = cfg.getEntry();
689 for (CFGBlock::const_succ_iterator i = entry.succ_begin(),
690 e = entry.succ_end(); i != e; ++i) {
691 if (const CFGBlock *succ = *i) {
692 ValueVector &vec = vals.getValueVector(&entry, succ);
693 const unsigned n = vals.getNumEntries();
694 for (unsigned j = 0; j < n ; ++j) {
695 vec[j] = Uninitialized;
696 }
697 }
698 }
699
700 // Proceed with the workist.
Ted Kremenek610068c2011-01-15 02:58:47 +0000701 DataflowWorklist worklist(cfg);
Ted Kremenek496398d2011-03-15 04:57:32 +0000702 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
Ted Kremenek610068c2011-01-15 02:58:47 +0000703 worklist.enqueueSuccessors(&cfg.getEntry());
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000704 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
Ted Kremenek610068c2011-01-15 02:58:47 +0000705
706 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000707 // Did the block change?
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000708 bool changed = runOnBlock(block, cfg, ac, vals, wasAnalyzed);
Ted Kremenek610068c2011-01-15 02:58:47 +0000709 if (changed || !previouslyVisited[block->getBlockID()])
710 worklist.enqueueSuccessors(block);
711 previouslyVisited[block->getBlockID()] = true;
712 }
713
714 // Run through the blocks one more time, and report uninitialized variabes.
715 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000716 if (wasAnalyzed[(*BI)->getBlockID()])
717 runOnBlock(*BI, cfg, ac, vals, wasAnalyzed, &handler,
718 /* flagBlockUses */ true);
Ted Kremenek610068c2011-01-15 02:58:47 +0000719 }
720}
721
722UninitVariablesHandler::~UninitVariablesHandler() {}
723