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 // Classify arguments to std::move as used. 345 if (CE->getNumArgs() == 1) { 346 if (FunctionDecl *FD = CE->getDirectCallee()) { 347 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) { 348 classify(CE->getArg(0), Use); 349 return; 350 } 351 } 352 } 353 354 // If a value is passed by const reference to a function, we should not assume 355 // that it is initialized by the call, and we conservatively do not assume 356 // that it is used. 357 for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); 358 I != E; ++I) 359 if ((*I)->getType().isConstQualified() && (*I)->isGLValue()) 360 classify(*I, Ignore); 361 } 362 363 void ClassifyRefs::VisitCastExpr(CastExpr *CE) { 364 if (CE->getCastKind() == CK_LValueToRValue) 365 classify(CE->getSubExpr(), Use); 366 else if (CStyleCastExpr *CSE = dyn_cast<CStyleCastExpr>(CE)) { 367 if (CSE->getType()->isVoidType()) { 368 // Squelch any detected load of an uninitialized value if 369 // we cast it to void. 370 // e.g. (void) x; 371 classify(CSE->getSubExpr(), Ignore); 372 } 373 } 374 } 375 376 //------------------------------------------------------------------------====// 377 // Transfer function for uninitialized values analysis. 378 //====------------------------------------------------------------------------// 379 380 namespace { 381 class TransferFunctions : public StmtVisitor<TransferFunctions> { 382 CFGBlockValues &vals; 383 const CFG &cfg; 384 const CFGBlock *block; 385 AnalysisDeclContext ∾ 386 const ClassifyRefs &classification; 387 ObjCNoReturn objCNoRet; 388 UninitVariablesHandler &handler; 389 390 public: 391 TransferFunctions(CFGBlockValues &vals, const CFG &cfg, 392 const CFGBlock *block, AnalysisDeclContext &ac, 393 const ClassifyRefs &classification, 394 UninitVariablesHandler &handler) 395 : vals(vals), cfg(cfg), block(block), ac(ac), 396 classification(classification), objCNoRet(ac.getASTContext()), 397 handler(handler) {} 398 399 void reportUse(const Expr *ex, const VarDecl *vd); 400 401 void VisitBinaryOperator(BinaryOperator *bo); 402 void VisitBlockExpr(BlockExpr *be); 403 void VisitCallExpr(CallExpr *ce); 404 void VisitDeclRefExpr(DeclRefExpr *dr); 405 void VisitDeclStmt(DeclStmt *ds); 406 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS); 407 void VisitObjCMessageExpr(ObjCMessageExpr *ME); 408 409 bool isTrackedVar(const VarDecl *vd) { 410 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl())); 411 } 412 413 FindVarResult findVar(const Expr *ex) { 414 return ::findVar(ex, cast<DeclContext>(ac.getDecl())); 415 } 416 417 UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) { 418 UninitUse Use(ex, isAlwaysUninit(v)); 419 420 assert(isUninitialized(v)); 421 if (Use.getKind() == UninitUse::Always) 422 return Use; 423 424 // If an edge which leads unconditionally to this use did not initialize 425 // the variable, we can say something stronger than 'may be uninitialized': 426 // we can say 'either it's used uninitialized or you have dead code'. 427 // 428 // We track the number of successors of a node which have been visited, and 429 // visit a node once we have visited all of its successors. Only edges where 430 // the variable might still be uninitialized are followed. Since a variable 431 // can't transfer from being initialized to being uninitialized, this will 432 // trace out the subgraph which inevitably leads to the use and does not 433 // initialize the variable. We do not want to skip past loops, since their 434 // non-termination might be correlated with the initialization condition. 435 // 436 // For example: 437 // 438 // void f(bool a, bool b) { 439 // block1: int n; 440 // if (a) { 441 // block2: if (b) 442 // block3: n = 1; 443 // block4: } else if (b) { 444 // block5: while (!a) { 445 // block6: do_work(&a); 446 // n = 2; 447 // } 448 // } 449 // block7: if (a) 450 // block8: g(); 451 // block9: return n; 452 // } 453 // 454 // Starting from the maybe-uninitialized use in block 9: 455 // * Block 7 is not visited because we have only visited one of its two 456 // successors. 457 // * Block 8 is visited because we've visited its only successor. 458 // From block 8: 459 // * Block 7 is visited because we've now visited both of its successors. 460 // From block 7: 461 // * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all 462 // of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively). 463 // * Block 3 is not visited because it initializes 'n'. 464 // Now the algorithm terminates, having visited blocks 7 and 8, and having 465 // found the frontier is blocks 2, 4, and 5. 466 // 467 // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2 468 // and 4), so we report that any time either of those edges is taken (in 469 // each case when 'b == false'), 'n' is used uninitialized. 470 SmallVector<const CFGBlock*, 32> Queue; 471 SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0); 472 Queue.push_back(block); 473 // Specify that we've already visited all successors of the starting block. 474 // This has the dual purpose of ensuring we never add it to the queue, and 475 // of marking it as not being a candidate element of the frontier. 476 SuccsVisited[block->getBlockID()] = block->succ_size(); 477 while (!Queue.empty()) { 478 const CFGBlock *B = Queue.pop_back_val(); 479 480 // If the use is always reached from the entry block, make a note of that. 481 if (B == &cfg.getEntry()) 482 Use.setUninitAfterCall(); 483 484 for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end(); 485 I != E; ++I) { 486 const CFGBlock *Pred = *I; 487 if (!Pred) 488 continue; 489 490 Value AtPredExit = vals.getValue(Pred, B, vd); 491 if (AtPredExit == Initialized) 492 // This block initializes the variable. 493 continue; 494 if (AtPredExit == MayUninitialized && 495 vals.getValue(B, nullptr, vd) == Uninitialized) { 496 // This block declares the variable (uninitialized), and is reachable 497 // from a block that initializes the variable. We can't guarantee to 498 // give an earlier location for the diagnostic (and it appears that 499 // this code is intended to be reachable) so give a diagnostic here 500 // and go no further down this path. 501 Use.setUninitAfterDecl(); 502 continue; 503 } 504 505 unsigned &SV = SuccsVisited[Pred->getBlockID()]; 506 if (!SV) { 507 // When visiting the first successor of a block, mark all NULL 508 // successors as having been visited. 509 for (CFGBlock::const_succ_iterator SI = Pred->succ_begin(), 510 SE = Pred->succ_end(); 511 SI != SE; ++SI) 512 if (!*SI) 513 ++SV; 514 } 515 516 if (++SV == Pred->succ_size()) 517 // All paths from this block lead to the use and don't initialize the 518 // variable. 519 Queue.push_back(Pred); 520 } 521 } 522 523 // Scan the frontier, looking for blocks where the variable was 524 // uninitialized. 525 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { 526 const CFGBlock *Block = *BI; 527 unsigned BlockID = Block->getBlockID(); 528 const Stmt *Term = Block->getTerminator(); 529 if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() && 530 Term) { 531 // This block inevitably leads to the use. If we have an edge from here 532 // to a post-dominator block, and the variable is uninitialized on that 533 // edge, we have found a bug. 534 for (CFGBlock::const_succ_iterator I = Block->succ_begin(), 535 E = Block->succ_end(); I != E; ++I) { 536 const CFGBlock *Succ = *I; 537 if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() && 538 vals.getValue(Block, Succ, vd) == Uninitialized) { 539 // Switch cases are a special case: report the label to the caller 540 // as the 'terminator', not the switch statement itself. Suppress 541 // situations where no label matched: we can't be sure that's 542 // possible. 543 if (isa<SwitchStmt>(Term)) { 544 const Stmt *Label = Succ->getLabel(); 545 if (!Label || !isa<SwitchCase>(Label)) 546 // Might not be possible. 547 continue; 548 UninitUse::Branch Branch; 549 Branch.Terminator = Label; 550 Branch.Output = 0; // Ignored. 551 Use.addUninitBranch(Branch); 552 } else { 553 UninitUse::Branch Branch; 554 Branch.Terminator = Term; 555 Branch.Output = I - Block->succ_begin(); 556 Use.addUninitBranch(Branch); 557 } 558 } 559 } 560 } 561 } 562 563 return Use; 564 } 565 }; 566 } 567 568 void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) { 569 Value v = vals[vd]; 570 if (isUninitialized(v)) 571 handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v)); 572 } 573 574 void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) { 575 // This represents an initialization of the 'element' value. 576 if (DeclStmt *DS = dyn_cast<DeclStmt>(FS->getElement())) { 577 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 578 if (isTrackedVar(VD)) 579 vals[VD] = Initialized; 580 } 581 } 582 583 void TransferFunctions::VisitBlockExpr(BlockExpr *be) { 584 const BlockDecl *bd = be->getBlockDecl(); 585 for (const auto &I : bd->captures()) { 586 const VarDecl *vd = I.getVariable(); 587 if (!isTrackedVar(vd)) 588 continue; 589 if (I.isByRef()) { 590 vals[vd] = Initialized; 591 continue; 592 } 593 reportUse(be, vd); 594 } 595 } 596 597 void TransferFunctions::VisitCallExpr(CallExpr *ce) { 598 if (Decl *Callee = ce->getCalleeDecl()) { 599 if (Callee->hasAttr<ReturnsTwiceAttr>()) { 600 // After a call to a function like setjmp or vfork, any variable which is 601 // initialized anywhere within this function may now be initialized. For 602 // now, just assume such a call initializes all variables. FIXME: Only 603 // mark variables as initialized if they have an initializer which is 604 // reachable from here. 605 vals.setAllScratchValues(Initialized); 606 } 607 else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) { 608 // Functions labeled like "analyzer_noreturn" are often used to denote 609 // "panic" functions that in special debug situations can still return, 610 // but for the most part should not be treated as returning. This is a 611 // useful annotation borrowed from the static analyzer that is useful for 612 // suppressing branch-specific false positives when we call one of these 613 // functions but keep pretending the path continues (when in reality the 614 // user doesn't care). 615 vals.setAllScratchValues(Unknown); 616 } 617 } 618 } 619 620 void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) { 621 switch (classification.get(dr)) { 622 case ClassifyRefs::Ignore: 623 break; 624 case ClassifyRefs::Use: 625 reportUse(dr, cast<VarDecl>(dr->getDecl())); 626 break; 627 case ClassifyRefs::Init: 628 vals[cast<VarDecl>(dr->getDecl())] = Initialized; 629 break; 630 case ClassifyRefs::SelfInit: 631 handler.handleSelfInit(cast<VarDecl>(dr->getDecl())); 632 break; 633 } 634 } 635 636 void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) { 637 if (BO->getOpcode() == BO_Assign) { 638 FindVarResult Var = findVar(BO->getLHS()); 639 if (const VarDecl *VD = Var.getDecl()) 640 vals[VD] = Initialized; 641 } 642 } 643 644 void TransferFunctions::VisitDeclStmt(DeclStmt *DS) { 645 for (auto *DI : DS->decls()) { 646 VarDecl *VD = dyn_cast<VarDecl>(DI); 647 if (VD && isTrackedVar(VD)) { 648 if (getSelfInitExpr(VD)) { 649 // If the initializer consists solely of a reference to itself, we 650 // explicitly mark the variable as uninitialized. This allows code 651 // like the following: 652 // 653 // int x = x; 654 // 655 // to deliberately leave a variable uninitialized. Different analysis 656 // clients can detect this pattern and adjust their reporting 657 // appropriately, but we need to continue to analyze subsequent uses 658 // of the variable. 659 vals[VD] = Uninitialized; 660 } else if (VD->getInit()) { 661 // Treat the new variable as initialized. 662 vals[VD] = Initialized; 663 } else { 664 // No initializer: the variable is now uninitialized. This matters 665 // for cases like: 666 // while (...) { 667 // int n; 668 // use(n); 669 // n = 0; 670 // } 671 // FIXME: Mark the variable as uninitialized whenever its scope is 672 // left, since its scope could be re-entered by a jump over the 673 // declaration. 674 vals[VD] = Uninitialized; 675 } 676 } 677 } 678 } 679 680 void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) { 681 // If the Objective-C message expression is an implicit no-return that 682 // is not modeled in the CFG, set the tracked dataflow values to Unknown. 683 if (objCNoRet.isImplicitNoReturn(ME)) { 684 vals.setAllScratchValues(Unknown); 685 } 686 } 687 688 //------------------------------------------------------------------------====// 689 // High-level "driver" logic for uninitialized values analysis. 690 //====------------------------------------------------------------------------// 691 692 static bool runOnBlock(const CFGBlock *block, const CFG &cfg, 693 AnalysisDeclContext &ac, CFGBlockValues &vals, 694 const ClassifyRefs &classification, 695 llvm::BitVector &wasAnalyzed, 696 UninitVariablesHandler &handler) { 697 wasAnalyzed[block->getBlockID()] = true; 698 vals.resetScratch(); 699 // Merge in values of predecessor blocks. 700 bool isFirst = true; 701 for (CFGBlock::const_pred_iterator I = block->pred_begin(), 702 E = block->pred_end(); I != E; ++I) { 703 const CFGBlock *pred = *I; 704 if (!pred) 705 continue; 706 if (wasAnalyzed[pred->getBlockID()]) { 707 vals.mergeIntoScratch(vals.getValueVector(pred), isFirst); 708 isFirst = false; 709 } 710 } 711 // Apply the transfer function. 712 TransferFunctions tf(vals, cfg, block, ac, classification, handler); 713 for (CFGBlock::const_iterator I = block->begin(), E = block->end(); 714 I != E; ++I) { 715 if (Optional<CFGStmt> cs = I->getAs<CFGStmt>()) 716 tf.Visit(const_cast<Stmt*>(cs->getStmt())); 717 } 718 return vals.updateValueVectorWithScratch(block); 719 } 720 721 /// PruneBlocksHandler is a special UninitVariablesHandler that is used 722 /// to detect when a CFGBlock has any *potential* use of an uninitialized 723 /// variable. It is mainly used to prune out work during the final 724 /// reporting pass. 725 namespace { 726 struct PruneBlocksHandler : public UninitVariablesHandler { 727 PruneBlocksHandler(unsigned numBlocks) 728 : hadUse(numBlocks, false), hadAnyUse(false), 729 currentBlock(0) {} 730 731 virtual ~PruneBlocksHandler() {} 732 733 /// Records if a CFGBlock had a potential use of an uninitialized variable. 734 llvm::BitVector hadUse; 735 736 /// Records if any CFGBlock had a potential use of an uninitialized variable. 737 bool hadAnyUse; 738 739 /// The current block to scribble use information. 740 unsigned currentBlock; 741 742 void handleUseOfUninitVariable(const VarDecl *vd, 743 const UninitUse &use) override { 744 hadUse[currentBlock] = true; 745 hadAnyUse = true; 746 } 747 748 /// Called when the uninitialized variable analysis detects the 749 /// idiom 'int x = x'. All other uses of 'x' within the initializer 750 /// are handled by handleUseOfUninitVariable. 751 void handleSelfInit(const VarDecl *vd) override { 752 hadUse[currentBlock] = true; 753 hadAnyUse = true; 754 } 755 }; 756 } 757 758 void clang::runUninitializedVariablesAnalysis( 759 const DeclContext &dc, 760 const CFG &cfg, 761 AnalysisDeclContext &ac, 762 UninitVariablesHandler &handler, 763 UninitVariablesAnalysisStats &stats) { 764 CFGBlockValues vals(cfg); 765 vals.computeSetOfDeclarations(dc); 766 if (vals.hasNoDeclarations()) 767 return; 768 769 stats.NumVariablesAnalyzed = vals.getNumEntries(); 770 771 // Precompute which expressions are uses and which are initializations. 772 ClassifyRefs classification(ac); 773 cfg.VisitBlockStmts(classification); 774 775 // Mark all variables uninitialized at the entry. 776 const CFGBlock &entry = cfg.getEntry(); 777 ValueVector &vec = vals.getValueVector(&entry); 778 const unsigned n = vals.getNumEntries(); 779 for (unsigned j = 0; j < n ; ++j) { 780 vec[j] = Uninitialized; 781 } 782 783 // Proceed with the workist. 784 ForwardDataflowWorklist worklist(cfg, ac); 785 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs()); 786 worklist.enqueueSuccessors(&cfg.getEntry()); 787 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false); 788 wasAnalyzed[cfg.getEntry().getBlockID()] = true; 789 PruneBlocksHandler PBH(cfg.getNumBlockIDs()); 790 791 while (const CFGBlock *block = worklist.dequeue()) { 792 PBH.currentBlock = block->getBlockID(); 793 794 // Did the block change? 795 bool changed = runOnBlock(block, cfg, ac, vals, 796 classification, wasAnalyzed, PBH); 797 ++stats.NumBlockVisits; 798 if (changed || !previouslyVisited[block->getBlockID()]) 799 worklist.enqueueSuccessors(block); 800 previouslyVisited[block->getBlockID()] = true; 801 } 802 803 if (!PBH.hadAnyUse) 804 return; 805 806 // Run through the blocks one more time, and report uninitialized variables. 807 for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { 808 const CFGBlock *block = *BI; 809 if (PBH.hadUse[block->getBlockID()]) { 810 runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler); 811 ++stats.NumBlockVisits; 812 } 813 } 814 } 815 816 UninitVariablesHandler::~UninitVariablesHandler() {} 817