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 VisitGCCAsmStmt(GCCAsmStmt *as); 479 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS); 480 void VisitObjCMessageExpr(ObjCMessageExpr *ME); 481 void VisitOMPExecutableDirective(OMPExecutableDirective *ED); 482 483 bool isTrackedVar(const VarDecl *vd) { 484 return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl())); 485 } 486 487 FindVarResult findVar(const Expr *ex) { 488 return ::findVar(ex, cast<DeclContext>(ac.getDecl())); 489 } 490 491 UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) { 492 UninitUse Use(ex, isAlwaysUninit(v)); 493 494 assert(isUninitialized(v)); 495 if (Use.getKind() == UninitUse::Always) 496 return Use; 497 498 // If an edge which leads unconditionally to this use did not initialize 499 // the variable, we can say something stronger than 'may be uninitialized': 500 // we can say 'either it's used uninitialized or you have dead code'. 501 // 502 // We track the number of successors of a node which have been visited, and 503 // visit a node once we have visited all of its successors. Only edges where 504 // the variable might still be uninitialized are followed. Since a variable 505 // can't transfer from being initialized to being uninitialized, this will 506 // trace out the subgraph which inevitably leads to the use and does not 507 // initialize the variable. We do not want to skip past loops, since their 508 // non-termination might be correlated with the initialization condition. 509 // 510 // For example: 511 // 512 // void f(bool a, bool b) { 513 // block1: int n; 514 // if (a) { 515 // block2: if (b) 516 // block3: n = 1; 517 // block4: } else if (b) { 518 // block5: while (!a) { 519 // block6: do_work(&a); 520 // n = 2; 521 // } 522 // } 523 // block7: if (a) 524 // block8: g(); 525 // block9: return n; 526 // } 527 // 528 // Starting from the maybe-uninitialized use in block 9: 529 // * Block 7 is not visited because we have only visited one of its two 530 // successors. 531 // * Block 8 is visited because we've visited its only successor. 532 // From block 8: 533 // * Block 7 is visited because we've now visited both of its successors. 534 // From block 7: 535 // * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all 536 // of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively). 537 // * Block 3 is not visited because it initializes 'n'. 538 // Now the algorithm terminates, having visited blocks 7 and 8, and having 539 // found the frontier is blocks 2, 4, and 5. 540 // 541 // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2 542 // and 4), so we report that any time either of those edges is taken (in 543 // each case when 'b == false'), 'n' is used uninitialized. 544 SmallVector<const CFGBlock*, 32> Queue; 545 SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0); 546 Queue.push_back(block); 547 // Specify that we've already visited all successors of the starting block. 548 // This has the dual purpose of ensuring we never add it to the queue, and 549 // of marking it as not being a candidate element of the frontier. 550 SuccsVisited[block->getBlockID()] = block->succ_size(); 551 while (!Queue.empty()) { 552 const CFGBlock *B = Queue.pop_back_val(); 553 554 // If the use is always reached from the entry block, make a note of that. 555 if (B == &cfg.getEntry()) 556 Use.setUninitAfterCall(); 557 558 for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end(); 559 I != E; ++I) { 560 const CFGBlock *Pred = *I; 561 if (!Pred) 562 continue; 563 564 Value AtPredExit = vals.getValue(Pred, B, vd); 565 if (AtPredExit == Initialized) 566 // This block initializes the variable. 567 continue; 568 if (AtPredExit == MayUninitialized && 569 vals.getValue(B, nullptr, vd) == Uninitialized) { 570 // This block declares the variable (uninitialized), and is reachable 571 // from a block that initializes the variable. We can't guarantee to 572 // give an earlier location for the diagnostic (and it appears that 573 // this code is intended to be reachable) so give a diagnostic here 574 // and go no further down this path. 575 Use.setUninitAfterDecl(); 576 continue; 577 } 578 579 if (AtPredExit == MayUninitialized) { 580 // If the predecessor's terminator is an "asm goto" that initializes 581 // the variable, then it won't be counted as "initialized" on the 582 // non-fallthrough paths. 583 CFGTerminator term = Pred->getTerminator(); 584 if (const auto *as = dyn_cast_or_null<GCCAsmStmt>(term.getStmt())) { 585 const CFGBlock *fallthrough = *Pred->succ_begin(); 586 if (as->isAsmGoto() && 587 llvm::any_of(as->outputs(), [&](const Expr *output) { 588 return vd == findVar(output).getDecl() && 589 llvm::any_of(as->labels(), 590 [&](const AddrLabelExpr *label) { 591 return label->getLabel()->getStmt() == B->Label && 592 B != fallthrough; 593 }); 594 })) { 595 Use.setUninitAfterDecl(); 596 continue; 597 } 598 } 599 } 600 601 unsigned &SV = SuccsVisited[Pred->getBlockID()]; 602 if (!SV) { 603 // When visiting the first successor of a block, mark all NULL 604 // successors as having been visited. 605 for (CFGBlock::const_succ_iterator SI = Pred->succ_begin(), 606 SE = Pred->succ_end(); 607 SI != SE; ++SI) 608 if (!*SI) 609 ++SV; 610 } 611 612 if (++SV == Pred->succ_size()) 613 // All paths from this block lead to the use and don't initialize the 614 // variable. 615 Queue.push_back(Pred); 616 } 617 } 618 619 // Scan the frontier, looking for blocks where the variable was 620 // uninitialized. 621 for (const auto *Block : cfg) { 622 unsigned BlockID = Block->getBlockID(); 623 const Stmt *Term = Block->getTerminatorStmt(); 624 if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() && 625 Term) { 626 // This block inevitably leads to the use. If we have an edge from here 627 // to a post-dominator block, and the variable is uninitialized on that 628 // edge, we have found a bug. 629 for (CFGBlock::const_succ_iterator I = Block->succ_begin(), 630 E = Block->succ_end(); I != E; ++I) { 631 const CFGBlock *Succ = *I; 632 if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() && 633 vals.getValue(Block, Succ, vd) == Uninitialized) { 634 // Switch cases are a special case: report the label to the caller 635 // as the 'terminator', not the switch statement itself. Suppress 636 // situations where no label matched: we can't be sure that's 637 // possible. 638 if (isa<SwitchStmt>(Term)) { 639 const Stmt *Label = Succ->getLabel(); 640 if (!Label || !isa<SwitchCase>(Label)) 641 // Might not be possible. 642 continue; 643 UninitUse::Branch Branch; 644 Branch.Terminator = Label; 645 Branch.Output = 0; // Ignored. 646 Use.addUninitBranch(Branch); 647 } else { 648 UninitUse::Branch Branch; 649 Branch.Terminator = Term; 650 Branch.Output = I - Block->succ_begin(); 651 Use.addUninitBranch(Branch); 652 } 653 } 654 } 655 } 656 } 657 658 return Use; 659 } 660 }; 661 662 } // namespace 663 664 void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) { 665 Value v = vals[vd]; 666 if (isUninitialized(v)) 667 handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v)); 668 } 669 670 void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) { 671 // This represents an initialization of the 'element' value. 672 if (const auto *DS = dyn_cast<DeclStmt>(FS->getElement())) { 673 const auto *VD = cast<VarDecl>(DS->getSingleDecl()); 674 if (isTrackedVar(VD)) 675 vals[VD] = Initialized; 676 } 677 } 678 679 void TransferFunctions::VisitOMPExecutableDirective( 680 OMPExecutableDirective *ED) { 681 for (Stmt *S : OMPExecutableDirective::used_clauses_children(ED->clauses())) { 682 assert(S && "Expected non-null used-in-clause child."); 683 Visit(S); 684 } 685 if (!ED->isStandaloneDirective()) 686 Visit(ED->getStructuredBlock()); 687 } 688 689 void TransferFunctions::VisitBlockExpr(BlockExpr *be) { 690 const BlockDecl *bd = be->getBlockDecl(); 691 for (const auto &I : bd->captures()) { 692 const VarDecl *vd = I.getVariable(); 693 if (!isTrackedVar(vd)) 694 continue; 695 if (I.isByRef()) { 696 vals[vd] = Initialized; 697 continue; 698 } 699 reportUse(be, vd); 700 } 701 } 702 703 void TransferFunctions::VisitCallExpr(CallExpr *ce) { 704 if (Decl *Callee = ce->getCalleeDecl()) { 705 if (Callee->hasAttr<ReturnsTwiceAttr>()) { 706 // After a call to a function like setjmp or vfork, any variable which is 707 // initialized anywhere within this function may now be initialized. For 708 // now, just assume such a call initializes all variables. FIXME: Only 709 // mark variables as initialized if they have an initializer which is 710 // reachable from here. 711 vals.setAllScratchValues(Initialized); 712 } 713 else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) { 714 // Functions labeled like "analyzer_noreturn" are often used to denote 715 // "panic" functions that in special debug situations can still return, 716 // but for the most part should not be treated as returning. This is a 717 // useful annotation borrowed from the static analyzer that is useful for 718 // suppressing branch-specific false positives when we call one of these 719 // functions but keep pretending the path continues (when in reality the 720 // user doesn't care). 721 vals.setAllScratchValues(Unknown); 722 } 723 } 724 } 725 726 void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) { 727 switch (classification.get(dr)) { 728 case ClassifyRefs::Ignore: 729 break; 730 case ClassifyRefs::Use: 731 reportUse(dr, cast<VarDecl>(dr->getDecl())); 732 break; 733 case ClassifyRefs::Init: 734 vals[cast<VarDecl>(dr->getDecl())] = Initialized; 735 break; 736 case ClassifyRefs::SelfInit: 737 handler.handleSelfInit(cast<VarDecl>(dr->getDecl())); 738 break; 739 } 740 } 741 742 void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) { 743 if (BO->getOpcode() == BO_Assign) { 744 FindVarResult Var = findVar(BO->getLHS()); 745 if (const VarDecl *VD = Var.getDecl()) 746 vals[VD] = Initialized; 747 } 748 } 749 750 void TransferFunctions::VisitDeclStmt(DeclStmt *DS) { 751 for (auto *DI : DS->decls()) { 752 auto *VD = dyn_cast<VarDecl>(DI); 753 if (VD && isTrackedVar(VD)) { 754 if (getSelfInitExpr(VD)) { 755 // If the initializer consists solely of a reference to itself, we 756 // explicitly mark the variable as uninitialized. This allows code 757 // like the following: 758 // 759 // int x = x; 760 // 761 // to deliberately leave a variable uninitialized. Different analysis 762 // clients can detect this pattern and adjust their reporting 763 // appropriately, but we need to continue to analyze subsequent uses 764 // of the variable. 765 vals[VD] = Uninitialized; 766 } else if (VD->getInit()) { 767 // Treat the new variable as initialized. 768 vals[VD] = Initialized; 769 } else { 770 // No initializer: the variable is now uninitialized. This matters 771 // for cases like: 772 // while (...) { 773 // int n; 774 // use(n); 775 // n = 0; 776 // } 777 // FIXME: Mark the variable as uninitialized whenever its scope is 778 // left, since its scope could be re-entered by a jump over the 779 // declaration. 780 vals[VD] = Uninitialized; 781 } 782 } 783 } 784 } 785 786 void TransferFunctions::VisitGCCAsmStmt(GCCAsmStmt *as) { 787 // An "asm goto" statement is a terminator that may initialize some variables. 788 if (!as->isAsmGoto()) 789 return; 790 791 for (const Expr *o : as->outputs()) 792 if (const VarDecl *VD = findVar(o).getDecl()) 793 if (vals[VD] != Initialized) 794 // If the variable isn't initialized by the time we get here, then we 795 // mark it as potentially uninitialized for those cases where it's used 796 // on an indirect path, where it's not guaranteed to be defined. 797 vals[VD] = MayUninitialized; 798 } 799 800 void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) { 801 // If the Objective-C message expression is an implicit no-return that 802 // is not modeled in the CFG, set the tracked dataflow values to Unknown. 803 if (objCNoRet.isImplicitNoReturn(ME)) { 804 vals.setAllScratchValues(Unknown); 805 } 806 } 807 808 //------------------------------------------------------------------------====// 809 // High-level "driver" logic for uninitialized values analysis. 810 //====------------------------------------------------------------------------// 811 812 static bool runOnBlock(const CFGBlock *block, const CFG &cfg, 813 AnalysisDeclContext &ac, CFGBlockValues &vals, 814 const ClassifyRefs &classification, 815 llvm::BitVector &wasAnalyzed, 816 UninitVariablesHandler &handler) { 817 wasAnalyzed[block->getBlockID()] = true; 818 vals.resetScratch(); 819 // Merge in values of predecessor blocks. 820 bool isFirst = true; 821 for (CFGBlock::const_pred_iterator I = block->pred_begin(), 822 E = block->pred_end(); I != E; ++I) { 823 const CFGBlock *pred = *I; 824 if (!pred) 825 continue; 826 if (wasAnalyzed[pred->getBlockID()]) { 827 vals.mergeIntoScratch(vals.getValueVector(pred), isFirst); 828 isFirst = false; 829 } 830 } 831 // Apply the transfer function. 832 TransferFunctions tf(vals, cfg, block, ac, classification, handler); 833 for (const auto &I : *block) { 834 if (Optional<CFGStmt> cs = I.getAs<CFGStmt>()) 835 tf.Visit(const_cast<Stmt *>(cs->getStmt())); 836 } 837 CFGTerminator terminator = block->getTerminator(); 838 if (auto *as = dyn_cast_or_null<GCCAsmStmt>(terminator.getStmt())) 839 if (as->isAsmGoto()) 840 tf.Visit(as); 841 return vals.updateValueVectorWithScratch(block); 842 } 843 844 namespace { 845 846 /// PruneBlocksHandler is a special UninitVariablesHandler that is used 847 /// to detect when a CFGBlock has any *potential* use of an uninitialized 848 /// variable. It is mainly used to prune out work during the final 849 /// reporting pass. 850 struct PruneBlocksHandler : public UninitVariablesHandler { 851 /// Records if a CFGBlock had a potential use of an uninitialized variable. 852 llvm::BitVector hadUse; 853 854 /// Records if any CFGBlock had a potential use of an uninitialized variable. 855 bool hadAnyUse = false; 856 857 /// The current block to scribble use information. 858 unsigned currentBlock = 0; 859 860 PruneBlocksHandler(unsigned numBlocks) : hadUse(numBlocks, false) {} 861 862 ~PruneBlocksHandler() override = default; 863 864 void handleUseOfUninitVariable(const VarDecl *vd, 865 const UninitUse &use) override { 866 hadUse[currentBlock] = true; 867 hadAnyUse = true; 868 } 869 870 /// Called when the uninitialized variable analysis detects the 871 /// idiom 'int x = x'. All other uses of 'x' within the initializer 872 /// are handled by handleUseOfUninitVariable. 873 void handleSelfInit(const VarDecl *vd) override { 874 hadUse[currentBlock] = true; 875 hadAnyUse = true; 876 } 877 }; 878 879 } // namespace 880 881 void clang::runUninitializedVariablesAnalysis( 882 const DeclContext &dc, 883 const CFG &cfg, 884 AnalysisDeclContext &ac, 885 UninitVariablesHandler &handler, 886 UninitVariablesAnalysisStats &stats) { 887 CFGBlockValues vals(cfg); 888 vals.computeSetOfDeclarations(dc); 889 if (vals.hasNoDeclarations()) 890 return; 891 892 stats.NumVariablesAnalyzed = vals.getNumEntries(); 893 894 // Precompute which expressions are uses and which are initializations. 895 ClassifyRefs classification(ac); 896 cfg.VisitBlockStmts(classification); 897 898 // Mark all variables uninitialized at the entry. 899 const CFGBlock &entry = cfg.getEntry(); 900 ValueVector &vec = vals.getValueVector(&entry); 901 const unsigned n = vals.getNumEntries(); 902 for (unsigned j = 0; j < n; ++j) { 903 vec[j] = Uninitialized; 904 } 905 906 // Proceed with the workist. 907 ForwardDataflowWorklist worklist(cfg, ac); 908 llvm::BitVector previouslyVisited(cfg.getNumBlockIDs()); 909 worklist.enqueueSuccessors(&cfg.getEntry()); 910 llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false); 911 wasAnalyzed[cfg.getEntry().getBlockID()] = true; 912 PruneBlocksHandler PBH(cfg.getNumBlockIDs()); 913 914 while (const CFGBlock *block = worklist.dequeue()) { 915 PBH.currentBlock = block->getBlockID(); 916 917 // Did the block change? 918 bool changed = runOnBlock(block, cfg, ac, vals, 919 classification, wasAnalyzed, PBH); 920 ++stats.NumBlockVisits; 921 if (changed || !previouslyVisited[block->getBlockID()]) 922 worklist.enqueueSuccessors(block); 923 previouslyVisited[block->getBlockID()] = true; 924 } 925 926 if (!PBH.hadAnyUse) 927 return; 928 929 // Run through the blocks one more time, and report uninitialized variables. 930 for (const auto *block : cfg) 931 if (PBH.hadUse[block->getBlockID()]) { 932 runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler); 933 ++stats.NumBlockVisits; 934 } 935 } 936 937 UninitVariablesHandler::~UninitVariablesHandler() = default; 938