blob: 1d6959d81b16d2744cb0694c7f333e547211af80 [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
Ted Kremenek3c0349e2011-03-01 03:15:10 +0000181 BinaryOperator *b = llvm::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 {
286 llvm::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
339class TransferFunctions : public CFGRecStmtVisitor<TransferFunctions> {
340 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 Kremenekc21fed32011-01-18 21:18:58 +0000344 const DeclRefExpr *currentDR;
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000345 const Expr *currentVoidCast;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000346 const bool flagBlockUses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000347public:
348 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000349 AnalysisContext &ac,
350 UninitVariablesHandler *handler,
351 bool flagBlockUses)
352 : vals(vals), cfg(cfg), ac(ac), handler(handler), currentDR(0),
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000353 currentVoidCast(0), flagBlockUses(flagBlockUses) {}
Ted Kremenek610068c2011-01-15 02:58:47 +0000354
355 const CFG &getCFG() { return cfg; }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000356 void reportUninit(const DeclRefExpr *ex, const VarDecl *vd,
357 bool isAlwaysUninit);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000358
359 void VisitBlockExpr(BlockExpr *be);
Ted Kremenek610068c2011-01-15 02:58:47 +0000360 void VisitDeclStmt(DeclStmt *ds);
Ted Kremenekc21fed32011-01-18 21:18:58 +0000361 void VisitDeclRefExpr(DeclRefExpr *dr);
Ted Kremenek610068c2011-01-15 02:58:47 +0000362 void VisitUnaryOperator(UnaryOperator *uo);
363 void VisitBinaryOperator(BinaryOperator *bo);
364 void VisitCastExpr(CastExpr *ce);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000365 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *se);
Chandler Carruth86684942011-04-13 08:18:42 +0000366 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000367 void BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs);
Ted Kremenek40900ee2011-01-27 02:29:34 +0000368
369 bool isTrackedVar(const VarDecl *vd) {
370 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
371 }
372
373 FindVarResult findBlockVarDecl(Expr *ex);
Ted Kremenek610068c2011-01-15 02:58:47 +0000374};
375}
376
377void TransferFunctions::reportUninit(const DeclRefExpr *ex,
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000378 const VarDecl *vd, bool isAlwaysUnit) {
379 if (handler) handler->handleUseOfUninitVariable(ex, vd, isAlwaysUnit);
Ted Kremenek610068c2011-01-15 02:58:47 +0000380}
381
Ted Kremenek40900ee2011-01-27 02:29:34 +0000382FindVarResult TransferFunctions::findBlockVarDecl(Expr* ex) {
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000383 if (DeclRefExpr* dr = dyn_cast<DeclRefExpr>(ex->IgnoreParenCasts()))
384 if (VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
385 if (isTrackedVar(vd))
Ted Kremenek40900ee2011-01-27 02:29:34 +0000386 return FindVarResult(vd, dr);
Ted Kremenek1ea800c2011-01-27 02:01:31 +0000387 return FindVarResult(0, 0);
388}
389
390void TransferFunctions::BlockStmt_VisitObjCForCollectionStmt(
391 ObjCForCollectionStmt *fs) {
392
393 Visit(fs->getCollection());
394
395 // This represents an initialization of the 'element' value.
396 Stmt *element = fs->getElement();
397 const VarDecl* vd = 0;
398
399 if (DeclStmt* ds = dyn_cast<DeclStmt>(element)) {
400 vd = cast<VarDecl>(ds->getSingleDecl());
401 if (!isTrackedVar(vd))
402 vd = 0;
403 }
404 else {
405 // Initialize the value of the reference variable.
406 const FindVarResult &res = findBlockVarDecl(cast<Expr>(element));
407 vd = res.getDecl();
408 if (!vd) {
409 Visit(element);
410 return;
411 }
412 }
413
414 if (vd)
415 vals[vd] = Initialized;
416}
417
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000418void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
419 if (!flagBlockUses || !handler)
420 return;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000421 const BlockDecl *bd = be->getBlockDecl();
422 for (BlockDecl::capture_const_iterator i = bd->capture_begin(),
423 e = bd->capture_end() ; i != e; ++i) {
424 const VarDecl *vd = i->getVariable();
425 if (!vd->hasLocalStorage())
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000426 continue;
Ted Kremenekbc8b44c2011-03-31 22:32:41 +0000427 if (!isTrackedVar(vd))
428 continue;
429 if (i->isByRef()) {
430 vals[vd] = Initialized;
431 continue;
432 }
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000433 Value v = vals[vd];
434 if (isUninitialized(v))
435 handler->handleUseOfUninitVariable(be, vd, isAlwaysUninit(v));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000436 }
437}
438
Ted Kremenek610068c2011-01-15 02:58:47 +0000439void TransferFunctions::VisitDeclStmt(DeclStmt *ds) {
440 for (DeclStmt::decl_iterator DI = ds->decl_begin(), DE = ds->decl_end();
441 DI != DE; ++DI) {
442 if (VarDecl *vd = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek4dccb902011-01-18 05:00:42 +0000443 if (isTrackedVar(vd)) {
Chandler Carruthb88fb022011-04-05 21:36:30 +0000444 if (Expr *init = vd->getInit()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000445 Visit(init);
Chandler Carruthb88fb022011-04-05 21:36:30 +0000446
447 // If the initializer consists solely of a reference to itself, we
448 // explicitly mark the variable as uninitialized. This allows code
449 // like the following:
450 //
451 // int x = x;
452 //
453 // to deliberately leave a variable uninitialized. Different analysis
454 // clients can detect this pattern and adjust their reporting
455 // appropriately, but we need to continue to analyze subsequent uses
456 // of the variable.
457 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(init->IgnoreParenImpCasts());
458 vals[vd] = (DRE && DRE->getDecl() == vd) ? Uninitialized
459 : Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000460 }
Chandler Carruthb88fb022011-04-05 21:36:30 +0000461 } else if (Stmt *init = vd->getInit()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000462 Visit(init);
463 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000464 }
465 }
466}
467
Ted Kremenekc21fed32011-01-18 21:18:58 +0000468void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
469 // We assume that DeclRefExprs wrapped in an lvalue-to-rvalue cast
470 // cannot be block-level expressions. Therefore, we determine if
471 // a DeclRefExpr is involved in a "load" by comparing it to the current
472 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
473 // If a DeclRefExpr is not involved in a load, we are essentially computing
474 // its address, either for assignment to a reference or via the '&' operator.
475 // In such cases, treat the variable as being initialized, since this
476 // analysis isn't powerful enough to do alias tracking.
477 if (dr != currentDR)
478 if (const VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
479 if (isTrackedVar(vd))
480 vals[vd] = Initialized;
481}
482
Ted Kremenek610068c2011-01-15 02:58:47 +0000483void TransferFunctions::VisitBinaryOperator(clang::BinaryOperator *bo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000484 if (bo->isAssignmentOp()) {
485 const FindVarResult &res = findBlockVarDecl(bo->getLHS());
486 if (const VarDecl* vd = res.getDecl()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000487 // We assume that DeclRefExprs wrapped in a BinaryOperator "assignment"
488 // cannot be block-level expressions. Therefore, we determine if
489 // a DeclRefExpr is involved in a "load" by comparing it to the current
490 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
491 SaveAndRestore<const DeclRefExpr*> lastDR(currentDR,
492 res.getDeclRefExpr());
493 Visit(bo->getRHS());
494 Visit(bo->getLHS());
495
Ted Kremenek496398d2011-03-15 04:57:32 +0000496 ValueVector::reference val = vals[vd];
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000497 if (isUninitialized(val)) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000498 if (bo->getOpcode() != BO_Assign)
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000499 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
Ted Kremenek496398d2011-03-15 04:57:32 +0000500 val = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000501 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000502 return;
Ted Kremenek610068c2011-01-15 02:58:47 +0000503 }
504 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000505 Visit(bo->getRHS());
506 Visit(bo->getLHS());
Ted Kremenek610068c2011-01-15 02:58:47 +0000507}
508
509void TransferFunctions::VisitUnaryOperator(clang::UnaryOperator *uo) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000510 switch (uo->getOpcode()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000511 case clang::UO_PostDec:
512 case clang::UO_PostInc:
513 case clang::UO_PreDec:
514 case clang::UO_PreInc: {
515 const FindVarResult &res = findBlockVarDecl(uo->getSubExpr());
516 if (const VarDecl *vd = res.getDecl()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000517 // We assume that DeclRefExprs wrapped in a unary operator ++/--
518 // cannot be block-level expressions. Therefore, we determine if
519 // a DeclRefExpr is involved in a "load" by comparing it to the current
520 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
521 SaveAndRestore<const DeclRefExpr*> lastDR(currentDR,
522 res.getDeclRefExpr());
523 Visit(uo->getSubExpr());
524
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000525 ValueVector::reference val = vals[vd];
526 if (isUninitialized(val)) {
527 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
528 // Don't cascade warnings.
529 val = Initialized;
Ted Kremenek610068c2011-01-15 02:58:47 +0000530 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000531 return;
Ted Kremenek610068c2011-01-15 02:58:47 +0000532 }
533 break;
534 }
535 default:
536 break;
537 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000538 Visit(uo->getSubExpr());
Ted Kremenek610068c2011-01-15 02:58:47 +0000539}
540
541void TransferFunctions::VisitCastExpr(clang::CastExpr *ce) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000542 if (ce->getCastKind() == CK_LValueToRValue) {
543 const FindVarResult &res = findBlockVarDecl(ce->getSubExpr());
Ted Kremenekc21fed32011-01-18 21:18:58 +0000544 if (const VarDecl *vd = res.getDecl()) {
545 // We assume that DeclRefExprs wrapped in an lvalue-to-rvalue cast
546 // cannot be block-level expressions. Therefore, we determine if
547 // a DeclRefExpr is involved in a "load" by comparing it to the current
548 // DeclRefExpr found when analyzing the last lvalue-to-rvalue CastExpr.
549 // Here we update 'currentDR' to be the one associated with this
550 // lvalue-to-rvalue cast. Then, when we analyze the DeclRefExpr, we
551 // will know that we are not computing its lvalue for other purposes
552 // than to perform a load.
553 SaveAndRestore<const DeclRefExpr*> lastDR(currentDR,
554 res.getDeclRefExpr());
555 Visit(ce->getSubExpr());
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000556 if (currentVoidCast != ce) {
557 Value val = vals[vd];
558 if (isUninitialized(val)) {
559 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
560 // Don't cascade warnings.
561 vals[vd] = Initialized;
562 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000563 }
564 return;
565 }
Ted Kremenekdd0f7942011-01-26 04:49:43 +0000566 }
567 else if (CStyleCastExpr *cse = dyn_cast<CStyleCastExpr>(ce)) {
568 if (cse->getType()->isVoidType()) {
569 // e.g. (void) x;
570 SaveAndRestore<const Expr *>
571 lastVoidCast(currentVoidCast, cse->getSubExpr()->IgnoreParens());
572 Visit(cse->getSubExpr());
573 return;
574 }
575 }
Ted Kremenekc21fed32011-01-18 21:18:58 +0000576 Visit(ce->getSubExpr());
Ted Kremenek610068c2011-01-15 02:58:47 +0000577}
578
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000579void TransferFunctions::VisitUnaryExprOrTypeTraitExpr(
580 UnaryExprOrTypeTraitExpr *se) {
581 if (se->getKind() == UETT_SizeOf) {
Ted Kremenek96608032011-01-23 17:53:04 +0000582 if (se->getType()->isConstantSizeType())
583 return;
584 // Handle VLAs.
585 Visit(se->getArgumentExpr());
586 }
587}
588
Chandler Carruth86684942011-04-13 08:18:42 +0000589void TransferFunctions::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
590 // typeid(expression) is potentially evaluated when the argument is
591 // a glvalue of polymorphic type. (C++ 5.2.8p2-3)
592 if (!E->isTypeOperand() && E->Classify(ac.getASTContext()).isGLValue()) {
593 QualType SubExprTy = E->getExprOperand()->getType();
594 if (const RecordType *Record = SubExprTy->getAs<RecordType>())
595 if (cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic())
596 Visit(E->getExprOperand());
597 }
598}
599
Ted Kremenek610068c2011-01-15 02:58:47 +0000600//------------------------------------------------------------------------====//
601// High-level "driver" logic for uninitialized values analysis.
602//====------------------------------------------------------------------------//
603
Ted Kremenek13bd4232011-01-20 17:37:17 +0000604static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000605 AnalysisContext &ac, CFGBlockValues &vals,
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000606 llvm::BitVector &wasAnalyzed,
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000607 UninitVariablesHandler *handler = 0,
608 bool flagBlockUses = false) {
Ted Kremenek13bd4232011-01-20 17:37:17 +0000609
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000610 wasAnalyzed[block->getBlockID()] = true;
611
Ted Kremenek13bd4232011-01-20 17:37:17 +0000612 if (const BinaryOperator *b = getLogicalOperatorInChain(block)) {
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000613 CFGBlock::const_pred_iterator itr = block->pred_begin();
Ted Kremenek136f8f22011-03-15 04:57:27 +0000614 BVPair vA = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000615 ++itr;
Ted Kremenek136f8f22011-03-15 04:57:27 +0000616 BVPair vB = vals.getValueVectors(*itr, false);
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000617
618 BVPair valsAB;
619
620 if (b->getOpcode() == BO_LAnd) {
621 // Merge the 'F' bits from the first and second.
622 vals.mergeIntoScratch(*(vA.second ? vA.second : vA.first), true);
623 vals.mergeIntoScratch(*(vB.second ? vB.second : vB.first), false);
624 valsAB.first = vA.first;
Ted Kremenek2d4bed12011-01-20 21:25:31 +0000625 valsAB.second = &vals.getScratch();
Ted Kremenek13bd4232011-01-20 17:37:17 +0000626 }
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000627 else {
628 // Merge the 'T' bits from the first and second.
629 assert(b->getOpcode() == BO_LOr);
630 vals.mergeIntoScratch(*vA.first, true);
631 vals.mergeIntoScratch(*vB.first, false);
632 valsAB.first = &vals.getScratch();
633 valsAB.second = vA.second ? vA.second : vA.first;
634 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000635 return vals.updateValueVectors(block, valsAB);
Ted Kremenek13bd4232011-01-20 17:37:17 +0000636 }
637
Ted Kremenek9fcbcee2011-02-01 17:43:18 +0000638 // Default behavior: merge in values of predecessor blocks.
Ted Kremenek610068c2011-01-15 02:58:47 +0000639 vals.resetScratch();
640 bool isFirst = true;
641 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
642 E = block->pred_end(); I != E; ++I) {
Ted Kremenek136f8f22011-03-15 04:57:27 +0000643 vals.mergeIntoScratch(vals.getValueVector(*I, block), isFirst);
Ted Kremenek610068c2011-01-15 02:58:47 +0000644 isFirst = false;
645 }
646 // Apply the transfer function.
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000647 TransferFunctions tf(vals, cfg, ac, handler, flagBlockUses);
Ted Kremenek610068c2011-01-15 02:58:47 +0000648 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
649 I != E; ++I) {
650 if (const CFGStmt *cs = dyn_cast<CFGStmt>(&*I)) {
651 tf.BlockStmt_Visit(cs->getStmt());
652 }
653 }
Ted Kremenek136f8f22011-03-15 04:57:27 +0000654 return vals.updateValueVectorWithScratch(block);
Ted Kremenek610068c2011-01-15 02:58:47 +0000655}
656
Chandler Carruth5d989942011-07-06 16:21:37 +0000657void clang::runUninitializedVariablesAnalysis(
658 const DeclContext &dc,
659 const CFG &cfg,
660 AnalysisContext &ac,
661 UninitVariablesHandler &handler,
662 UninitVariablesAnalysisStats &stats) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000663 CFGBlockValues vals(cfg);
664 vals.computeSetOfDeclarations(dc);
665 if (vals.hasNoDeclarations())
666 return;
Ted Kremenekd40066b2011-04-04 23:29:12 +0000667
Chandler Carruth5d989942011-07-06 16:21:37 +0000668 stats.NumVariablesAnalyzed = vals.getNumEntries();
669
Ted Kremenekd40066b2011-04-04 23:29:12 +0000670 // Mark all variables uninitialized at the entry.
671 const CFGBlock &entry = cfg.getEntry();
672 for (CFGBlock::const_succ_iterator i = entry.succ_begin(),
673 e = entry.succ_end(); i != e; ++i) {
674 if (const CFGBlock *succ = *i) {
675 ValueVector &vec = vals.getValueVector(&entry, succ);
676 const unsigned n = vals.getNumEntries();
677 for (unsigned j = 0; j < n ; ++j) {
678 vec[j] = Uninitialized;
679 }
680 }
681 }
682
683 // Proceed with the workist.
Ted Kremenek610068c2011-01-15 02:58:47 +0000684 DataflowWorklist worklist(cfg);
Ted Kremenek496398d2011-03-15 04:57:32 +0000685 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
Ted Kremenek610068c2011-01-15 02:58:47 +0000686 worklist.enqueueSuccessors(&cfg.getEntry());
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000687 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
Ted Kremenek610068c2011-01-15 02:58:47 +0000688
689 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek610068c2011-01-15 02:58:47 +0000690 // Did the block change?
Chandler Carruth5d989942011-07-06 16:21:37 +0000691 bool changed = runOnBlock(block, cfg, ac, vals, wasAnalyzed);
692 ++stats.NumBlockVisits;
Ted Kremenek610068c2011-01-15 02:58:47 +0000693 if (changed || !previouslyVisited[block->getBlockID()])
694 worklist.enqueueSuccessors(block);
695 previouslyVisited[block->getBlockID()] = true;
696 }
697
698 // Run through the blocks one more time, and report uninitialized variabes.
699 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
Chandler Carruth5d989942011-07-06 16:21:37 +0000700 if (wasAnalyzed[(*BI)->getBlockID()]) {
Ted Kremenekf8adeef2011-04-04 20:30:58 +0000701 runOnBlock(*BI, cfg, ac, vals, wasAnalyzed, &handler,
702 /* flagBlockUses */ true);
Chandler Carruth5d989942011-07-06 16:21:37 +0000703 ++stats.NumBlockVisits;
704 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000705 }
706}
707
708UninitVariablesHandler::~UninitVariablesHandler() {}