UninitializedValues.cpp revision 218893
1//==- UninitializedValues.cpp - Find Uninitialized Values -------*- C++ --*-==//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Uninitialized Values analysis for source-level CFGs.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/Analyses/UninitializedValues.h"
15#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
16#include "clang/Analysis/AnalysisDiagnostic.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/Analysis/FlowSensitive/DataflowSolver.h"
19
20#include "llvm/ADT/SmallPtrSet.h"
21
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Dataflow initialization logic.
26//===----------------------------------------------------------------------===//
27
28namespace {
29
30class RegisterDecls
31  : public CFGRecStmtDeclVisitor<RegisterDecls> {
32
33  UninitializedValues::AnalysisDataTy& AD;
34public:
35  RegisterDecls(UninitializedValues::AnalysisDataTy& ad) :  AD(ad) {}
36
37  void VisitVarDecl(VarDecl* VD) { AD.Register(VD); }
38  CFG& getCFG() { return AD.getCFG(); }
39};
40
41} // end anonymous namespace
42
43void UninitializedValues::InitializeValues(const CFG& cfg) {
44  RegisterDecls R(getAnalysisData());
45  cfg.VisitBlockStmts(R);
46}
47
48//===----------------------------------------------------------------------===//
49// Transfer functions.
50//===----------------------------------------------------------------------===//
51
52namespace {
53class TransferFuncs
54  : public CFGStmtVisitor<TransferFuncs,bool> {
55
56  UninitializedValues::ValTy V;
57  UninitializedValues::AnalysisDataTy& AD;
58public:
59  TransferFuncs(UninitializedValues::AnalysisDataTy& ad) : AD(ad) {}
60
61  UninitializedValues::ValTy& getVal() { return V; }
62  CFG& getCFG() { return AD.getCFG(); }
63
64  void SetTopValue(UninitializedValues::ValTy& X) {
65    X.setDeclValues(AD);
66    X.resetBlkExprValues(AD);
67  }
68
69  bool VisitDeclRefExpr(DeclRefExpr* DR);
70  bool VisitBinaryOperator(BinaryOperator* B);
71  bool VisitUnaryOperator(UnaryOperator* U);
72  bool VisitStmt(Stmt* S);
73  bool VisitCallExpr(CallExpr* C);
74  bool VisitDeclStmt(DeclStmt* D);
75  bool VisitAbstractConditionalOperator(AbstractConditionalOperator* C);
76  bool BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S);
77
78  bool Visit(Stmt *S);
79  bool BlockStmt_VisitExpr(Expr* E);
80
81  void VisitTerminator(CFGBlock* B) { }
82
83  void setCurrentBlock(const CFGBlock *block) {}
84};
85
86static const bool Initialized = false;
87static const bool Uninitialized = true;
88
89bool TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {
90
91  if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl()))
92    if (VD->isLocalVarDecl()) {
93
94      if (AD.Observer)
95        AD.Observer->ObserveDeclRefExpr(V, AD, DR, VD);
96
97      // Pseudo-hack to prevent cascade of warnings.  If an accessed variable
98      // is uninitialized, then we are already going to flag a warning for
99      // this variable, which a "source" of uninitialized values.
100      // We can otherwise do a full "taint" of uninitialized values.  The
101      // client has both options by toggling AD.FullUninitTaint.
102
103      if (AD.FullUninitTaint)
104        return V(VD,AD);
105    }
106
107  return Initialized;
108}
109
110static VarDecl* FindBlockVarDecl(Expr* E) {
111
112  // Blast through casts and parentheses to find any DeclRefExprs that
113  // refer to a block VarDecl.
114
115  if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
116    if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl()))
117      if (VD->isLocalVarDecl()) return VD;
118
119  return NULL;
120}
121
122bool TransferFuncs::VisitBinaryOperator(BinaryOperator* B) {
123
124  if (VarDecl* VD = FindBlockVarDecl(B->getLHS()))
125    if (B->isAssignmentOp()) {
126      if (B->getOpcode() == BO_Assign)
127        return V(VD,AD) = Visit(B->getRHS());
128      else // Handle +=, -=, *=, etc.  We do want '&', not '&&'.
129        return V(VD,AD) = Visit(B->getLHS()) & Visit(B->getRHS());
130    }
131
132  return VisitStmt(B);
133}
134
135bool TransferFuncs::VisitDeclStmt(DeclStmt* S) {
136  for (DeclStmt::decl_iterator I=S->decl_begin(), E=S->decl_end(); I!=E; ++I) {
137    VarDecl *VD = dyn_cast<VarDecl>(*I);
138    if (VD && VD->isLocalVarDecl()) {
139      if (Stmt* I = VD->getInit()) {
140        // Visit the subexpression to check for uses of uninitialized values,
141        // even if we don't propagate that value.
142        bool isSubExprUninit = Visit(I);
143        V(VD,AD) = AD.FullUninitTaint ? isSubExprUninit : Initialized;
144      }
145      else {
146        // Special case for declarations of array types.  For things like:
147        //
148        //  char x[10];
149        //
150        // we should treat "x" as being initialized, because the variable
151        // "x" really refers to the memory block.  Clearly x[1] is
152        // uninitialized, but expressions like "(char *) x" really do refer to
153        // an initialized value.  This simple dataflow analysis does not reason
154        // about the contents of arrays, although it could be potentially
155        // extended to do so if the array were of constant size.
156        if (VD->getType()->isArrayType())
157          V(VD,AD) = Initialized;
158        else
159          V(VD,AD) = Uninitialized;
160      }
161    }
162  }
163  return Uninitialized; // Value is never consumed.
164}
165
166bool TransferFuncs::VisitCallExpr(CallExpr* C) {
167  VisitChildren(C);
168  return Initialized;
169}
170
171bool TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {
172  switch (U->getOpcode()) {
173    case UO_AddrOf: {
174      VarDecl* VD = FindBlockVarDecl(U->getSubExpr());
175      if (VD && VD->isLocalVarDecl())
176        return V(VD,AD) = Initialized;
177      break;
178    }
179
180    default:
181      break;
182  }
183
184  return Visit(U->getSubExpr());
185}
186
187bool
188TransferFuncs::BlockStmt_VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
189  // This represents a use of the 'collection'
190  bool x = Visit(S->getCollection());
191
192  if (x == Uninitialized)
193    return Uninitialized;
194
195  // This represents an initialization of the 'element' value.
196  Stmt* Element = S->getElement();
197  VarDecl* VD = 0;
198
199  if (DeclStmt* DS = dyn_cast<DeclStmt>(Element))
200    VD = cast<VarDecl>(DS->getSingleDecl());
201  else {
202    Expr* ElemExpr = cast<Expr>(Element)->IgnoreParens();
203
204    // Initialize the value of the reference variable.
205    if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(ElemExpr))
206      VD = cast<VarDecl>(DR->getDecl());
207    else
208      return Visit(ElemExpr);
209  }
210
211  V(VD,AD) = Initialized;
212  return Initialized;
213}
214
215
216bool TransferFuncs::
217VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
218  Visit(C->getCond());
219
220  bool rhsResult = Visit(C->getFalseExpr());
221  // Handle the GNU extension for missing LHS.
222  if (isa<ConditionalOperator>(C))
223    return Visit(C->getTrueExpr()) & rhsResult; // Yes: we want &, not &&.
224  else
225    return rhsResult;
226}
227
228bool TransferFuncs::VisitStmt(Stmt* S) {
229  bool x = Initialized;
230
231  // We don't stop at the first subexpression that is Uninitialized because
232  // evaluating some subexpressions may result in propogating "Uninitialized"
233  // or "Initialized" to variables referenced in the other subexpressions.
234  for (Stmt::child_range I = S->children(); I; ++I)
235    if (*I && Visit(*I) == Uninitialized) x = Uninitialized;
236
237  return x;
238}
239
240bool TransferFuncs::Visit(Stmt *S) {
241  if (AD.isTracked(static_cast<Expr*>(S))) return V(static_cast<Expr*>(S),AD);
242  else return static_cast<CFGStmtVisitor<TransferFuncs,bool>*>(this)->Visit(S);
243}
244
245bool TransferFuncs::BlockStmt_VisitExpr(Expr* E) {
246  bool x = static_cast<CFGStmtVisitor<TransferFuncs,bool>*>(this)->Visit(E);
247  if (AD.isTracked(E)) V(E,AD) = x;
248  return x;
249}
250
251} // end anonymous namespace
252
253//===----------------------------------------------------------------------===//
254// Merge operator.
255//
256//  In our transfer functions we take the approach that any
257//  combination of uninitialized values, e.g.
258//      Uninitialized + ___ = Uninitialized.
259//
260//  Merges take the same approach, preferring soundness.  At a confluence point,
261//  if any predecessor has a variable marked uninitialized, the value is
262//  uninitialized at the confluence point.
263//===----------------------------------------------------------------------===//
264
265namespace {
266  typedef StmtDeclBitVector_Types::Union Merge;
267  typedef DataflowSolver<UninitializedValues,TransferFuncs,Merge> Solver;
268}
269
270//===----------------------------------------------------------------------===//
271// Uninitialized values checker.   Scan an AST and flag variable uses
272//===----------------------------------------------------------------------===//
273
274UninitializedValues_ValueTypes::ObserverTy::~ObserverTy() {}
275
276namespace {
277class UninitializedValuesChecker
278  : public UninitializedValues::ObserverTy {
279
280  ASTContext &Ctx;
281  Diagnostic &Diags;
282  llvm::SmallPtrSet<VarDecl*,10> AlreadyWarned;
283
284public:
285  UninitializedValuesChecker(ASTContext &ctx, Diagnostic &diags)
286    : Ctx(ctx), Diags(diags) {}
287
288  virtual void ObserveDeclRefExpr(UninitializedValues::ValTy& V,
289                                  UninitializedValues::AnalysisDataTy& AD,
290                                  DeclRefExpr* DR, VarDecl* VD) {
291
292    assert ( AD.isTracked(VD) && "Unknown VarDecl.");
293
294    if (V(VD,AD) == Uninitialized)
295      if (AlreadyWarned.insert(VD))
296        Diags.Report(Ctx.getFullLoc(DR->getSourceRange().getBegin()),
297                     diag::warn_uninit_val);
298  }
299};
300} // end anonymous namespace
301
302namespace clang {
303void CheckUninitializedValues(CFG& cfg, ASTContext &Ctx, Diagnostic &Diags,
304                              bool FullUninitTaint) {
305
306  // Compute the uninitialized values information.
307  UninitializedValues U(cfg);
308  U.getAnalysisData().FullUninitTaint = FullUninitTaint;
309  Solver S(U);
310  S.runOnCFG(cfg);
311
312  // Scan for DeclRefExprs that use uninitialized values.
313  UninitializedValuesChecker Observer(Ctx,Diags);
314  U.getAnalysisData().Observer = &Observer;
315  S.runOnAllBlocks(cfg);
316}
317} // end namespace clang
318