1 //==- UninitializedValues.cpp - Find Uninitialized Values -------*- C++ --*-==//
2 //
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
14 #include <utility>
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/PackedVector.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/Analysis/CFG.h"
21 #include "clang/Analysis/AnalysisContext.h"
22 #include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
23 #include "clang/Analysis/Analyses/UninitializedValues.h"
24 #include "clang/Analysis/Support/SaveAndRestore.h"
25
26 using namespace clang;
27
isTrackedVar(const VarDecl * vd,const DeclContext * dc)28 static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) {
29 if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() &&
30 !vd->isExceptionVariable() &&
31 vd->getDeclContext() == dc) {
32 QualType ty = vd->getType();
33 return ty->isScalarType() || ty->isVectorType();
34 }
35 return false;
36 }
37
38 //------------------------------------------------------------------------====//
39 // DeclToIndex: a mapping from Decls we track to value indices.
40 //====------------------------------------------------------------------------//
41
42 namespace {
43 class DeclToIndex {
44 llvm::DenseMap<const VarDecl *, unsigned> map;
45 public:
DeclToIndex()46 DeclToIndex() {}
47
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.
size() const52 unsigned size() const { return map.size(); }
53
54 /// Returns the bit vector index for a given declaration.
55 llvm::Optional<unsigned> getValueIndex(const VarDecl *d) const;
56 };
57 }
58
computeMap(const DeclContext & dc)59 void DeclToIndex::computeMap(const DeclContext &dc) {
60 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;
65 if (isTrackedVar(vd, &dc))
66 map[vd] = count++;
67 }
68 }
69
getValueIndex(const VarDecl * d) const70 llvm::Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const {
71 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d);
72 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
81 // These values are defined in such a way that a merge can be done using
82 // a bitwise OR.
83 enum Value { Unknown = 0x0, /* 00 */
84 Initialized = 0x1, /* 01 */
85 Uninitialized = 0x2, /* 10 */
86 MayUninitialized = 0x3 /* 11 */ };
87
isUninitialized(const Value v)88 static bool isUninitialized(const Value v) {
89 return v >= Uninitialized;
90 }
isAlwaysUninit(const Value v)91 static bool isAlwaysUninit(const Value v) {
92 return v == Uninitialized;
93 }
94
95 namespace {
96
97 typedef llvm::PackedVector<Value, 2> ValueVector;
98 typedef std::pair<ValueVector *, ValueVector *> BVPair;
99
100 class CFGBlockValues {
101 const CFG &cfg;
102 BVPair *vals;
103 ValueVector scratch;
104 DeclToIndex declToIndex;
105
106 ValueVector &lazyCreate(ValueVector *&bv);
107 public:
108 CFGBlockValues(const CFG &cfg);
109 ~CFGBlockValues();
110
getNumEntries() const111 unsigned getNumEntries() const { return declToIndex.size(); }
112
113 void computeSetOfDeclarations(const DeclContext &dc);
114 ValueVector &getValueVector(const CFGBlock *block,
115 const CFGBlock *dstBlock);
116
117 BVPair &getValueVectors(const CFGBlock *block, bool shouldLazyCreate);
118
119 void mergeIntoScratch(ValueVector const &source, bool isFirst);
120 bool updateValueVectorWithScratch(const CFGBlock *block);
121 bool updateValueVectors(const CFGBlock *block, const BVPair &newVals);
122
hasNoDeclarations() const123 bool hasNoDeclarations() const {
124 return declToIndex.size() == 0;
125 }
126
hasEntry(const VarDecl * vd) const127 bool hasEntry(const VarDecl *vd) const {
128 return declToIndex.getValueIndex(vd).hasValue();
129 }
130
131 bool hasValues(const CFGBlock *block);
132
133 void resetScratch();
getScratch()134 ValueVector &getScratch() { return scratch; }
135
136 ValueVector::reference operator[](const VarDecl *vd);
137 };
138 } // end anonymous namespace
139
CFGBlockValues(const CFG & c)140 CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {
141 unsigned n = cfg.getNumBlockIDs();
142 if (!n)
143 return;
144 vals = new std::pair<ValueVector*, ValueVector*>[n];
145 memset((void*)vals, 0, sizeof(*vals) * n);
146 }
147
~CFGBlockValues()148 CFGBlockValues::~CFGBlockValues() {
149 unsigned n = cfg.getNumBlockIDs();
150 if (n == 0)
151 return;
152 for (unsigned i = 0; i < n; ++i) {
153 delete vals[i].first;
154 delete vals[i].second;
155 }
156 delete [] vals;
157 }
158
computeSetOfDeclarations(const DeclContext & dc)159 void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
160 declToIndex.computeMap(dc);
161 scratch.resize(declToIndex.size());
162 }
163
lazyCreate(ValueVector * & bv)164 ValueVector &CFGBlockValues::lazyCreate(ValueVector *&bv) {
165 if (!bv)
166 bv = new ValueVector(declToIndex.size());
167 return *bv;
168 }
169
170 /// 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.
getLogicalOperatorInChain(const CFGBlock * block)173 static BinaryOperator *getLogicalOperatorInChain(const CFGBlock *block) {
174 if (block->empty())
175 return 0;
176
177 const CFGStmt *cstmt = block->front().getAs<CFGStmt>();
178 if (!cstmt)
179 return 0;
180
181 BinaryOperator *b = llvm::dyn_cast_or_null<BinaryOperator>(cstmt->getStmt());
182
183 if (!b || !b->isLogicalOp())
184 return 0;
185
186 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
195 return 0;
196 }
197
getValueVector(const CFGBlock * block,const CFGBlock * dstBlock)198 ValueVector &CFGBlockValues::getValueVector(const CFGBlock *block,
199 const CFGBlock *dstBlock) {
200 unsigned idx = block->getBlockID();
201 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);
206 }
207
208 assert(vals[idx].second == 0);
209 return lazyCreate(vals[idx].first);
210 }
211
hasValues(const CFGBlock * block)212 bool CFGBlockValues::hasValues(const CFGBlock *block) {
213 unsigned idx = block->getBlockID();
214 return vals[idx].second != 0;
215 }
216
getValueVectors(const clang::CFGBlock * block,bool shouldLazyCreate)217 BVPair &CFGBlockValues::getValueVectors(const clang::CFGBlock *block,
218 bool shouldLazyCreate) {
219 unsigned idx = block->getBlockID();
220 lazyCreate(vals[idx].first);
221 if (shouldLazyCreate)
222 lazyCreate(vals[idx].second);
223 return vals[idx];
224 }
225
mergeIntoScratch(ValueVector const & source,bool isFirst)226 void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
227 bool isFirst) {
228 if (isFirst)
229 scratch = source;
230 else
231 scratch |= source;
232 }
233 #if 0
234 static void printVector(const CFGBlock *block, ValueVector &bv,
235 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
244
updateValueVectorWithScratch(const CFGBlock * block)245 bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
246 ValueVector &dst = getValueVector(block, 0);
247 bool changed = (dst != scratch);
248 if (changed)
249 dst = scratch;
250 #if 0
251 printVector(block, scratch, 0);
252 #endif
253 return changed;
254 }
255
updateValueVectors(const CFGBlock * block,const BVPair & newVals)256 bool CFGBlockValues::updateValueVectors(const CFGBlock *block,
257 const BVPair &newVals) {
258 BVPair &vals = getValueVectors(block, true);
259 bool changed = *newVals.first != *vals.first ||
260 *newVals.second != *vals.second;
261 *vals.first = *newVals.first;
262 *vals.second = *newVals.second;
263 #if 0
264 printVector(block, *vals.first, 1);
265 printVector(block, *vals.second, 2);
266 #endif
267 return changed;
268 }
269
resetScratch()270 void CFGBlockValues::resetScratch() {
271 scratch.reset();
272 }
273
operator [](const VarDecl * vd)274 ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
275 const llvm::Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
276 assert(idx.hasValue());
277 return scratch[idx.getValue()];
278 }
279
280 //------------------------------------------------------------------------====//
281 // Worklist: worklist for dataflow analysis.
282 //====------------------------------------------------------------------------//
283
284 namespace {
285 class DataflowWorklist {
286 llvm::SmallVector<const CFGBlock *, 20> worklist;
287 llvm::BitVector enqueuedBlocks;
288 public:
DataflowWorklist(const CFG & cfg)289 DataflowWorklist(const CFG &cfg) : enqueuedBlocks(cfg.getNumBlockIDs()) {}
290
291 void enqueueSuccessors(const CFGBlock *block);
292 const CFGBlock *dequeue();
293 };
294 }
295
enqueueSuccessors(const clang::CFGBlock * block)296 void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
297 unsigned OldWorklistSize = worklist.size();
298 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
299 E = block->succ_end(); I != E; ++I) {
300 const CFGBlock *Successor = *I;
301 if (!Successor || enqueuedBlocks[Successor->getBlockID()])
302 continue;
303 worklist.push_back(Successor);
304 enqueuedBlocks[Successor->getBlockID()] = true;
305 }
306 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());
313 }
314
dequeue()315 const 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
328 namespace {
329 class FindVarResult {
330 const VarDecl *vd;
331 const DeclRefExpr *dr;
332 public:
FindVarResult(VarDecl * vd,DeclRefExpr * dr)333 FindVarResult(VarDecl *vd, DeclRefExpr *dr) : vd(vd), dr(dr) {}
334
getDeclRefExpr() const335 const DeclRefExpr *getDeclRefExpr() const { return dr; }
getDecl() const336 const VarDecl *getDecl() const { return vd; }
337 };
338
339 class TransferFunctions : public StmtVisitor<TransferFunctions> {
340 CFGBlockValues &vals;
341 const CFG &cfg;
342 AnalysisContext ∾
343 UninitVariablesHandler *handler;
344 const bool flagBlockUses;
345
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;
355 public:
TransferFunctions(CFGBlockValues & vals,const CFG & cfg,AnalysisContext & ac,UninitVariablesHandler * handler,bool flagBlockUses)356 TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
357 AnalysisContext &ac,
358 UninitVariablesHandler *handler,
359 bool flagBlockUses)
360 : vals(vals), cfg(cfg), ac(ac), handler(handler),
361 flagBlockUses(flagBlockUses), lastDR(0), lastLoad(0) {}
362
getCFG()363 const CFG &getCFG() { return cfg; }
364 void reportUninit(const DeclRefExpr *ex, const VarDecl *vd,
365 bool isAlwaysUninit);
366
367 void VisitBlockExpr(BlockExpr *be);
368 void VisitDeclStmt(DeclStmt *ds);
369 void VisitDeclRefExpr(DeclRefExpr *dr);
370 void VisitUnaryOperator(UnaryOperator *uo);
371 void VisitBinaryOperator(BinaryOperator *bo);
372 void VisitCastExpr(CastExpr *ce);
373 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs);
374 void Visit(Stmt *s);
375
isTrackedVar(const VarDecl * vd)376 bool isTrackedVar(const VarDecl *vd) {
377 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
378 }
379
380 FindVarResult findBlockVarDecl(Expr *ex);
381
382 void ProcessUses(Stmt *s = 0);
383 };
384 }
385
reportUninit(const DeclRefExpr * ex,const VarDecl * vd,bool isAlwaysUnit)386 void TransferFunctions::reportUninit(const DeclRefExpr *ex,
387 const VarDecl *vd, bool isAlwaysUnit) {
388 if (handler) handler->handleUseOfUninitVariable(ex, vd, isAlwaysUnit);
389 }
390
findBlockVarDecl(Expr * ex)391 FindVarResult TransferFunctions::findBlockVarDecl(Expr* ex) {
392 if (DeclRefExpr* dr = dyn_cast<DeclRefExpr>(ex->IgnoreParenCasts()))
393 if (VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
394 if (isTrackedVar(vd))
395 return FindVarResult(vd, dr);
396 return FindVarResult(0, 0);
397 }
398
VisitObjCForCollectionStmt(ObjCForCollectionStmt * fs)399 void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *fs) {
400 // This represents an initialization of the 'element' value.
401 Stmt *element = fs->getElement();
402 const VarDecl* vd = 0;
403
404 if (DeclStmt* ds = dyn_cast<DeclStmt>(element)) {
405 vd = cast<VarDecl>(ds->getSingleDecl());
406 if (!isTrackedVar(vd))
407 vd = 0;
408 }
409 else {
410 // Initialize the value of the reference variable.
411 const FindVarResult &res = findBlockVarDecl(cast<Expr>(element));
412 vd = res.getDecl();
413 }
414
415 if (vd)
416 vals[vd] = Initialized;
417 }
418
VisitBlockExpr(BlockExpr * be)419 void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
420 if (!flagBlockUses || !handler)
421 return;
422 const BlockDecl *bd = be->getBlockDecl();
423 for (BlockDecl::capture_const_iterator i = bd->capture_begin(),
424 e = bd->capture_end() ; i != e; ++i) {
425 const VarDecl *vd = i->getVariable();
426 if (!vd->hasLocalStorage())
427 continue;
428 if (!isTrackedVar(vd))
429 continue;
430 if (i->isByRef()) {
431 vals[vd] = Initialized;
432 continue;
433 }
434 Value v = vals[vd];
435 if (isUninitialized(v))
436 handler->handleUseOfUninitVariable(be, vd, isAlwaysUninit(v));
437 }
438 }
439
VisitDeclRefExpr(DeclRefExpr * dr)440 void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
441 // Record the last DeclRefExpr seen. This is an lvalue computation.
442 // We use this value to later detect if a variable "escapes" the analysis.
443 if (const VarDecl *vd = dyn_cast<VarDecl>(dr->getDecl()))
444 if (isTrackedVar(vd))
445 lastDR = dr;
446 }
447
VisitDeclStmt(DeclStmt * ds)448 void TransferFunctions::VisitDeclStmt(DeclStmt *ds) {
449 for (DeclStmt::decl_iterator DI = ds->decl_begin(), DE = ds->decl_end();
450 DI != DE; ++DI) {
451 if (VarDecl *vd = dyn_cast<VarDecl>(*DI)) {
452 if (isTrackedVar(vd)) {
453 if (Expr *init = vd->getInit()) {
454 // If the initializer consists solely of a reference to itself, we
455 // explicitly mark the variable as uninitialized. This allows code
456 // like the following:
457 //
458 // int x = x;
459 //
460 // to deliberately leave a variable uninitialized. Different analysis
461 // clients can detect this pattern and adjust their reporting
462 // appropriately, but we need to continue to analyze subsequent uses
463 // of the variable.
464 if (init == lastLoad) {
465 DeclRefExpr *DR =
466 cast<DeclRefExpr>(lastLoad->getSubExpr()->IgnoreParens());
467 if (DR->getDecl() == vd) {
468 // int x = x;
469 // Propagate uninitialized value, but don't immediately report
470 // a problem.
471 vals[vd] = Uninitialized;
472 lastLoad = 0;
473 lastDR = 0;
474 return;
475 }
476 }
477
478 // All other cases: treat the new variable as initialized.
479 vals[vd] = Initialized;
480 }
481 }
482 }
483 }
484 }
485
VisitBinaryOperator(clang::BinaryOperator * bo)486 void TransferFunctions::VisitBinaryOperator(clang::BinaryOperator *bo) {
487 if (bo->isAssignmentOp()) {
488 const FindVarResult &res = findBlockVarDecl(bo->getLHS());
489 if (const VarDecl* vd = res.getDecl()) {
490 ValueVector::reference val = vals[vd];
491 if (isUninitialized(val)) {
492 if (bo->getOpcode() != BO_Assign)
493 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
494 val = Initialized;
495 }
496 }
497 }
498 }
499
VisitUnaryOperator(clang::UnaryOperator * uo)500 void TransferFunctions::VisitUnaryOperator(clang::UnaryOperator *uo) {
501 switch (uo->getOpcode()) {
502 case clang::UO_PostDec:
503 case clang::UO_PostInc:
504 case clang::UO_PreDec:
505 case clang::UO_PreInc: {
506 const FindVarResult &res = findBlockVarDecl(uo->getSubExpr());
507 if (const VarDecl *vd = res.getDecl()) {
508 assert(res.getDeclRefExpr() == lastDR);
509 // We null out lastDR to indicate we have fully processed it
510 // and we don't want the auto-value setting in Visit().
511 lastDR = 0;
512
513 ValueVector::reference val = vals[vd];
514 if (isUninitialized(val)) {
515 reportUninit(res.getDeclRefExpr(), vd, isAlwaysUninit(val));
516 // Don't cascade warnings.
517 val = Initialized;
518 }
519 }
520 break;
521 }
522 default:
523 break;
524 }
525 }
526
VisitCastExpr(clang::CastExpr * ce)527 void TransferFunctions::VisitCastExpr(clang::CastExpr *ce) {
528 if (ce->getCastKind() == CK_LValueToRValue) {
529 const FindVarResult &res = findBlockVarDecl(ce->getSubExpr());
530 if (const VarDecl *vd = res.getDecl()) {
531 assert(res.getDeclRefExpr() == lastDR);
532 if (isUninitialized(vals[vd])) {
533 // Record this load of an uninitialized value. Normally this
534 // results in a warning, but we delay reporting the issue
535 // in case it is wrapped in a void cast, etc.
536 lastLoad = ce;
537 }
538 }
539 }
540 else if (CStyleCastExpr *cse = dyn_cast<CStyleCastExpr>(ce)) {
541 if (cse->getType()->isVoidType()) {
542 // e.g. (void) x;
543 if (lastLoad == cse->getSubExpr()) {
544 // Squelch any detected load of an uninitialized value if
545 // we cast it to void.
546 lastLoad = 0;
547 lastDR = 0;
548 }
549 }
550 }
551 }
552
Visit(clang::Stmt * s)553 void TransferFunctions::Visit(clang::Stmt *s) {
554 StmtVisitor<TransferFunctions>::Visit(s);
555 ProcessUses(s);
556 }
557
ProcessUses(Stmt * s)558 void TransferFunctions::ProcessUses(Stmt *s) {
559 // This method is typically called after visiting a CFGElement statement
560 // in the CFG. We delay processing of reporting many loads of uninitialized
561 // values until here.
562 if (lastLoad) {
563 // If we just visited the lvalue-to-rvalue cast, there is nothing
564 // left to do.
565 if (lastLoad == s)
566 return;
567
568 // If we reach here, we have seen a load of an uninitialized value
569 // and it hasn't been casted to void or otherwise handled. In this
570 // situation, report the incident.
571 DeclRefExpr *DR = cast<DeclRefExpr>(lastLoad->getSubExpr()->IgnoreParens());
572 VarDecl *VD = cast<VarDecl>(DR->getDecl());
573 reportUninit(DR, VD, isAlwaysUninit(vals[VD]));
574 lastLoad = 0;
575
576 // Prevent cascade of warnings.
577 vals[VD] = Initialized;
578 if (DR == lastDR) {
579 lastDR = 0;
580 return;
581 }
582 }
583
584 // Any other uses of 'lastDR' involve taking an lvalue of variable.
585 // In this case, it "escapes" the analysis.
586 if (lastDR && lastDR != s) {
587 vals[cast<VarDecl>(lastDR->getDecl())] = Initialized;
588 lastDR = 0;
589 }
590 }
591
592 //------------------------------------------------------------------------====//
593 // High-level "driver" logic for uninitialized values analysis.
594 //====------------------------------------------------------------------------//
595
runOnBlock(const CFGBlock * block,const CFG & cfg,AnalysisContext & ac,CFGBlockValues & vals,llvm::BitVector & wasAnalyzed,UninitVariablesHandler * handler=0,bool flagBlockUses=false)596 static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
597 AnalysisContext &ac, CFGBlockValues &vals,
598 llvm::BitVector &wasAnalyzed,
599 UninitVariablesHandler *handler = 0,
600 bool flagBlockUses = false) {
601
602 wasAnalyzed[block->getBlockID()] = true;
603
604 if (const BinaryOperator *b = getLogicalOperatorInChain(block)) {
605 CFGBlock::const_pred_iterator itr = block->pred_begin();
606 BVPair vA = vals.getValueVectors(*itr, false);
607 ++itr;
608 BVPair vB = vals.getValueVectors(*itr, false);
609
610 BVPair valsAB;
611
612 if (b->getOpcode() == BO_LAnd) {
613 // Merge the 'F' bits from the first and second.
614 vals.mergeIntoScratch(*(vA.second ? vA.second : vA.first), true);
615 vals.mergeIntoScratch(*(vB.second ? vB.second : vB.first), false);
616 valsAB.first = vA.first;
617 valsAB.second = &vals.getScratch();
618 }
619 else {
620 // Merge the 'T' bits from the first and second.
621 assert(b->getOpcode() == BO_LOr);
622 vals.mergeIntoScratch(*vA.first, true);
623 vals.mergeIntoScratch(*vB.first, false);
624 valsAB.first = &vals.getScratch();
625 valsAB.second = vA.second ? vA.second : vA.first;
626 }
627 return vals.updateValueVectors(block, valsAB);
628 }
629
630 // Default behavior: merge in values of predecessor blocks.
631 vals.resetScratch();
632 bool isFirst = true;
633 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
634 E = block->pred_end(); I != E; ++I) {
635 vals.mergeIntoScratch(vals.getValueVector(*I, block), isFirst);
636 isFirst = false;
637 }
638 // Apply the transfer function.
639 TransferFunctions tf(vals, cfg, ac, handler, flagBlockUses);
640 for (CFGBlock::const_iterator I = block->begin(), E = block->end();
641 I != E; ++I) {
642 if (const CFGStmt *cs = dyn_cast<CFGStmt>(&*I)) {
643 tf.Visit(cs->getStmt());
644 }
645 }
646 tf.ProcessUses();
647 return vals.updateValueVectorWithScratch(block);
648 }
649
runUninitializedVariablesAnalysis(const DeclContext & dc,const CFG & cfg,AnalysisContext & ac,UninitVariablesHandler & handler,UninitVariablesAnalysisStats & stats)650 void clang::runUninitializedVariablesAnalysis(
651 const DeclContext &dc,
652 const CFG &cfg,
653 AnalysisContext &ac,
654 UninitVariablesHandler &handler,
655 UninitVariablesAnalysisStats &stats) {
656 CFGBlockValues vals(cfg);
657 vals.computeSetOfDeclarations(dc);
658 if (vals.hasNoDeclarations())
659 return;
660
661 stats.NumVariablesAnalyzed = vals.getNumEntries();
662
663 // Mark all variables uninitialized at the entry.
664 const CFGBlock &entry = cfg.getEntry();
665 for (CFGBlock::const_succ_iterator i = entry.succ_begin(),
666 e = entry.succ_end(); i != e; ++i) {
667 if (const CFGBlock *succ = *i) {
668 ValueVector &vec = vals.getValueVector(&entry, succ);
669 const unsigned n = vals.getNumEntries();
670 for (unsigned j = 0; j < n ; ++j) {
671 vec[j] = Uninitialized;
672 }
673 }
674 }
675
676 // Proceed with the workist.
677 DataflowWorklist worklist(cfg);
678 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
679 worklist.enqueueSuccessors(&cfg.getEntry());
680 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
681
682 while (const CFGBlock *block = worklist.dequeue()) {
683 // Did the block change?
684 bool changed = runOnBlock(block, cfg, ac, vals, wasAnalyzed);
685 ++stats.NumBlockVisits;
686 if (changed || !previouslyVisited[block->getBlockID()])
687 worklist.enqueueSuccessors(block);
688 previouslyVisited[block->getBlockID()] = true;
689 }
690
691 // Run through the blocks one more time, and report uninitialized variabes.
692 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) {
693 if (wasAnalyzed[(*BI)->getBlockID()]) {
694 runOnBlock(*BI, cfg, ac, vals, wasAnalyzed, &handler,
695 /* flagBlockUses */ true);
696 ++stats.NumBlockVisits;
697 }
698 }
699 }
700
~UninitVariablesHandler()701 UninitVariablesHandler::~UninitVariablesHandler() {}
702