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 "clang/AST/ASTContext.h" 15 #include "clang/AST/Attr.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/StmtVisitor.h" 18 #include "clang/Analysis/Analyses/DataflowWorklist.h" 19 #include "clang/Analysis/Analyses/UninitializedValues.h" 20 #include "clang/Analysis/AnalysisContext.h" 21 #include "clang/Analysis/CFG.h" 22 #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/Optional.h" 25 #include "llvm/ADT/PackedVector.h" 26 #include "llvm/ADT/SmallBitVector.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/Support/SaveAndRestore.h" 29 #include <utility> 30 31 using namespace clang; 32 33 #define DEBUG_LOGGING 0 34 35 static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) { 36 if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() && 37 !vd->isExceptionVariable() && !vd->isInitCapture() && 38 vd->getDeclContext() == dc) { 39 QualType ty = vd->getType(); 40 return ty->isScalarType() || ty->isVectorType(); 41 } 42 return false; 43 } 44 45 //------------------------------------------------------------------------====// 46 // DeclToIndex: a mapping from Decls we track to value indices. 47 //====------------------------------------------------------------------------// 48 49 namespace { 50 class DeclToIndex { 51 llvm::DenseMap<const VarDecl *, unsigned> map; 52 public: 53 DeclToIndex() {} 54 55 /// Compute the actual mapping from declarations to bits. 56 void computeMap(const DeclContext &dc); 57 58 /// Return the number of declarations in the map. 59 unsigned size() const { return map.size(); } 60 61 /// Returns the bit vector index for a given declaration. 62 Optional<unsigned> getValueIndex(const VarDecl *d) const; 63 }; 64 } 65 66 void DeclToIndex::computeMap(const DeclContext &dc) { 67 unsigned count = 0; 68 DeclContext::specific_decl_iterator<VarDecl> I(dc.decls_begin()), 69 E(dc.decls_end()); 70 for ( ; I != E; ++I) { 71 const VarDecl *vd = *I; 72 if (isTrackedVar(vd, &dc)) 73 map[vd] = count++; 74 } 75 } 76 77 Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const { 78 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d); 79 if (I == map.end()) 80 return None; 81 return I->second; 82 } 83 84 //------------------------------------------------------------------------====// 85 // CFGBlockValues: dataflow values for CFG blocks. 86 //====------------------------------------------------------------------------// 87 88 // These values are defined in such a way that a merge can be done using 89 // a bitwise OR. 90 enum Value { Unknown = 0x0, /* 00 */ 91 Initialized = 0x1, /* 01 */ 92 Uninitialized = 0x2, /* 10 */ 93 MayUninitialized = 0x3 /* 11 */ }; 94 95 static bool isUninitialized(const Value v) { 96 return v >= Uninitialized; 97 } 98 static bool isAlwaysUninit(const Value v) { 99 return v == Uninitialized; 100 } 101 102 namespace { 103 104 typedef llvm::PackedVector<Value, 2, llvm::SmallBitVector> ValueVector; 105 106 class CFGBlockValues { 107 const CFG &cfg; 108 SmallVector<ValueVector, 8> vals; 109 ValueVector scratch; 110 DeclToIndex declToIndex; 111 public: 112 CFGBlockValues(const CFG &cfg); 113 114 unsigned getNumEntries() const { return declToIndex.size(); } 115 116 void computeSetOfDeclarations(const DeclContext &dc); 117 ValueVector &getValueVector(const CFGBlock *block) { 118 return vals[block->getBlockID()]; 119 } 120 121 void setAllScratchValues(Value V); 122 void mergeIntoScratch(ValueVector const &source, bool isFirst); 123 bool updateValueVectorWithScratch(const CFGBlock *block); 124 125 bool hasNoDeclarations() const { 126 return declToIndex.size() == 0; 127 } 128 129 void resetScratch(); 130 131 ValueVector::reference operator[](const VarDecl *vd); 132 133 Value getValue(const CFGBlock *block, const CFGBlock *dstBlock, 134 const VarDecl *vd) { 135 const Optional<unsigned> &idx = declToIndex.getValueIndex(vd); 136 assert(idx.hasValue()); 137 return getValueVector(block)[idx.getValue()]; 138 } 139 }; 140 } // end anonymous namespace 141 142 CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {} 143 144 void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) { 145 declToIndex.computeMap(dc); 146 unsigned decls = declToIndex.size(); 147 scratch.resize(decls); 148 unsigned n = cfg.getNumBlockIDs(); 149 if (!n) 150 return; 151 vals.resize(n); 152 for (unsigned i = 0; i < n; ++i) 153 vals[i].resize(decls); 154 } 155 156 #if DEBUG_LOGGING 157 static void printVector(const CFGBlock *block, ValueVector &bv, 158 unsigned num) { 159 llvm::errs() << block->getBlockID() << " :"; 160 for (unsigned i = 0; i < bv.size(); ++i) { 161 llvm::errs() << ' ' << bv[i]; 162 } 163 llvm::errs() << " : " << num << '\n'; 164 } 165 #endif 166 167 void CFGBlockValues::setAllScratchValues(Value V) { 168 for (unsigned I = 0, E = scratch.size(); I != E; ++I) 169 scratch[I] = V; 170 } 171 172 void CFGBlockValues::mergeIntoScratch(ValueVector const &source, 173 bool isFirst) { 174 if (isFirst) 175 scratch = source; 176 else 177 scratch |= source; 178 } 179 180 bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) { 181 ValueVector &dst = getValueVector(block); 182 bool changed = (dst != scratch); 183 if (changed) 184 dst = scratch; 185 #if DEBUG_LOGGING 186 printVector(block, scratch, 0); 187 #endif 188 return changed; 189 } 190 191 void CFGBlockValues::resetScratch() { 192 scratch.reset(); 193 } 194 195 ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) { 196 const Optional<unsigned> &idx = declToIndex.getValueIndex(vd); 197 assert(idx.hasValue()); 198 return scratch[idx.getValue()]; 199 } 200 201 //------------------------------------------------------------------------====// 202 // Classification of DeclRefExprs as use or initialization. 203 //====------------------------------------------------------------------------// 204 205 namespace { 206 class FindVarResult { 207 const VarDecl *vd; 208 const DeclRefExpr *dr; 209 public: 210 FindVarResult(const VarDecl *vd, const DeclRefExpr *dr) : vd(vd), dr(dr) {} 211 212 const DeclRefExpr *getDeclRefExpr() const { return dr; } 213 const VarDecl *getDecl() const { return vd; } 214 }; 215 216 static const Expr *stripCasts(ASTContext &C, const Expr *Ex) { 217 while (Ex) { 218 Ex = Ex->IgnoreParenNoopCasts(C); 219 if (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 220 if (CE->getCastKind() == CK_LValueBitCast) { 221 Ex = CE->getSubExpr(); 222 continue; 223 } 224 } 225 break; 226 } 227 return Ex; 228 } 229 230 /// If E is an expression comprising a reference to a single variable, find that 231 /// variable. 232 static FindVarResult findVar(const Expr *E, const DeclContext *DC) { 233 if (const DeclRefExpr *DRE = 234 dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E))) 235 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 236 if (isTrackedVar(VD, DC)) 237 return FindVarResult(VD, DRE); 238 return FindVarResult(nullptr, nullptr); 239 } 240 241 /// \brief Classify each DeclRefExpr as an initialization or a use. Any 242 /// DeclRefExpr which isn't explicitly classified will be assumed to have 243 /// escaped the analysis and will be treated as an initialization. 244 class ClassifyRefs : public StmtVisitor<ClassifyRefs> { 245 public: 246 enum Class { 247 Init, 248 Use, 249 SelfInit, 250 Ignore 251 }; 252 253 private: 254 const DeclContext *DC; 255 llvm::DenseMap<const DeclRefExpr*, Class> Classification; 256 257 bool isTrackedVar(const VarDecl *VD) const { 258 return ::isTrackedVar(VD, DC); 259 } 260 261 void classify(const Expr *E, Class C); 262 263 public: 264 ClassifyRefs(AnalysisDeclContext &AC) : DC(cast<DeclContext>(AC.getDecl())) {} 265 266 void VisitDeclStmt(DeclStmt *DS); 267 void VisitUnaryOperator(UnaryOperator *UO); 268 void VisitBinaryOperator(BinaryOperator *BO); 269 void VisitCallExpr(CallExpr *CE); 270 void VisitCastExpr(CastExpr *CE); 271 272 void operator()(Stmt *S) { Visit(S); } 273 274 Class get(const DeclRefExpr *DRE) const { 275 llvm::DenseMap<const DeclRefExpr*, Class>::const_iterator I 276 = Classification.find(DRE); 277 if (I != Classification.end()) 278 return I->second; 279 280 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); 281 if (!VD || !isTrackedVar(VD)) 282 return Ignore; 283 284 return Init; 285 } 286 }; 287 } 288 289 static const DeclRefExpr *getSelfInitExpr(VarDecl *VD) { 290 if (Expr *Init = VD->getInit()) { 291 const DeclRefExpr *DRE 292 = dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init)); 293 if (DRE && DRE->getDecl() == VD) 294 return DRE; 295 } 296 return nullptr; 297 } 298 299 void ClassifyRefs::classify(const Expr *E, Class C) { 300 // The result of a ?: could also be an lvalue. 301 E = E->IgnoreParens(); 302 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 303 const Expr *TrueExpr = CO->getTrueExpr(); 304 if (!isa<OpaqueValueExpr>(TrueExpr)) 305 classify(TrueExpr, C); 306 classify(CO->getFalseExpr(), C); 307 return; 308 } 309 310 FindVarResult Var = findVar(E, DC); 311 if (const DeclRefExpr *DRE = Var.getDeclRefExpr()) 312 Classification[DRE] = std::max(Classification[DRE], C); 313 } 314 315 void ClassifyRefs::VisitDeclStmt(DeclStmt *DS) { 316 for (auto *DI : DS->decls()) { 317 VarDecl *VD = dyn_cast<VarDecl>(DI); 318 if (VD && isTrackedVar(VD)) 319 if (const DeclRefExpr *DRE = getSelfInitExpr(VD)) 320 Classification[DRE] = SelfInit; 321 } 322 } 323 324 void ClassifyRefs::VisitBinaryOperator(BinaryOperator *BO) { 325 // Ignore the evaluation of a DeclRefExpr on the LHS of an assignment. If this 326 // is not a compound-assignment, we will treat it as initializing the variable 327 // when TransferFunctions visits it. A compound-assignment does not affect 328 // whether a variable is uninitialized, and there's no point counting it as a 329 // use. 330 if (BO->isCompoundAssignmentOp()) 331 classify(BO->getLHS(), Use); 332 else if (BO->getOpcode() == BO_Assign) 333 classify(BO->getLHS(), Ignore); 334 } 335 336 void ClassifyRefs::VisitUnaryOperator(UnaryOperator *UO) { 337 // Increment and decrement are uses despite there being no lvalue-to-rvalue 338 // conversion. 339 if (UO->isIncrementDecrementOp()) 340 classify(UO->getSubExpr(), Use); 341 } 342 343 void ClassifyRefs::VisitCallExpr(CallExpr *CE) { 344 // If a value is passed by const reference to a function, we should not assume 345 // that it is initialized by the call, and we conservatively do not assume 346 // that it is used. 347 for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); 348 I != E; ++I) 349 if ((*I)->getType().isConstQualified() && (*I)->isGLValue()) 350 classify(*I, Ignore); 351 } 352 353 void ClassifyRefs::VisitCastExpr(CastExpr *CE) { 354 if (CE->getCastKind() == CK_LValueToRValue) 355 classify(CE->getSubExpr(), Use); 356 else if (CStyleCastExpr *CSE = dyn_cast<CStyleCastExpr>(CE)) { 357 if (CSE->getType()->isVoidType()) { 358 // Squelch any detected load of an uninitialized value if 359 // we cast it to void. 360 // e.g. (void) x; 361 classify(CSE->getSubExpr(), Ignore); 362 } 363 } 364 } 365 366 //------------------------------------------------------------------------====// 367 // Transfer function for uninitialized values analysis. 368 //====------------------------------------------------------------------------// 369 370 namespace { 371 class TransferFunctions : public StmtVisitor<TransferFunctions> { 372 CFGBlockValues &vals; 373 const CFG &cfg; 374 const CFGBlock *block; 375 AnalysisDeclContext ∾ 376 const ClassifyRefs &classification; 377 ObjCNoReturn objCNoRet; 378 UninitVariablesHandler &handler; 379 380 public: 381 TransferFunctions(CFGBlockValues &vals, const CFG &cfg, 382 const CFGBlock *block, AnalysisDeclContext &ac, 383 const ClassifyRefs &classification, 384 UninitVariablesHandler &handler) 385 : vals(vals), cfg(cfg), block(block), ac(ac), 386 classification(classification), objCNoRet(ac.getASTContext()), 387 handler(handler) {} 388 389 void reportUse(const Expr *ex, const VarDecl *vd); 390 391 void VisitBinaryOperator(BinaryOperator *bo); 392 void VisitBlockExpr(BlockExpr *be); 393 void VisitCallExpr(CallExpr *ce); 394 void VisitDeclRefExpr(DeclRefExpr *dr); 395 void VisitDeclStmt(DeclStmt *ds); 396 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS); 397 void VisitObjCMessageExpr(ObjCMessageExpr *ME); 398 399 bool isTrackedVar(const VarDecl *vd) { 400 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl())); 401 } 402 403 FindVarResult findVar(const Expr *ex) { 404 return ::findVar(ex, cast<DeclContext>(ac.getDecl())); 405 } 406 407 UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) { 408 UninitUse Use(ex, isAlwaysUninit(v)); 409 410 assert(isUninitialized(v)); 411 if (Use.getKind() == UninitUse::Always) 412 return Use; 413 414 // If an edge which leads unconditionally to this use did not initialize 415 // the variable, we can say something stronger than 'may be uninitialized': 416 // we can say 'either it's used uninitialized or you have dead code'. 417 // 418 // We track the number of successors of a node which have been visited, and 419 // visit a node once we have visited all of its successors. Only edges where 420 // the variable might still be uninitialized are followed. Since a variable 421 // can't transfer from being initialized to being uninitialized, this will 422 // trace out the subgraph which inevitably leads to the use and does not 423 // initialize the variable. We do not want to skip past loops, since their 424 // non-termination might be correlated with the initialization condition. 425 // 426 // For example: 427 // 428 // void f(bool a, bool b) { 429 // block1: int n; 430 // if (a) { 431 // block2: if (b) 432 // block3: n = 1; 433 // block4: } else if (b) { 434 // block5: while (!a) { 435 // block6: do_work(&a); 436 // n = 2; 437 // } 438 // } 439 // block7: if (a) 440 // block8: g(); 441 // block9: return n; 442 // } 443 // 444 // Starting from the maybe-uninitialized use in block 9: 445 // * Block 7 is not visited because we have only visited one of its two 446 // successors. 447 // * Block 8 is visited because we've visited its only successor. 448 // From block 8: 449 // * Block 7 is visited because we've now visited both of its successors. 450 // From block 7: 451 // * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all 452 // of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively). 453 // * Block 3 is not visited because it initializes 'n'. 454 // Now the algorithm terminates, having visited blocks 7 and 8, and having 455 // found the frontier is blocks 2, 4, and 5. 456 // 457 // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2 458 // and 4), so we report that any time either of those edges is taken (in 459 // each case when 'b == false'), 'n' is used uninitialized. 460 SmallVector<const CFGBlock*, 32> Queue; 461 SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0); 462 Queue.push_back(block); 463 // Specify that we've already visited all successors of the starting block. 464 // This has the dual purpose of ensuring we never add it to the queue, and 465 // of marking it as not being a candidate element of the frontier. 466 SuccsVisited[block->getBlockID()] = block->succ_size(); 467 while (!Queue.empty()) { 468 const CFGBlock *B = Queue.pop_back_val(); 469 470 // If the use is always reached from the entry block, make a note of that. 471 if (B == &cfg.getEntry()) 472 Use.setUninitAfterCall(); 473 474 for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end(); 475 I != E; ++I) { 476 const CFGBlock *Pred = *I; 477 if (!Pred) 478 continue; 479 480 Value AtPredExit = vals.getValue(Pred, B, vd); 481 if (AtPredExit == Initialized) 482 // This block initializes the variable. 483 continue; 484 if (AtPredExit == MayUninitialized && 485 vals.getValue(B, nullptr, vd) == Uninitialized) { 486 // This block declares the variable (uninitialized), and is reachable 487 // from a block that initializes the variable. We can't guarantee to 488 // give an earlier location for the diagnostic (and it appears that 489 // this code is intended to be reachable) so give a diagnostic here 490 // and go no further down this path. 491 Use.setUninitAfterDecl(); 492 continue; 493 } 494 495 unsigned &SV = SuccsVisited[Pred->getBlockID()]; 496 if (!SV) { 497 // When visiting the first successor of a block, mark all NULL 498 // successors as having been visited. 499 for (CFGBlock::const_succ_iterator SI = Pred->succ_begin(), 500 SE = Pred->succ_end(); 501 SI != SE; ++SI) 502 if (!*SI) 503 ++SV; 504 } 505 506 if (++SV == Pred->succ_size()) 507 // All paths from this block lead to the use and don't initialize the 508 // variable. 509 Queue.push_back(Pred); 510 } 511 } 512 513 // Scan the frontier, looking for blocks where the variable was 514 // uninitialized. 515 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { 516 const CFGBlock *Block = *BI; 517 unsigned BlockID = Block->getBlockID(); 518 const Stmt *Term = Block->getTerminator(); 519 if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() && 520 Term) { 521 // This block inevitably leads to the use. If we have an edge from here 522 // to a post-dominator block, and the variable is uninitialized on that 523 // edge, we have found a bug. 524 for (CFGBlock::const_succ_iterator I = Block->succ_begin(), 525 E = Block->succ_end(); I != E; ++I) { 526 const CFGBlock *Succ = *I; 527 if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() && 528 vals.getValue(Block, Succ, vd) == Uninitialized) { 529 // Switch cases are a special case: report the label to the caller 530 // as the 'terminator', not the switch statement itself. Suppress 531 // situations where no label matched: we can't be sure that's 532 // possible. 533 if (isa<SwitchStmt>(Term)) { 534 const Stmt *Label = Succ->getLabel(); 535 if (!Label || !isa<SwitchCase>(Label)) 536 // Might not be possible. 537 continue; 538 UninitUse::Branch Branch; 539 Branch.Terminator = Label; 540 Branch.Output = 0; // Ignored. 541 Use.addUninitBranch(Branch); 542 } else { 543 UninitUse::Branch Branch; 544 Branch.Terminator = Term; 545 Branch.Output = I - Block->succ_begin(); 546 Use.addUninitBranch(Branch); 547 } 548 } 549 } 550 } 551 } 552 553 return Use; 554 } 555 }; 556 } 557 558 void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) { 559 Value v = vals[vd]; 560 if (isUninitialized(v)) 561 handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v)); 562 } 563 564 void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) { 565 // This represents an initialization of the 'element' value. 566 if (DeclStmt *DS = dyn_cast<DeclStmt>(FS->getElement())) { 567 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 568 if (isTrackedVar(VD)) 569 vals[VD] = Initialized; 570 } 571 } 572 573 void TransferFunctions::VisitBlockExpr(BlockExpr *be) { 574 const BlockDecl *bd = be->getBlockDecl(); 575 for (const auto &I : bd->captures()) { 576 const VarDecl *vd = I.getVariable(); 577 if (!isTrackedVar(vd)) 578 continue; 579 if (I.isByRef()) { 580 vals[vd] = Initialized; 581 continue; 582 } 583 reportUse(be, vd); 584 } 585 } 586 587 void TransferFunctions::VisitCallExpr(CallExpr *ce) { 588 if (Decl *Callee = ce->getCalleeDecl()) { 589 if (Callee->hasAttr<ReturnsTwiceAttr>()) { 590 // After a call to a function like setjmp or vfork, any variable which is 591 // initialized anywhere within this function may now be initialized. For 592 // now, just assume such a call initializes all variables. FIXME: Only 593 // mark variables as initialized if they have an initializer which is 594 // reachable from here. 595 vals.setAllScratchValues(Initialized); 596 } 597 else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) { 598 // Functions labeled like "analyzer_noreturn" are often used to denote 599 // "panic" functions that in special debug situations can still return, 600 // but for the most part should not be treated as returning. This is a 601 // useful annotation borrowed from the static analyzer that is useful for 602 // suppressing branch-specific false positives when we call one of these 603 // functions but keep pretending the path continues (when in reality the 604 // user doesn't care). 605 vals.setAllScratchValues(Unknown); 606 } 607 } 608 } 609 610 void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) { 611 switch (classification.get(dr)) { 612 case ClassifyRefs::Ignore: 613 break; 614 case ClassifyRefs::Use: 615 reportUse(dr, cast<VarDecl>(dr->getDecl())); 616 break; 617 case ClassifyRefs::Init: 618 vals[cast<VarDecl>(dr->getDecl())] = Initialized; 619 break; 620 case ClassifyRefs::SelfInit: 621 handler.handleSelfInit(cast<VarDecl>(dr->getDecl())); 622 break; 623 } 624 } 625 626 void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) { 627 if (BO->getOpcode() == BO_Assign) { 628 FindVarResult Var = findVar(BO->getLHS()); 629 if (const VarDecl *VD = Var.getDecl()) 630 vals[VD] = Initialized; 631 } 632 } 633 634 void TransferFunctions::VisitDeclStmt(DeclStmt *DS) { 635 for (auto *DI : DS->decls()) { 636 VarDecl *VD = dyn_cast<VarDecl>(DI); 637 if (VD && isTrackedVar(VD)) { 638 if (getSelfInitExpr(VD)) { 639 // If the initializer consists solely of a reference to itself, we 640 // explicitly mark the variable as uninitialized. This allows code 641 // like the following: 642 // 643 // int x = x; 644 // 645 // to deliberately leave a variable uninitialized. Different analysis 646 // clients can detect this pattern and adjust their reporting 647 // appropriately, but we need to continue to analyze subsequent uses 648 // of the variable. 649 vals[VD] = Uninitialized; 650 } else if (VD->getInit()) { 651 // Treat the new variable as initialized. 652 vals[VD] = Initialized; 653 } else { 654 // No initializer: the variable is now uninitialized. This matters 655 // for cases like: 656 // while (...) { 657 // int n; 658 // use(n); 659 // n = 0; 660 // } 661 // FIXME: Mark the variable as uninitialized whenever its scope is 662 // left, since its scope could be re-entered by a jump over the 663 // declaration. 664 vals[VD] = Uninitialized; 665 } 666 } 667 } 668 } 669 670 void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) { 671 // If the Objective-C message expression is an implicit no-return that 672 // is not modeled in the CFG, set the tracked dataflow values to Unknown. 673 if (objCNoRet.isImplicitNoReturn(ME)) { 674 vals.setAllScratchValues(Unknown); 675 } 676 } 677 678 //------------------------------------------------------------------------====// 679 // High-level "driver" logic for uninitialized values analysis. 680 //====------------------------------------------------------------------------// 681 682 static bool runOnBlock(const CFGBlock *block, const CFG &cfg, 683 AnalysisDeclContext &ac, CFGBlockValues &vals, 684 const ClassifyRefs &classification, 685 llvm::BitVector &wasAnalyzed, 686 UninitVariablesHandler &handler) { 687 wasAnalyzed[block->getBlockID()] = true; 688 vals.resetScratch(); 689 // Merge in values of predecessor blocks. 690 bool isFirst = true; 691 for (CFGBlock::const_pred_iterator I = block->pred_begin(), 692 E = block->pred_end(); I != E; ++I) { 693 const CFGBlock *pred = *I; 694 if (!pred) 695 continue; 696 if (wasAnalyzed[pred->getBlockID()]) { 697 vals.mergeIntoScratch(vals.getValueVector(pred), isFirst); 698 isFirst = false; 699 } 700 } 701 // Apply the transfer function. 702 TransferFunctions tf(vals, cfg, block, ac, classification, handler); 703 for (CFGBlock::const_iterator I = block->begin(), E = block->end(); 704 I != E; ++I) { 705 if (Optional<CFGStmt> cs = I->getAs<CFGStmt>()) 706 tf.Visit(const_cast<Stmt*>(cs->getStmt())); 707 } 708 return vals.updateValueVectorWithScratch(block); 709 } 710 711 /// PruneBlocksHandler is a special UninitVariablesHandler that is used 712 /// to detect when a CFGBlock has any *potential* use of an uninitialized 713 /// variable. It is mainly used to prune out work during the final 714 /// reporting pass. 715 namespace { 716 struct PruneBlocksHandler : public UninitVariablesHandler { 717 PruneBlocksHandler(unsigned numBlocks) 718 : hadUse(numBlocks, false), hadAnyUse(false), 719 currentBlock(0) {} 720 721 virtual ~PruneBlocksHandler() {} 722 723 /// Records if a CFGBlock had a potential use of an uninitialized variable. 724 llvm::BitVector hadUse; 725 726 /// Records if any CFGBlock had a potential use of an uninitialized variable. 727 bool hadAnyUse; 728 729 /// The current block to scribble use information. 730 unsigned currentBlock; 731 732 void handleUseOfUninitVariable(const VarDecl *vd, 733 const UninitUse &use) override { 734 hadUse[currentBlock] = true; 735 hadAnyUse = true; 736 } 737 738 /// Called when the uninitialized variable analysis detects the 739 /// idiom 'int x = x'. All other uses of 'x' within the initializer 740 /// are handled by handleUseOfUninitVariable. 741 void handleSelfInit(const VarDecl *vd) override { 742 hadUse[currentBlock] = true; 743 hadAnyUse = true; 744 } 745 }; 746 } 747 748 void clang::runUninitializedVariablesAnalysis( 749 const DeclContext &dc, 750 const CFG &cfg, 751 AnalysisDeclContext &ac, 752 UninitVariablesHandler &handler, 753 UninitVariablesAnalysisStats &stats) { 754 CFGBlockValues vals(cfg); 755 vals.computeSetOfDeclarations(dc); 756 if (vals.hasNoDeclarations()) 757 return; 758 759 stats.NumVariablesAnalyzed = vals.getNumEntries(); 760 761 // Precompute which expressions are uses and which are initializations. 762 ClassifyRefs classification(ac); 763 cfg.VisitBlockStmts(classification); 764 765 // Mark all variables uninitialized at the entry. 766 const CFGBlock &entry = cfg.getEntry(); 767 ValueVector &vec = vals.getValueVector(&entry); 768 const unsigned n = vals.getNumEntries(); 769 for (unsigned j = 0; j < n ; ++j) { 770 vec[j] = Uninitialized; 771 } 772 773 // Proceed with the workist. 774 DataflowWorklist worklist(cfg, ac); 775 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs()); 776 worklist.enqueueSuccessors(&cfg.getEntry()); 777 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false); 778 wasAnalyzed[cfg.getEntry().getBlockID()] = true; 779 PruneBlocksHandler PBH(cfg.getNumBlockIDs()); 780 781 while (const CFGBlock *block = worklist.dequeue()) { 782 PBH.currentBlock = block->getBlockID(); 783 784 // Did the block change? 785 bool changed = runOnBlock(block, cfg, ac, vals, 786 classification, wasAnalyzed, PBH); 787 ++stats.NumBlockVisits; 788 if (changed || !previouslyVisited[block->getBlockID()]) 789 worklist.enqueueSuccessors(block); 790 previouslyVisited[block->getBlockID()] = true; 791 } 792 793 if (!PBH.hadAnyUse) 794 return; 795 796 // Run through the blocks one more time, and report uninitialized variables. 797 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { 798 const CFGBlock *block = *BI; 799 if (PBH.hadUse[block->getBlockID()]) { 800 runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler); 801 ++stats.NumBlockVisits; 802 } 803 } 804 } 805 806 UninitVariablesHandler::~UninitVariablesHandler() {} 807