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