11c1057afSEugene Zelenko //===- UninitializedValues.cpp - Find Uninitialized Values ----------------===//
2a0a5ca14STed Kremenek //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a0a5ca14STed Kremenek //
7a0a5ca14STed Kremenek //===----------------------------------------------------------------------===//
8a0a5ca14STed Kremenek //
9a0a5ca14STed Kremenek // This file implements uninitialized values analysis for source-level CFGs.
10a0a5ca14STed Kremenek //
11a0a5ca14STed Kremenek //===----------------------------------------------------------------------===//
12a0a5ca14STed Kremenek 
131c1057afSEugene Zelenko #include "clang/Analysis/Analyses/UninitializedValues.h"
14ea70eb30SBenjamin Kramer #include "clang/AST/Attr.h"
15a0a5ca14STed Kremenek #include "clang/AST/Decl.h"
161c1057afSEugene Zelenko #include "clang/AST/DeclBase.h"
171c1057afSEugene Zelenko #include "clang/AST/Expr.h"
181c1057afSEugene Zelenko #include "clang/AST/OperationKinds.h"
191c1057afSEugene Zelenko #include "clang/AST/Stmt.h"
201c1057afSEugene Zelenko #include "clang/AST/StmtObjC.h"
21a7f94ce8SJordan Rose #include "clang/AST/StmtVisitor.h"
221c1057afSEugene Zelenko #include "clang/AST/Type.h"
2327720765SArtyom Skrobov #include "clang/Analysis/Analyses/PostOrderCFGView.h"
2450657f6bSGeorge Karpenkov #include "clang/Analysis/AnalysisDeclContext.h"
25ea70eb30SBenjamin Kramer #include "clang/Analysis/CFG.h"
26edf22edcSTed Kremenek #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h"
2705c7dc66SGabor Horvath #include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
281c1057afSEugene Zelenko #include "clang/Basic/LLVM.h"
291c1057afSEugene Zelenko #include "llvm/ADT/BitVector.h"
30ea70eb30SBenjamin Kramer #include "llvm/ADT/DenseMap.h"
311c1057afSEugene Zelenko #include "llvm/ADT/None.h"
32ea70eb30SBenjamin Kramer #include "llvm/ADT/Optional.h"
33ea70eb30SBenjamin Kramer #include "llvm/ADT/PackedVector.h"
34ea70eb30SBenjamin Kramer #include "llvm/ADT/SmallBitVector.h"
35ea70eb30SBenjamin Kramer #include "llvm/ADT/SmallVector.h"
361c1057afSEugene Zelenko #include "llvm/Support/Casting.h"
371c1057afSEugene Zelenko #include <algorithm>
381c1057afSEugene Zelenko #include <cassert>
39a0a5ca14STed Kremenek 
40a0a5ca14STed Kremenek using namespace clang;
41a0a5ca14STed Kremenek 
42130b8d4eSRichard Smith #define DEBUG_LOGGING 0
43130b8d4eSRichard Smith 
isTrackedVar(const VarDecl * vd,const DeclContext * dc)44a0a5ca14STed Kremenek static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) {
45c15a4e4bSTed Kremenek   if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() &&
46d88b44d4SRichard Smith       !vd->isExceptionVariable() && !vd->isInitCapture() &&
47c38498f0SRichard Smith       !vd->isImplicit() && vd->getDeclContext() == dc) {
48c15a4e4bSTed Kremenek     QualType ty = vd->getType();
4927ee25f7SManuel Klimek     return ty->isScalarType() || ty->isVectorType() || ty->isRecordType();
50c15a4e4bSTed Kremenek   }
51c15a4e4bSTed Kremenek   return false;
52a0a5ca14STed Kremenek }
53a0a5ca14STed Kremenek 
54a0a5ca14STed Kremenek //------------------------------------------------------------------------====//
55a895fe99STed Kremenek // DeclToIndex: a mapping from Decls we track to value indices.
56a0a5ca14STed Kremenek //====------------------------------------------------------------------------//
57a0a5ca14STed Kremenek 
58a0a5ca14STed Kremenek namespace {
591c1057afSEugene Zelenko 
60a895fe99STed Kremenek class DeclToIndex {
61a0a5ca14STed Kremenek   llvm::DenseMap<const VarDecl *, unsigned> map;
621c1057afSEugene Zelenko 
63a0a5ca14STed Kremenek public:
641c1057afSEugene Zelenko   DeclToIndex() = default;
65a0a5ca14STed Kremenek 
66a0a5ca14STed Kremenek   /// Compute the actual mapping from declarations to bits.
67a0a5ca14STed Kremenek   void computeMap(const DeclContext &dc);
68a0a5ca14STed Kremenek 
69a0a5ca14STed Kremenek   /// Return the number of declarations in the map.
size() const70a0a5ca14STed Kremenek   unsigned size() const { return map.size(); }
71a0a5ca14STed Kremenek 
72a0a5ca14STed Kremenek   /// Returns the bit vector index for a given declaration.
7305785d16SDavid Blaikie   Optional<unsigned> getValueIndex(const VarDecl *d) const;
74a0a5ca14STed Kremenek };
751c1057afSEugene Zelenko 
761c1057afSEugene Zelenko } // namespace
77a0a5ca14STed Kremenek 
computeMap(const DeclContext & dc)78a895fe99STed Kremenek void DeclToIndex::computeMap(const DeclContext &dc) {
79a0a5ca14STed Kremenek   unsigned count = 0;
80a0a5ca14STed Kremenek   DeclContext::specific_decl_iterator<VarDecl> I(dc.decls_begin()),
81a0a5ca14STed Kremenek                                                E(dc.decls_end());
82a0a5ca14STed Kremenek   for ( ; I != E; ++I) {
8340ed2973SDavid Blaikie     const VarDecl *vd = *I;
84a0a5ca14STed Kremenek     if (isTrackedVar(vd, &dc))
85a0a5ca14STed Kremenek       map[vd] = count++;
86a0a5ca14STed Kremenek   }
87a0a5ca14STed Kremenek }
88a0a5ca14STed Kremenek 
getValueIndex(const VarDecl * d) const8905785d16SDavid Blaikie Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const {
9003325c4bSTed Kremenek   llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d);
91a0a5ca14STed Kremenek   if (I == map.end())
927a30dc53SDavid Blaikie     return None;
93a0a5ca14STed Kremenek   return I->second;
94a0a5ca14STed Kremenek }
95a0a5ca14STed Kremenek 
96a0a5ca14STed Kremenek //------------------------------------------------------------------------====//
97a0a5ca14STed Kremenek // CFGBlockValues: dataflow values for CFG blocks.
98a0a5ca14STed Kremenek //====------------------------------------------------------------------------//
99a0a5ca14STed Kremenek 
100c8c4e5f3STed Kremenek // These values are defined in such a way that a merge can be done using
101c8c4e5f3STed Kremenek // a bitwise OR.
102c8c4e5f3STed Kremenek enum Value { Unknown = 0x0,         /* 00 */
103c8c4e5f3STed Kremenek              Initialized = 0x1,     /* 01 */
104c8c4e5f3STed Kremenek              Uninitialized = 0x2,   /* 10 */
105c8c4e5f3STed Kremenek              MayUninitialized = 0x3 /* 11 */ };
106c8c4e5f3STed Kremenek 
isUninitialized(const Value v)107c8c4e5f3STed Kremenek static bool isUninitialized(const Value v) {
108c8c4e5f3STed Kremenek   return v >= Uninitialized;
109c8c4e5f3STed Kremenek }
1101c1057afSEugene Zelenko 
isAlwaysUninit(const Value v)111c8c4e5f3STed Kremenek static bool isAlwaysUninit(const Value v) {
112c8c4e5f3STed Kremenek   return v == Uninitialized;
113c8c4e5f3STed Kremenek }
114d3def384STed Kremenek 
1158aef596dSBenjamin Kramer namespace {
1169b15c962STed Kremenek 
1171c1057afSEugene Zelenko using ValueVector = llvm::PackedVector<Value, 2, llvm::SmallBitVector>;
118a0a5ca14STed Kremenek 
119a0a5ca14STed Kremenek class CFGBlockValues {
120a0a5ca14STed Kremenek   const CFG &cfg;
1215721daaeSBenjamin Kramer   SmallVector<ValueVector, 8> vals;
122a895fe99STed Kremenek   ValueVector scratch;
123e3ae0a4cSTed Kremenek   DeclToIndex declToIndex;
1241c1057afSEugene Zelenko 
125a0a5ca14STed Kremenek public:
126a0a5ca14STed Kremenek   CFGBlockValues(const CFG &cfg);
127a0a5ca14STed Kremenek 
getNumEntries() const12837881934STed Kremenek   unsigned getNumEntries() const { return declToIndex.size(); }
12937881934STed Kremenek 
130a0a5ca14STed Kremenek   void computeSetOfDeclarations(const DeclContext &dc);
1311c1057afSEugene Zelenko 
getValueVector(const CFGBlock * block)1326080d321STed Kremenek   ValueVector &getValueVector(const CFGBlock *block) {
1335721daaeSBenjamin Kramer     return vals[block->getBlockID()];
1346080d321STed Kremenek   }
135a0a5ca14STed Kremenek 
136b721e301SRichard Smith   void setAllScratchValues(Value V);
137a895fe99STed Kremenek   void mergeIntoScratch(ValueVector const &source, bool isFirst);
138a895fe99STed Kremenek   bool updateValueVectorWithScratch(const CFGBlock *block);
139a0a5ca14STed Kremenek 
hasNoDeclarations() const140a0a5ca14STed Kremenek   bool hasNoDeclarations() const {
141e3ae0a4cSTed Kremenek     return declToIndex.size() == 0;
142a0a5ca14STed Kremenek   }
143a0a5ca14STed Kremenek 
144a0a5ca14STed Kremenek   void resetScratch();
145a0a5ca14STed Kremenek 
146a895fe99STed Kremenek   ValueVector::reference operator[](const VarDecl *vd);
1474323bf8eSRichard Smith 
getValue(const CFGBlock * block,const CFGBlock * dstBlock,const VarDecl * vd)1484323bf8eSRichard Smith   Value getValue(const CFGBlock *block, const CFGBlock *dstBlock,
1494323bf8eSRichard Smith                  const VarDecl *vd) {
15005785d16SDavid Blaikie     const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
15197afce08SKazu Hirata     assert(idx);
152*cb2c8f69SKazu Hirata     return getValueVector(block)[idx.value()];
1534323bf8eSRichard Smith   }
154a0a5ca14STed Kremenek };
1551c1057afSEugene Zelenko 
1561c1057afSEugene Zelenko } // namespace
157a0a5ca14STed Kremenek 
CFGBlockValues(const CFG & c)1586080d321STed Kremenek CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {}
159a0a5ca14STed Kremenek 
computeSetOfDeclarations(const DeclContext & dc)160a0a5ca14STed Kremenek void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) {
161e3ae0a4cSTed Kremenek   declToIndex.computeMap(dc);
1626080d321STed Kremenek   unsigned decls = declToIndex.size();
1636080d321STed Kremenek   scratch.resize(decls);
1646080d321STed Kremenek   unsigned n = cfg.getNumBlockIDs();
1656080d321STed Kremenek   if (!n)
1666080d321STed Kremenek     return;
1676080d321STed Kremenek   vals.resize(n);
1681c1057afSEugene Zelenko   for (auto &val : vals)
1691c1057afSEugene Zelenko     val.resize(decls);
170a0a5ca14STed Kremenek }
171a0a5ca14STed Kremenek 
172130b8d4eSRichard Smith #if DEBUG_LOGGING
printVector(const CFGBlock * block,ValueVector & bv,unsigned num)173a895fe99STed Kremenek static void printVector(const CFGBlock *block, ValueVector &bv,
174a0a5ca14STed Kremenek                         unsigned num) {
175a0a5ca14STed Kremenek   llvm::errs() << block->getBlockID() << " :";
1761c1057afSEugene Zelenko   for (const auto &i : bv)
1771c1057afSEugene Zelenko     llvm::errs() << ' ' << i;
178a0a5ca14STed Kremenek   llvm::errs() << " : " << num << '\n';
179a0a5ca14STed Kremenek }
180a0a5ca14STed Kremenek #endif
181a0a5ca14STed Kremenek 
setAllScratchValues(Value V)182b721e301SRichard Smith void CFGBlockValues::setAllScratchValues(Value V) {
183b721e301SRichard Smith   for (unsigned I = 0, E = scratch.size(); I != E; ++I)
184b721e301SRichard Smith     scratch[I] = V;
185b721e301SRichard Smith }
186b721e301SRichard Smith 
mergeIntoScratch(ValueVector const & source,bool isFirst)187f8fd4d49STed Kremenek void CFGBlockValues::mergeIntoScratch(ValueVector const &source,
188f8fd4d49STed Kremenek                                       bool isFirst) {
189f8fd4d49STed Kremenek   if (isFirst)
190f8fd4d49STed Kremenek     scratch = source;
191f8fd4d49STed Kremenek   else
192f8fd4d49STed Kremenek     scratch |= source;
193f8fd4d49STed Kremenek }
194f8fd4d49STed Kremenek 
updateValueVectorWithScratch(const CFGBlock * block)195a895fe99STed Kremenek bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) {
1966080d321STed Kremenek   ValueVector &dst = getValueVector(block);
197a0a5ca14STed Kremenek   bool changed = (dst != scratch);
198a0a5ca14STed Kremenek   if (changed)
199a0a5ca14STed Kremenek     dst = scratch;
200130b8d4eSRichard Smith #if DEBUG_LOGGING
201a0a5ca14STed Kremenek   printVector(block, scratch, 0);
202a0a5ca14STed Kremenek #endif
203a0a5ca14STed Kremenek   return changed;
204a0a5ca14STed Kremenek }
205a0a5ca14STed Kremenek 
resetScratch()206a0a5ca14STed Kremenek void CFGBlockValues::resetScratch() {
207a0a5ca14STed Kremenek   scratch.reset();
208a0a5ca14STed Kremenek }
209a0a5ca14STed Kremenek 
operator [](const VarDecl * vd)210a895fe99STed Kremenek ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
21105785d16SDavid Blaikie   const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
21297afce08SKazu Hirata   assert(idx);
213*cb2c8f69SKazu Hirata   return scratch[idx.value()];
214a0a5ca14STed Kremenek }
215a0a5ca14STed Kremenek 
216a0a5ca14STed Kremenek //------------------------------------------------------------------------====//
2176376d1fdSRichard Smith // Classification of DeclRefExprs as use or initialization.
218a0a5ca14STed Kremenek //====------------------------------------------------------------------------//
219a0a5ca14STed Kremenek 
220a0a5ca14STed Kremenek namespace {
2211c1057afSEugene Zelenko 
222a0a5ca14STed Kremenek class FindVarResult {
223a0a5ca14STed Kremenek   const VarDecl *vd;
224a0a5ca14STed Kremenek   const DeclRefExpr *dr;
2251c1057afSEugene Zelenko 
226a0a5ca14STed Kremenek public:
FindVarResult(const VarDecl * vd,const DeclRefExpr * dr)2276376d1fdSRichard Smith   FindVarResult(const VarDecl *vd, const DeclRefExpr *dr) : vd(vd), dr(dr) {}
228a0a5ca14STed Kremenek 
getDeclRefExpr() const229a0a5ca14STed Kremenek   const DeclRefExpr *getDeclRefExpr() const { return dr; }
getDecl() const230a0a5ca14STed Kremenek   const VarDecl *getDecl() const { return vd; }
231a0a5ca14STed Kremenek };
232a0a5ca14STed Kremenek 
2331c1057afSEugene Zelenko } // namespace
2341c1057afSEugene Zelenko 
stripCasts(ASTContext & C,const Expr * Ex)2356376d1fdSRichard Smith static const Expr *stripCasts(ASTContext &C, const Expr *Ex) {
2366376d1fdSRichard Smith   while (Ex) {
2376376d1fdSRichard Smith     Ex = Ex->IgnoreParenNoopCasts(C);
2381c1057afSEugene Zelenko     if (const auto *CE = dyn_cast<CastExpr>(Ex)) {
2396376d1fdSRichard Smith       if (CE->getCastKind() == CK_LValueBitCast) {
2406376d1fdSRichard Smith         Ex = CE->getSubExpr();
2416376d1fdSRichard Smith         continue;
2426376d1fdSRichard Smith       }
2436376d1fdSRichard Smith     }
2446376d1fdSRichard Smith     break;
2456376d1fdSRichard Smith   }
2466376d1fdSRichard Smith   return Ex;
2476376d1fdSRichard Smith }
2486376d1fdSRichard Smith 
2496376d1fdSRichard Smith /// If E is an expression comprising a reference to a single variable, find that
2506376d1fdSRichard Smith /// variable.
findVar(const Expr * E,const DeclContext * DC)2516376d1fdSRichard Smith static FindVarResult findVar(const Expr *E, const DeclContext *DC) {
2521c1057afSEugene Zelenko   if (const auto *DRE =
2536376d1fdSRichard Smith           dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E)))
2541c1057afSEugene Zelenko     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2556376d1fdSRichard Smith       if (isTrackedVar(VD, DC))
2566376d1fdSRichard Smith         return FindVarResult(VD, DRE);
25725542943SCraig Topper   return FindVarResult(nullptr, nullptr);
2586376d1fdSRichard Smith }
2596376d1fdSRichard Smith 
2601c1057afSEugene Zelenko namespace {
2611c1057afSEugene Zelenko 
2629fc8faf9SAdrian Prantl /// Classify each DeclRefExpr as an initialization or a use. Any
2636376d1fdSRichard Smith /// DeclRefExpr which isn't explicitly classified will be assumed to have
2646376d1fdSRichard Smith /// escaped the analysis and will be treated as an initialization.
2656376d1fdSRichard Smith class ClassifyRefs : public StmtVisitor<ClassifyRefs> {
2666376d1fdSRichard Smith public:
2676376d1fdSRichard Smith   enum Class {
2686376d1fdSRichard Smith     Init,
2696376d1fdSRichard Smith     Use,
2706376d1fdSRichard Smith     SelfInit,
271170b6869SZequan Wu     ConstRefUse,
2726376d1fdSRichard Smith     Ignore
2736376d1fdSRichard Smith   };
2746376d1fdSRichard Smith 
2756376d1fdSRichard Smith private:
2766376d1fdSRichard Smith   const DeclContext *DC;
2776376d1fdSRichard Smith   llvm::DenseMap<const DeclRefExpr *, Class> Classification;
2786376d1fdSRichard Smith 
isTrackedVar(const VarDecl * VD) const2796376d1fdSRichard Smith   bool isTrackedVar(const VarDecl *VD) const {
2806376d1fdSRichard Smith     return ::isTrackedVar(VD, DC);
2816376d1fdSRichard Smith   }
2826376d1fdSRichard Smith 
2836376d1fdSRichard Smith   void classify(const Expr *E, Class C);
2846376d1fdSRichard Smith 
2856376d1fdSRichard Smith public:
ClassifyRefs(AnalysisDeclContext & AC)2866376d1fdSRichard Smith   ClassifyRefs(AnalysisDeclContext &AC) : DC(cast<DeclContext>(AC.getDecl())) {}
2876376d1fdSRichard Smith 
2886376d1fdSRichard Smith   void VisitDeclStmt(DeclStmt *DS);
2896376d1fdSRichard Smith   void VisitUnaryOperator(UnaryOperator *UO);
2906376d1fdSRichard Smith   void VisitBinaryOperator(BinaryOperator *BO);
2916376d1fdSRichard Smith   void VisitCallExpr(CallExpr *CE);
2926376d1fdSRichard Smith   void VisitCastExpr(CastExpr *CE);
293c2c21ef9SAlexey Bataev   void VisitOMPExecutableDirective(OMPExecutableDirective *ED);
2946376d1fdSRichard Smith 
operator ()(Stmt * S)2956376d1fdSRichard Smith   void operator()(Stmt *S) { Visit(S); }
2966376d1fdSRichard Smith 
get(const DeclRefExpr * DRE) const2976376d1fdSRichard Smith   Class get(const DeclRefExpr *DRE) const {
2986376d1fdSRichard Smith     llvm::DenseMap<const DeclRefExpr*, Class>::const_iterator I
2996376d1fdSRichard Smith         = Classification.find(DRE);
3006376d1fdSRichard Smith     if (I != Classification.end())
3016376d1fdSRichard Smith       return I->second;
3026376d1fdSRichard Smith 
3031c1057afSEugene Zelenko     const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
3046376d1fdSRichard Smith     if (!VD || !isTrackedVar(VD))
3056376d1fdSRichard Smith       return Ignore;
3066376d1fdSRichard Smith 
3076376d1fdSRichard Smith     return Init;
3086376d1fdSRichard Smith   }
3096376d1fdSRichard Smith };
3101c1057afSEugene Zelenko 
3111c1057afSEugene Zelenko } // namespace
3126376d1fdSRichard Smith 
getSelfInitExpr(VarDecl * VD)3136376d1fdSRichard Smith static const DeclRefExpr *getSelfInitExpr(VarDecl *VD) {
3142f8b97f3SPiotr Padlewski   if (VD->getType()->isRecordType())
3152f8b97f3SPiotr Padlewski     return nullptr;
3166376d1fdSRichard Smith   if (Expr *Init = VD->getInit()) {
3171c1057afSEugene Zelenko     const auto *DRE =
3181c1057afSEugene Zelenko         dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init));
3196376d1fdSRichard Smith     if (DRE && DRE->getDecl() == VD)
3206376d1fdSRichard Smith       return DRE;
3216376d1fdSRichard Smith   }
32225542943SCraig Topper   return nullptr;
3236376d1fdSRichard Smith }
3246376d1fdSRichard Smith 
classify(const Expr * E,Class C)3256376d1fdSRichard Smith void ClassifyRefs::classify(const Expr *E, Class C) {
3267ba78c67STed Kremenek   // The result of a ?: could also be an lvalue.
3277ba78c67STed Kremenek   E = E->IgnoreParens();
3281c1057afSEugene Zelenko   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
329abf6ec45SRichard Trieu     classify(CO->getTrueExpr(), C);
3307ba78c67STed Kremenek     classify(CO->getFalseExpr(), C);
3317ba78c67STed Kremenek     return;
3327ba78c67STed Kremenek   }
3337ba78c67STed Kremenek 
3341c1057afSEugene Zelenko   if (const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
335abf6ec45SRichard Trieu     classify(BCO->getFalseExpr(), C);
336abf6ec45SRichard Trieu     return;
337abf6ec45SRichard Trieu   }
338abf6ec45SRichard Trieu 
3391c1057afSEugene Zelenko   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
340abf6ec45SRichard Trieu     classify(OVE->getSourceExpr(), C);
341abf6ec45SRichard Trieu     return;
342abf6ec45SRichard Trieu   }
343abf6ec45SRichard Trieu 
3441c1057afSEugene Zelenko   if (const auto *ME = dyn_cast<MemberExpr>(E)) {
3451c1057afSEugene Zelenko     if (const auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
34627ee25f7SManuel Klimek       if (!VD->isStaticDataMember())
34727ee25f7SManuel Klimek         classify(ME->getBase(), C);
34827ee25f7SManuel Klimek     }
34927ee25f7SManuel Klimek     return;
35027ee25f7SManuel Klimek   }
35127ee25f7SManuel Klimek 
3521c1057afSEugene Zelenko   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
35327ee25f7SManuel Klimek     switch (BO->getOpcode()) {
35427ee25f7SManuel Klimek     case BO_PtrMemD:
35527ee25f7SManuel Klimek     case BO_PtrMemI:
35627ee25f7SManuel Klimek       classify(BO->getLHS(), C);
35727ee25f7SManuel Klimek       return;
35827ee25f7SManuel Klimek     case BO_Comma:
359abf6ec45SRichard Trieu       classify(BO->getRHS(), C);
360abf6ec45SRichard Trieu       return;
36127ee25f7SManuel Klimek     default:
36227ee25f7SManuel Klimek       return;
36327ee25f7SManuel Klimek     }
364abf6ec45SRichard Trieu   }
365abf6ec45SRichard Trieu 
3666376d1fdSRichard Smith   FindVarResult Var = findVar(E, DC);
3676376d1fdSRichard Smith   if (const DeclRefExpr *DRE = Var.getDeclRefExpr())
3686376d1fdSRichard Smith     Classification[DRE] = std::max(Classification[DRE], C);
3696376d1fdSRichard Smith }
3706376d1fdSRichard Smith 
VisitDeclStmt(DeclStmt * DS)3716376d1fdSRichard Smith void ClassifyRefs::VisitDeclStmt(DeclStmt *DS) {
372535bbcccSAaron Ballman   for (auto *DI : DS->decls()) {
3731c1057afSEugene Zelenko     auto *VD = dyn_cast<VarDecl>(DI);
3746376d1fdSRichard Smith     if (VD && isTrackedVar(VD))
3756376d1fdSRichard Smith       if (const DeclRefExpr *DRE = getSelfInitExpr(VD))
3766376d1fdSRichard Smith         Classification[DRE] = SelfInit;
3776376d1fdSRichard Smith   }
3786376d1fdSRichard Smith }
3796376d1fdSRichard Smith 
VisitBinaryOperator(BinaryOperator * BO)3806376d1fdSRichard Smith void ClassifyRefs::VisitBinaryOperator(BinaryOperator *BO) {
3816376d1fdSRichard Smith   // Ignore the evaluation of a DeclRefExpr on the LHS of an assignment. If this
3826376d1fdSRichard Smith   // is not a compound-assignment, we will treat it as initializing the variable
3836376d1fdSRichard Smith   // when TransferFunctions visits it. A compound-assignment does not affect
3846376d1fdSRichard Smith   // whether a variable is uninitialized, and there's no point counting it as a
3856376d1fdSRichard Smith   // use.
386b21dd02eSRichard Smith   if (BO->isCompoundAssignmentOp())
387b21dd02eSRichard Smith     classify(BO->getLHS(), Use);
38827ee25f7SManuel Klimek   else if (BO->getOpcode() == BO_Assign || BO->getOpcode() == BO_Comma)
3896376d1fdSRichard Smith     classify(BO->getLHS(), Ignore);
3906376d1fdSRichard Smith }
3916376d1fdSRichard Smith 
VisitUnaryOperator(UnaryOperator * UO)3926376d1fdSRichard Smith void ClassifyRefs::VisitUnaryOperator(UnaryOperator *UO) {
3936376d1fdSRichard Smith   // Increment and decrement are uses despite there being no lvalue-to-rvalue
3946376d1fdSRichard Smith   // conversion.
3956376d1fdSRichard Smith   if (UO->isIncrementDecrementOp())
3966376d1fdSRichard Smith     classify(UO->getSubExpr(), Use);
3976376d1fdSRichard Smith }
3986376d1fdSRichard Smith 
VisitOMPExecutableDirective(OMPExecutableDirective * ED)399c2c21ef9SAlexey Bataev void ClassifyRefs::VisitOMPExecutableDirective(OMPExecutableDirective *ED) {
400c2c21ef9SAlexey Bataev   for (Stmt *S : OMPExecutableDirective::used_clauses_children(ED->clauses()))
401c2c21ef9SAlexey Bataev     classify(cast<Expr>(S), Use);
402c2c21ef9SAlexey Bataev }
403c2c21ef9SAlexey Bataev 
isPointerToConst(const QualType & QT)40427ee25f7SManuel Klimek static bool isPointerToConst(const QualType &QT) {
40527ee25f7SManuel Klimek   return QT->isAnyPointerType() && QT->getPointeeType().isConstQualified();
40627ee25f7SManuel Klimek }
40727ee25f7SManuel Klimek 
hasTrivialBody(CallExpr * CE)40805470408SZequan Wu static bool hasTrivialBody(CallExpr *CE) {
40905470408SZequan Wu   if (FunctionDecl *FD = CE->getDirectCallee()) {
41005470408SZequan Wu     if (FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
41105470408SZequan Wu       return FTD->getTemplatedDecl()->hasTrivialBody();
41205470408SZequan Wu     return FD->hasTrivialBody();
41305470408SZequan Wu   }
41405470408SZequan Wu   return false;
41505470408SZequan Wu }
41605470408SZequan Wu 
VisitCallExpr(CallExpr * CE)4176376d1fdSRichard Smith void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
41811fd079bSRichard Trieu   // Classify arguments to std::move as used.
419b688d131SNico Weber   if (CE->isCallToStdMove()) {
42027ee25f7SManuel Klimek     // RecordTypes are handled in SemaDeclCXX.cpp.
42127ee25f7SManuel Klimek     if (!CE->getArg(0)->getType()->isRecordType())
42211fd079bSRichard Trieu       classify(CE->getArg(0), Use);
42311fd079bSRichard Trieu     return;
42411fd079bSRichard Trieu   }
42505470408SZequan Wu   bool isTrivialBody = hasTrivialBody(CE);
426170b6869SZequan Wu   // If a value is passed by const pointer to a function,
42727ee25f7SManuel Klimek   // we should not assume that it is initialized by the call, and we
42827ee25f7SManuel Klimek   // conservatively do not assume that it is used.
429170b6869SZequan Wu   // If a value is passed by const reference to a function,
430170b6869SZequan Wu   // it should already be initialized.
4316376d1fdSRichard Smith   for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end();
43227ee25f7SManuel Klimek        I != E; ++I) {
43327ee25f7SManuel Klimek     if ((*I)->isGLValue()) {
43427ee25f7SManuel Klimek       if ((*I)->getType().isConstQualified())
43505470408SZequan Wu         classify((*I), isTrivialBody ? Ignore : ConstRefUse);
43627ee25f7SManuel Klimek     } else if (isPointerToConst((*I)->getType())) {
43727ee25f7SManuel Klimek       const Expr *Ex = stripCasts(DC->getParentASTContext(), *I);
4381c1057afSEugene Zelenko       const auto *UO = dyn_cast<UnaryOperator>(Ex);
43927ee25f7SManuel Klimek       if (UO && UO->getOpcode() == UO_AddrOf)
44027ee25f7SManuel Klimek         Ex = UO->getSubExpr();
44127ee25f7SManuel Klimek       classify(Ex, Ignore);
44227ee25f7SManuel Klimek     }
44327ee25f7SManuel Klimek   }
4446376d1fdSRichard Smith }
4456376d1fdSRichard Smith 
VisitCastExpr(CastExpr * CE)4466376d1fdSRichard Smith void ClassifyRefs::VisitCastExpr(CastExpr *CE) {
4476376d1fdSRichard Smith   if (CE->getCastKind() == CK_LValueToRValue)
4486376d1fdSRichard Smith     classify(CE->getSubExpr(), Use);
4491c1057afSEugene Zelenko   else if (const auto *CSE = dyn_cast<CStyleCastExpr>(CE)) {
4506376d1fdSRichard Smith     if (CSE->getType()->isVoidType()) {
4516376d1fdSRichard Smith       // Squelch any detected load of an uninitialized value if
4526376d1fdSRichard Smith       // we cast it to void.
4536376d1fdSRichard Smith       // e.g. (void) x;
4546376d1fdSRichard Smith       classify(CSE->getSubExpr(), Ignore);
4556376d1fdSRichard Smith     }
4566376d1fdSRichard Smith   }
4576376d1fdSRichard Smith }
4586376d1fdSRichard Smith 
4596376d1fdSRichard Smith //------------------------------------------------------------------------====//
4606376d1fdSRichard Smith // Transfer function for uninitialized values analysis.
4616376d1fdSRichard Smith //====------------------------------------------------------------------------//
4626376d1fdSRichard Smith 
4636376d1fdSRichard Smith namespace {
4641c1057afSEugene Zelenko 
4659e100ea1STed Kremenek class TransferFunctions : public StmtVisitor<TransferFunctions> {
466a0a5ca14STed Kremenek   CFGBlockValues &vals;
467a0a5ca14STed Kremenek   const CFG &cfg;
4684323bf8eSRichard Smith   const CFGBlock *block;
46981ce1c8aSTed Kremenek   AnalysisDeclContext &ac;
4706376d1fdSRichard Smith   const ClassifyRefs &classification;
471edf22edcSTed Kremenek   ObjCNoReturn objCNoRet;
472778a6ed3STed Kremenek   UninitVariablesHandler &handler;
4739e100ea1STed Kremenek 
474a0a5ca14STed Kremenek public:
TransferFunctions(CFGBlockValues & vals,const CFG & cfg,const CFGBlock * block,AnalysisDeclContext & ac,const ClassifyRefs & classification,UninitVariablesHandler & handler)475a0a5ca14STed Kremenek   TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
4764323bf8eSRichard Smith                     const CFGBlock *block, AnalysisDeclContext &ac,
4776376d1fdSRichard Smith                     const ClassifyRefs &classification,
478778a6ed3STed Kremenek                     UninitVariablesHandler &handler)
4796376d1fdSRichard Smith       : vals(vals), cfg(cfg), block(block), ac(ac),
480edf22edcSTed Kremenek         classification(classification), objCNoRet(ac.getASTContext()),
481edf22edcSTed Kremenek         handler(handler) {}
482a0a5ca14STed Kremenek 
4833d31e8b2SRichard Smith   void reportUse(const Expr *ex, const VarDecl *vd);
484170b6869SZequan Wu   void reportConstRefUse(const Expr *ex, const VarDecl *vd);
485a0a5ca14STed Kremenek 
486edf22edcSTed Kremenek   void VisitBinaryOperator(BinaryOperator *bo);
487a0a5ca14STed Kremenek   void VisitBlockExpr(BlockExpr *be);
488b721e301SRichard Smith   void VisitCallExpr(CallExpr *ce);
489a0a5ca14STed Kremenek   void VisitDeclRefExpr(DeclRefExpr *dr);
490edf22edcSTed Kremenek   void VisitDeclStmt(DeclStmt *ds);
49150cac248SBill Wendling   void VisitGCCAsmStmt(GCCAsmStmt *as);
492edf22edcSTed Kremenek   void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS);
493edf22edcSTed Kremenek   void VisitObjCMessageExpr(ObjCMessageExpr *ME);
494c2c21ef9SAlexey Bataev   void VisitOMPExecutableDirective(OMPExecutableDirective *ED);
495a0a5ca14STed Kremenek 
isTrackedVar(const VarDecl * vd)496a0a5ca14STed Kremenek   bool isTrackedVar(const VarDecl *vd) {
497a0a5ca14STed Kremenek     return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl()));
498a0a5ca14STed Kremenek   }
499a0a5ca14STed Kremenek 
findVar(const Expr * ex)5006376d1fdSRichard Smith   FindVarResult findVar(const Expr *ex) {
5016376d1fdSRichard Smith     return ::findVar(ex, cast<DeclContext>(ac.getDecl()));
5026376d1fdSRichard Smith   }
5036376d1fdSRichard Smith 
getUninitUse(const Expr * ex,const VarDecl * vd,Value v)5044323bf8eSRichard Smith   UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) {
5054323bf8eSRichard Smith     UninitUse Use(ex, isAlwaysUninit(v));
5064323bf8eSRichard Smith 
5074323bf8eSRichard Smith     assert(isUninitialized(v));
5084323bf8eSRichard Smith     if (Use.getKind() == UninitUse::Always)
5094323bf8eSRichard Smith       return Use;
5104323bf8eSRichard Smith 
5114323bf8eSRichard Smith     // If an edge which leads unconditionally to this use did not initialize
5124323bf8eSRichard Smith     // the variable, we can say something stronger than 'may be uninitialized':
5134323bf8eSRichard Smith     // we can say 'either it's used uninitialized or you have dead code'.
5144323bf8eSRichard Smith     //
5154323bf8eSRichard Smith     // We track the number of successors of a node which have been visited, and
5164323bf8eSRichard Smith     // visit a node once we have visited all of its successors. Only edges where
5174323bf8eSRichard Smith     // the variable might still be uninitialized are followed. Since a variable
5184323bf8eSRichard Smith     // can't transfer from being initialized to being uninitialized, this will
5194323bf8eSRichard Smith     // trace out the subgraph which inevitably leads to the use and does not
5204323bf8eSRichard Smith     // initialize the variable. We do not want to skip past loops, since their
5214323bf8eSRichard Smith     // non-termination might be correlated with the initialization condition.
5224323bf8eSRichard Smith     //
5234323bf8eSRichard Smith     // For example:
5244323bf8eSRichard Smith     //
5254323bf8eSRichard Smith     //         void f(bool a, bool b) {
5264323bf8eSRichard Smith     // block1:   int n;
5274323bf8eSRichard Smith     //           if (a) {
5284323bf8eSRichard Smith     // block2:     if (b)
5294323bf8eSRichard Smith     // block3:       n = 1;
5304323bf8eSRichard Smith     // block4:   } else if (b) {
5314323bf8eSRichard Smith     // block5:     while (!a) {
5324323bf8eSRichard Smith     // block6:       do_work(&a);
5334323bf8eSRichard Smith     //               n = 2;
5344323bf8eSRichard Smith     //             }
5354323bf8eSRichard Smith     //           }
5364323bf8eSRichard Smith     // block7:   if (a)
5374323bf8eSRichard Smith     // block8:     g();
5384323bf8eSRichard Smith     // block9:   return n;
5394323bf8eSRichard Smith     //         }
5404323bf8eSRichard Smith     //
5414323bf8eSRichard Smith     // Starting from the maybe-uninitialized use in block 9:
5424323bf8eSRichard Smith     //  * Block 7 is not visited because we have only visited one of its two
5434323bf8eSRichard Smith     //    successors.
5444323bf8eSRichard Smith     //  * Block 8 is visited because we've visited its only successor.
5454323bf8eSRichard Smith     // From block 8:
5464323bf8eSRichard Smith     //  * Block 7 is visited because we've now visited both of its successors.
5474323bf8eSRichard Smith     // From block 7:
5484323bf8eSRichard Smith     //  * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all
5494323bf8eSRichard Smith     //    of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively).
5504323bf8eSRichard Smith     //  * Block 3 is not visited because it initializes 'n'.
5514323bf8eSRichard Smith     // Now the algorithm terminates, having visited blocks 7 and 8, and having
5524323bf8eSRichard Smith     // found the frontier is blocks 2, 4, and 5.
5534323bf8eSRichard Smith     //
5544323bf8eSRichard Smith     // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2
5554323bf8eSRichard Smith     // and 4), so we report that any time either of those edges is taken (in
5564323bf8eSRichard Smith     // each case when 'b == false'), 'n' is used uninitialized.
557f857950dSDmitri Gribenko     SmallVector<const CFGBlock*, 32> Queue;
558f857950dSDmitri Gribenko     SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0);
5594323bf8eSRichard Smith     Queue.push_back(block);
5604323bf8eSRichard Smith     // Specify that we've already visited all successors of the starting block.
5614323bf8eSRichard Smith     // This has the dual purpose of ensuring we never add it to the queue, and
5624323bf8eSRichard Smith     // of marking it as not being a candidate element of the frontier.
5634323bf8eSRichard Smith     SuccsVisited[block->getBlockID()] = block->succ_size();
5644323bf8eSRichard Smith     while (!Queue.empty()) {
56525284cc9SRobert Wilhelm       const CFGBlock *B = Queue.pop_back_val();
566ba8071ecSRichard Smith 
567ba8071ecSRichard Smith       // If the use is always reached from the entry block, make a note of that.
568ba8071ecSRichard Smith       if (B == &cfg.getEntry())
569ba8071ecSRichard Smith         Use.setUninitAfterCall();
570ba8071ecSRichard Smith 
5714323bf8eSRichard Smith       for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end();
5724323bf8eSRichard Smith            I != E; ++I) {
5734323bf8eSRichard Smith         const CFGBlock *Pred = *I;
5744b6fee6cSTed Kremenek         if (!Pred)
5754b6fee6cSTed Kremenek           continue;
5764b6fee6cSTed Kremenek 
577ba8071ecSRichard Smith         Value AtPredExit = vals.getValue(Pred, B, vd);
578ba8071ecSRichard Smith         if (AtPredExit == Initialized)
5794323bf8eSRichard Smith           // This block initializes the variable.
5804323bf8eSRichard Smith           continue;
581ba8071ecSRichard Smith         if (AtPredExit == MayUninitialized &&
58225542943SCraig Topper             vals.getValue(B, nullptr, vd) == Uninitialized) {
583ba8071ecSRichard Smith           // This block declares the variable (uninitialized), and is reachable
584ba8071ecSRichard Smith           // from a block that initializes the variable. We can't guarantee to
585ba8071ecSRichard Smith           // give an earlier location for the diagnostic (and it appears that
586ba8071ecSRichard Smith           // this code is intended to be reachable) so give a diagnostic here
587ba8071ecSRichard Smith           // and go no further down this path.
588ba8071ecSRichard Smith           Use.setUninitAfterDecl();
589ba8071ecSRichard Smith           continue;
590ba8071ecSRichard Smith         }
5914323bf8eSRichard Smith 
59272aa619aSBill Wendling         if (AtPredExit == MayUninitialized) {
59372aa619aSBill Wendling           // If the predecessor's terminator is an "asm goto" that initializes
594c4582a68SBill Wendling           // the variable, then don't count it as "initialized" on the indirect
595c4582a68SBill Wendling           // paths.
59672aa619aSBill Wendling           CFGTerminator term = Pred->getTerminator();
59772aa619aSBill Wendling           if (const auto *as = dyn_cast_or_null<GCCAsmStmt>(term.getStmt())) {
59872aa619aSBill Wendling             const CFGBlock *fallthrough = *Pred->succ_begin();
59972aa619aSBill Wendling             if (as->isAsmGoto() &&
60072aa619aSBill Wendling                 llvm::any_of(as->outputs(), [&](const Expr *output) {
60172aa619aSBill Wendling                     return vd == findVar(output).getDecl() &&
60272aa619aSBill Wendling                         llvm::any_of(as->labels(),
60372aa619aSBill Wendling                                      [&](const AddrLabelExpr *label) {
60472aa619aSBill Wendling                           return label->getLabel()->getStmt() == B->Label &&
60572aa619aSBill Wendling                               B != fallthrough;
60672aa619aSBill Wendling                         });
60772aa619aSBill Wendling                 })) {
60872aa619aSBill Wendling               Use.setUninitAfterDecl();
60972aa619aSBill Wendling               continue;
61072aa619aSBill Wendling             }
61172aa619aSBill Wendling           }
61272aa619aSBill Wendling         }
61372aa619aSBill Wendling 
614130b8d4eSRichard Smith         unsigned &SV = SuccsVisited[Pred->getBlockID()];
615130b8d4eSRichard Smith         if (!SV) {
616130b8d4eSRichard Smith           // When visiting the first successor of a block, mark all NULL
617130b8d4eSRichard Smith           // successors as having been visited.
618130b8d4eSRichard Smith           for (CFGBlock::const_succ_iterator SI = Pred->succ_begin(),
619130b8d4eSRichard Smith                                              SE = Pred->succ_end();
620130b8d4eSRichard Smith                SI != SE; ++SI)
621130b8d4eSRichard Smith             if (!*SI)
622130b8d4eSRichard Smith               ++SV;
623130b8d4eSRichard Smith         }
624130b8d4eSRichard Smith 
625130b8d4eSRichard Smith         if (++SV == Pred->succ_size())
6264323bf8eSRichard Smith           // All paths from this block lead to the use and don't initialize the
6274323bf8eSRichard Smith           // variable.
6284323bf8eSRichard Smith           Queue.push_back(Pred);
6294323bf8eSRichard Smith       }
6304323bf8eSRichard Smith     }
6314323bf8eSRichard Smith 
6324323bf8eSRichard Smith     // Scan the frontier, looking for blocks where the variable was
6334323bf8eSRichard Smith     // uninitialized.
6341c1057afSEugene Zelenko     for (const auto *Block : cfg) {
6354323bf8eSRichard Smith       unsigned BlockID = Block->getBlockID();
6364e53032dSArtem Dergachev       const Stmt *Term = Block->getTerminatorStmt();
6374323bf8eSRichard Smith       if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() &&
6384323bf8eSRichard Smith           Term) {
6394323bf8eSRichard Smith         // This block inevitably leads to the use. If we have an edge from here
6404323bf8eSRichard Smith         // to a post-dominator block, and the variable is uninitialized on that
6414323bf8eSRichard Smith         // edge, we have found a bug.
6424323bf8eSRichard Smith         for (CFGBlock::const_succ_iterator I = Block->succ_begin(),
6434323bf8eSRichard Smith              E = Block->succ_end(); I != E; ++I) {
6444323bf8eSRichard Smith           const CFGBlock *Succ = *I;
6454323bf8eSRichard Smith           if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() &&
6464323bf8eSRichard Smith               vals.getValue(Block, Succ, vd) == Uninitialized) {
6474323bf8eSRichard Smith             // Switch cases are a special case: report the label to the caller
6484323bf8eSRichard Smith             // as the 'terminator', not the switch statement itself. Suppress
6494323bf8eSRichard Smith             // situations where no label matched: we can't be sure that's
6504323bf8eSRichard Smith             // possible.
6514323bf8eSRichard Smith             if (isa<SwitchStmt>(Term)) {
6524323bf8eSRichard Smith               const Stmt *Label = Succ->getLabel();
6534323bf8eSRichard Smith               if (!Label || !isa<SwitchCase>(Label))
6544323bf8eSRichard Smith                 // Might not be possible.
6554323bf8eSRichard Smith                 continue;
6564323bf8eSRichard Smith               UninitUse::Branch Branch;
6574323bf8eSRichard Smith               Branch.Terminator = Label;
6584323bf8eSRichard Smith               Branch.Output = 0; // Ignored.
6594323bf8eSRichard Smith               Use.addUninitBranch(Branch);
6604323bf8eSRichard Smith             } else {
6614323bf8eSRichard Smith               UninitUse::Branch Branch;
6624323bf8eSRichard Smith               Branch.Terminator = Term;
6634323bf8eSRichard Smith               Branch.Output = I - Block->succ_begin();
6644323bf8eSRichard Smith               Use.addUninitBranch(Branch);
6654323bf8eSRichard Smith             }
6664323bf8eSRichard Smith           }
6674323bf8eSRichard Smith         }
6684323bf8eSRichard Smith       }
6694323bf8eSRichard Smith     }
6704323bf8eSRichard Smith 
6714323bf8eSRichard Smith     return Use;
6724323bf8eSRichard Smith   }
673a0a5ca14STed Kremenek };
6741c1057afSEugene Zelenko 
6751c1057afSEugene Zelenko } // namespace
676a0a5ca14STed Kremenek 
reportUse(const Expr * ex,const VarDecl * vd)6773d31e8b2SRichard Smith void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) {
6783d31e8b2SRichard Smith   Value v = vals[vd];
6793d31e8b2SRichard Smith   if (isUninitialized(v))
680778a6ed3STed Kremenek     handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v));
681a0a5ca14STed Kremenek }
682a0a5ca14STed Kremenek 
reportConstRefUse(const Expr * ex,const VarDecl * vd)683170b6869SZequan Wu void TransferFunctions::reportConstRefUse(const Expr *ex, const VarDecl *vd) {
684170b6869SZequan Wu   Value v = vals[vd];
6857096e04aSFangrui Song   if (isAlwaysUninit(v))
686170b6869SZequan Wu     handler.handleConstRefUseOfUninitVariable(vd, getUninitUse(ex, vd, v));
687170b6869SZequan Wu }
688170b6869SZequan Wu 
VisitObjCForCollectionStmt(ObjCForCollectionStmt * FS)6896376d1fdSRichard Smith void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) {
690a0a5ca14STed Kremenek   // This represents an initialization of the 'element' value.
6911c1057afSEugene Zelenko   if (const auto *DS = dyn_cast<DeclStmt>(FS->getElement())) {
6921c1057afSEugene Zelenko     const auto *VD = cast<VarDecl>(DS->getSingleDecl());
6936376d1fdSRichard Smith     if (isTrackedVar(VD))
6946376d1fdSRichard Smith       vals[VD] = Initialized;
695a0a5ca14STed Kremenek   }
696a0a5ca14STed Kremenek }
697a0a5ca14STed Kremenek 
VisitOMPExecutableDirective(OMPExecutableDirective * ED)698c2c21ef9SAlexey Bataev void TransferFunctions::VisitOMPExecutableDirective(
699c2c21ef9SAlexey Bataev     OMPExecutableDirective *ED) {
700c2c21ef9SAlexey Bataev   for (Stmt *S : OMPExecutableDirective::used_clauses_children(ED->clauses())) {
701c2c21ef9SAlexey Bataev     assert(S && "Expected non-null used-in-clause child.");
702c2c21ef9SAlexey Bataev     Visit(S);
703c2c21ef9SAlexey Bataev   }
704c2c21ef9SAlexey Bataev   if (!ED->isStandaloneDirective())
705c2c21ef9SAlexey Bataev     Visit(ED->getStructuredBlock());
706c2c21ef9SAlexey Bataev }
707c2c21ef9SAlexey Bataev 
VisitBlockExpr(BlockExpr * be)708a0a5ca14STed Kremenek void TransferFunctions::VisitBlockExpr(BlockExpr *be) {
70977361761STed Kremenek   const BlockDecl *bd = be->getBlockDecl();
7109371dd22SAaron Ballman   for (const auto &I : bd->captures()) {
7119371dd22SAaron Ballman     const VarDecl *vd = I.getVariable();
71277361761STed Kremenek     if (!isTrackedVar(vd))
71377361761STed Kremenek       continue;
7149371dd22SAaron Ballman     if (I.isByRef()) {
71577361761STed Kremenek       vals[vd] = Initialized;
71677361761STed Kremenek       continue;
71777361761STed Kremenek     }
7183d31e8b2SRichard Smith     reportUse(be, vd);
719a0a5ca14STed Kremenek   }
720a0a5ca14STed Kremenek }
721a0a5ca14STed Kremenek 
VisitCallExpr(CallExpr * ce)722b721e301SRichard Smith void TransferFunctions::VisitCallExpr(CallExpr *ce) {
7237979ccf3STed Kremenek   if (Decl *Callee = ce->getCalleeDecl()) {
7247979ccf3STed Kremenek     if (Callee->hasAttr<ReturnsTwiceAttr>()) {
725b721e301SRichard Smith       // After a call to a function like setjmp or vfork, any variable which is
7267979ccf3STed Kremenek       // initialized anywhere within this function may now be initialized. For
7277979ccf3STed Kremenek       // now, just assume such a call initializes all variables.  FIXME: Only
7287979ccf3STed Kremenek       // mark variables as initialized if they have an initializer which is
7297979ccf3STed Kremenek       // reachable from here.
730b721e301SRichard Smith       vals.setAllScratchValues(Initialized);
731b721e301SRichard Smith     }
7327979ccf3STed Kremenek     else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) {
7337979ccf3STed Kremenek       // Functions labeled like "analyzer_noreturn" are often used to denote
7347979ccf3STed Kremenek       // "panic" functions that in special debug situations can still return,
7357979ccf3STed Kremenek       // but for the most part should not be treated as returning.  This is a
7367979ccf3STed Kremenek       // useful annotation borrowed from the static analyzer that is useful for
7377979ccf3STed Kremenek       // suppressing branch-specific false positives when we call one of these
7387979ccf3STed Kremenek       // functions but keep pretending the path continues (when in reality the
7397979ccf3STed Kremenek       // user doesn't care).
7407979ccf3STed Kremenek       vals.setAllScratchValues(Unknown);
7417979ccf3STed Kremenek     }
7427979ccf3STed Kremenek   }
7437979ccf3STed Kremenek }
744b721e301SRichard Smith 
VisitDeclRefExpr(DeclRefExpr * dr)7459e100ea1STed Kremenek void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) {
7466376d1fdSRichard Smith   switch (classification.get(dr)) {
7476376d1fdSRichard Smith   case ClassifyRefs::Ignore:
7486376d1fdSRichard Smith     break;
7496376d1fdSRichard Smith   case ClassifyRefs::Use:
7506376d1fdSRichard Smith     reportUse(dr, cast<VarDecl>(dr->getDecl()));
7516376d1fdSRichard Smith     break;
7526376d1fdSRichard Smith   case ClassifyRefs::Init:
7536376d1fdSRichard Smith     vals[cast<VarDecl>(dr->getDecl())] = Initialized;
7546376d1fdSRichard Smith     break;
7556376d1fdSRichard Smith   case ClassifyRefs::SelfInit:
756778a6ed3STed Kremenek     handler.handleSelfInit(cast<VarDecl>(dr->getDecl()));
7576376d1fdSRichard Smith     break;
758170b6869SZequan Wu   case ClassifyRefs::ConstRefUse:
759170b6869SZequan Wu     reportConstRefUse(dr, cast<VarDecl>(dr->getDecl()));
760170b6869SZequan Wu     break;
7619e100ea1STed Kremenek   }
76281383c20STed Kremenek }
7639e100ea1STed Kremenek 
VisitBinaryOperator(BinaryOperator * BO)7646376d1fdSRichard Smith void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) {
7656376d1fdSRichard Smith   if (BO->getOpcode() == BO_Assign) {
7666376d1fdSRichard Smith     FindVarResult Var = findVar(BO->getLHS());
7676376d1fdSRichard Smith     if (const VarDecl *VD = Var.getDecl())
7686376d1fdSRichard Smith       vals[VD] = Initialized;
7696376d1fdSRichard Smith   }
7706376d1fdSRichard Smith }
7716376d1fdSRichard Smith 
VisitDeclStmt(DeclStmt * DS)7726376d1fdSRichard Smith void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
773535bbcccSAaron Ballman   for (auto *DI : DS->decls()) {
7741c1057afSEugene Zelenko     auto *VD = dyn_cast<VarDecl>(DI);
7756376d1fdSRichard Smith     if (VD && isTrackedVar(VD)) {
7766376d1fdSRichard Smith       if (getSelfInitExpr(VD)) {
77778c7e344SChandler Carruth         // If the initializer consists solely of a reference to itself, we
77878c7e344SChandler Carruth         // explicitly mark the variable as uninitialized. This allows code
77978c7e344SChandler Carruth         // like the following:
78078c7e344SChandler Carruth         //
78178c7e344SChandler Carruth         //   int x = x;
78278c7e344SChandler Carruth         //
78378c7e344SChandler Carruth         // to deliberately leave a variable uninitialized. Different analysis
78478c7e344SChandler Carruth         // clients can detect this pattern and adjust their reporting
78578c7e344SChandler Carruth         // appropriately, but we need to continue to analyze subsequent uses
78678c7e344SChandler Carruth         // of the variable.
7876376d1fdSRichard Smith         vals[VD] = Uninitialized;
7886376d1fdSRichard Smith       } else if (VD->getInit()) {
7896376d1fdSRichard Smith         // Treat the new variable as initialized.
7906376d1fdSRichard Smith         vals[VD] = Initialized;
791a8d4f229SRichard Smith       } else {
792a8d4f229SRichard Smith         // No initializer: the variable is now uninitialized. This matters
793a8d4f229SRichard Smith         // for cases like:
794a8d4f229SRichard Smith         //   while (...) {
795a8d4f229SRichard Smith         //     int n;
796a8d4f229SRichard Smith         //     use(n);
797a8d4f229SRichard Smith         //     n = 0;
798a8d4f229SRichard Smith         //   }
799a8d4f229SRichard Smith         // FIXME: Mark the variable as uninitialized whenever its scope is
800a8d4f229SRichard Smith         // left, since its scope could be re-entered by a jump over the
801a8d4f229SRichard Smith         // declaration.
8026376d1fdSRichard Smith         vals[VD] = Uninitialized;
803a0a5ca14STed Kremenek       }
8049e100ea1STed Kremenek     }
8059e100ea1STed Kremenek   }
8069e100ea1STed Kremenek }
8070a7aa3b6SChandler Carruth 
VisitGCCAsmStmt(GCCAsmStmt * as)80850cac248SBill Wendling void TransferFunctions::VisitGCCAsmStmt(GCCAsmStmt *as) {
80950cac248SBill Wendling   // An "asm goto" statement is a terminator that may initialize some variables.
81050cac248SBill Wendling   if (!as->isAsmGoto())
81150cac248SBill Wendling     return;
81250cac248SBill Wendling 
813c4582a68SBill Wendling   ASTContext &C = ac.getASTContext();
814c4582a68SBill Wendling   for (const Expr *O : as->outputs()) {
815c4582a68SBill Wendling     const Expr *Ex = stripCasts(C, O);
816c4582a68SBill Wendling 
817c4582a68SBill Wendling     // Strip away any unary operators. Invalid l-values are reported by other
818c4582a68SBill Wendling     // semantic analysis passes.
819c4582a68SBill Wendling     while (const auto *UO = dyn_cast<UnaryOperator>(Ex))
820c4582a68SBill Wendling       Ex = stripCasts(C, UO->getSubExpr());
821c4582a68SBill Wendling 
8223a604fdbSNick Desaulniers     // Mark the variable as potentially uninitialized for those cases where
8233a604fdbSNick Desaulniers     // it's used on an indirect path, where it's not guaranteed to be
8243a604fdbSNick Desaulniers     // defined.
825c4582a68SBill Wendling     if (const VarDecl *VD = findVar(Ex).getDecl())
82672aa619aSBill Wendling       vals[VD] = MayUninitialized;
82750cac248SBill Wendling   }
828c4582a68SBill Wendling }
82950cac248SBill Wendling 
VisitObjCMessageExpr(ObjCMessageExpr * ME)830edf22edcSTed Kremenek void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) {
831edf22edcSTed Kremenek   // If the Objective-C message expression is an implicit no-return that
832edf22edcSTed Kremenek   // is not modeled in the CFG, set the tracked dataflow values to Unknown.
833edf22edcSTed Kremenek   if (objCNoRet.isImplicitNoReturn(ME)) {
834edf22edcSTed Kremenek     vals.setAllScratchValues(Unknown);
835edf22edcSTed Kremenek   }
836edf22edcSTed Kremenek }
837edf22edcSTed Kremenek 
838a0a5ca14STed Kremenek //------------------------------------------------------------------------====//
839a0a5ca14STed Kremenek // High-level "driver" logic for uninitialized values analysis.
840a0a5ca14STed Kremenek //====------------------------------------------------------------------------//
841a0a5ca14STed Kremenek 
runOnBlock(const CFGBlock * block,const CFG & cfg,AnalysisDeclContext & ac,CFGBlockValues & vals,const ClassifyRefs & classification,llvm::BitVector & wasAnalyzed,UninitVariablesHandler & handler)842a0a5ca14STed Kremenek static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
84381ce1c8aSTed Kremenek                        AnalysisDeclContext &ac, CFGBlockValues &vals,
8446376d1fdSRichard Smith                        const ClassifyRefs &classification,
845352a7081STed Kremenek                        llvm::BitVector &wasAnalyzed,
846778a6ed3STed Kremenek                        UninitVariablesHandler &handler) {
847352a7081STed Kremenek   wasAnalyzed[block->getBlockID()] = true;
848a0a5ca14STed Kremenek   vals.resetScratch();
8496080d321STed Kremenek   // Merge in values of predecessor blocks.
850a0a5ca14STed Kremenek   bool isFirst = true;
851a0a5ca14STed Kremenek   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
852a0a5ca14STed Kremenek        E = block->pred_end(); I != E; ++I) {
853aed4677aSTed Kremenek     const CFGBlock *pred = *I;
8544b6fee6cSTed Kremenek     if (!pred)
8554b6fee6cSTed Kremenek       continue;
856aed4677aSTed Kremenek     if (wasAnalyzed[pred->getBlockID()]) {
8576080d321STed Kremenek       vals.mergeIntoScratch(vals.getValueVector(pred), isFirst);
858a0a5ca14STed Kremenek       isFirst = false;
859a0a5ca14STed Kremenek     }
860aed4677aSTed Kremenek   }
861a0a5ca14STed Kremenek   // Apply the transfer function.
8626376d1fdSRichard Smith   TransferFunctions tf(vals, cfg, block, ac, classification, handler);
8631c1057afSEugene Zelenko   for (const auto &I : *block) {
8641c1057afSEugene Zelenko     if (Optional<CFGStmt> cs = I.getAs<CFGStmt>())
86500be69abSDavid Blaikie       tf.Visit(const_cast<Stmt *>(cs->getStmt()));
866a0a5ca14STed Kremenek   }
86750cac248SBill Wendling   CFGTerminator terminator = block->getTerminator();
86872aa619aSBill Wendling   if (auto *as = dyn_cast_or_null<GCCAsmStmt>(terminator.getStmt()))
86950cac248SBill Wendling     if (as->isAsmGoto())
87050cac248SBill Wendling       tf.Visit(as);
871a895fe99STed Kremenek   return vals.updateValueVectorWithScratch(block);
872a0a5ca14STed Kremenek }
873a0a5ca14STed Kremenek 
8741c1057afSEugene Zelenko namespace {
8751c1057afSEugene Zelenko 
876778a6ed3STed Kremenek /// PruneBlocksHandler is a special UninitVariablesHandler that is used
877778a6ed3STed Kremenek /// to detect when a CFGBlock has any *potential* use of an uninitialized
878778a6ed3STed Kremenek /// variable.  It is mainly used to prune out work during the final
879778a6ed3STed Kremenek /// reporting pass.
880778a6ed3STed Kremenek struct PruneBlocksHandler : public UninitVariablesHandler {
881778a6ed3STed Kremenek   /// Records if a CFGBlock had a potential use of an uninitialized variable.
882778a6ed3STed Kremenek   llvm::BitVector hadUse;
883778a6ed3STed Kremenek 
884778a6ed3STed Kremenek   /// Records if any CFGBlock had a potential use of an uninitialized variable.
8851c1057afSEugene Zelenko   bool hadAnyUse = false;
886778a6ed3STed Kremenek 
887778a6ed3STed Kremenek   /// The current block to scribble use information.
8881c1057afSEugene Zelenko   unsigned currentBlock = 0;
8891c1057afSEugene Zelenko 
PruneBlocksHandler__anon812707660811::PruneBlocksHandler8901c1057afSEugene Zelenko   PruneBlocksHandler(unsigned numBlocks) : hadUse(numBlocks, false) {}
8911c1057afSEugene Zelenko 
8921c1057afSEugene Zelenko   ~PruneBlocksHandler() override = default;
893778a6ed3STed Kremenek 
handleUseOfUninitVariable__anon812707660811::PruneBlocksHandler894b45acb8aSCraig Topper   void handleUseOfUninitVariable(const VarDecl *vd,
895b45acb8aSCraig Topper                                  const UninitUse &use) override {
896778a6ed3STed Kremenek     hadUse[currentBlock] = true;
897778a6ed3STed Kremenek     hadAnyUse = true;
898778a6ed3STed Kremenek   }
899778a6ed3STed Kremenek 
handleConstRefUseOfUninitVariable__anon812707660811::PruneBlocksHandler900170b6869SZequan Wu   void handleConstRefUseOfUninitVariable(const VarDecl *vd,
901170b6869SZequan Wu                                          const UninitUse &use) override {
902170b6869SZequan Wu     hadUse[currentBlock] = true;
903170b6869SZequan Wu     hadAnyUse = true;
904170b6869SZequan Wu   }
905170b6869SZequan Wu 
906778a6ed3STed Kremenek   /// Called when the uninitialized variable analysis detects the
907778a6ed3STed Kremenek   /// idiom 'int x = x'.  All other uses of 'x' within the initializer
908778a6ed3STed Kremenek   /// are handled by handleUseOfUninitVariable.
handleSelfInit__anon812707660811::PruneBlocksHandler909b45acb8aSCraig Topper   void handleSelfInit(const VarDecl *vd) override {
910778a6ed3STed Kremenek     hadUse[currentBlock] = true;
911778a6ed3STed Kremenek     hadAnyUse = true;
912778a6ed3STed Kremenek   }
913778a6ed3STed Kremenek };
9141c1057afSEugene Zelenko 
9151c1057afSEugene Zelenko } // namespace
916778a6ed3STed Kremenek 
runUninitializedVariablesAnalysis(const DeclContext & dc,const CFG & cfg,AnalysisDeclContext & ac,UninitVariablesHandler & handler,UninitVariablesAnalysisStats & stats)917b4836ea7SChandler Carruth void clang::runUninitializedVariablesAnalysis(
918b4836ea7SChandler Carruth     const DeclContext &dc,
919a0a5ca14STed Kremenek     const CFG &cfg,
92081ce1c8aSTed Kremenek     AnalysisDeclContext &ac,
921b4836ea7SChandler Carruth     UninitVariablesHandler &handler,
922b4836ea7SChandler Carruth     UninitVariablesAnalysisStats &stats) {
923a0a5ca14STed Kremenek   CFGBlockValues vals(cfg);
924a0a5ca14STed Kremenek   vals.computeSetOfDeclarations(dc);
925a0a5ca14STed Kremenek   if (vals.hasNoDeclarations())
926a0a5ca14STed Kremenek     return;
92737881934STed Kremenek 
928b4836ea7SChandler Carruth   stats.NumVariablesAnalyzed = vals.getNumEntries();
929b4836ea7SChandler Carruth 
9306376d1fdSRichard Smith   // Precompute which expressions are uses and which are initializations.
9316376d1fdSRichard Smith   ClassifyRefs classification(ac);
9326376d1fdSRichard Smith   cfg.VisitBlockStmts(classification);
9336376d1fdSRichard Smith 
93437881934STed Kremenek   // Mark all variables uninitialized at the entry.
93537881934STed Kremenek   const CFGBlock &entry = cfg.getEntry();
9366080d321STed Kremenek   ValueVector &vec = vals.getValueVector(&entry);
93737881934STed Kremenek   const unsigned n = vals.getNumEntries();
93837881934STed Kremenek   for (unsigned j = 0; j < n; ++j) {
93937881934STed Kremenek     vec[j] = Uninitialized;
94037881934STed Kremenek   }
94137881934STed Kremenek 
94237881934STed Kremenek   // Proceed with the workist.
94305c7dc66SGabor Horvath   ForwardDataflowWorklist worklist(cfg, ac);
9449b15c962STed Kremenek   llvm::BitVector previouslyVisited(cfg.getNumBlockIDs());
945a0a5ca14STed Kremenek   worklist.enqueueSuccessors(&cfg.getEntry());
946352a7081STed Kremenek   llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false);
947aed4677aSTed Kremenek   wasAnalyzed[cfg.getEntry().getBlockID()] = true;
948778a6ed3STed Kremenek   PruneBlocksHandler PBH(cfg.getNumBlockIDs());
949a0a5ca14STed Kremenek 
950a0a5ca14STed Kremenek   while (const CFGBlock *block = worklist.dequeue()) {
951778a6ed3STed Kremenek     PBH.currentBlock = block->getBlockID();
952778a6ed3STed Kremenek 
953a0a5ca14STed Kremenek     // Did the block change?
9546376d1fdSRichard Smith     bool changed = runOnBlock(block, cfg, ac, vals,
955778a6ed3STed Kremenek                               classification, wasAnalyzed, PBH);
956b4836ea7SChandler Carruth     ++stats.NumBlockVisits;
957a0a5ca14STed Kremenek     if (changed || !previouslyVisited[block->getBlockID()])
958a0a5ca14STed Kremenek       worklist.enqueueSuccessors(block);
959a0a5ca14STed Kremenek     previouslyVisited[block->getBlockID()] = true;
960a0a5ca14STed Kremenek   }
961a0a5ca14STed Kremenek 
962778a6ed3STed Kremenek   if (!PBH.hadAnyUse)
963778a6ed3STed Kremenek     return;
964778a6ed3STed Kremenek 
965392291f7SEnea Zaffanella   // Run through the blocks one more time, and report uninitialized variables.
9661c1057afSEugene Zelenko   for (const auto *block : cfg)
967778a6ed3STed Kremenek     if (PBH.hadUse[block->getBlockID()]) {
968778a6ed3STed Kremenek       runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler);
969b4836ea7SChandler Carruth       ++stats.NumBlockVisits;
970b4836ea7SChandler Carruth     }
971a0a5ca14STed Kremenek }
972a0a5ca14STed Kremenek 
9731c1057afSEugene Zelenko UninitVariablesHandler::~UninitVariablesHandler() = default;
974