clang  16.0.0git
SVals.cpp
Go to the documentation of this file.
1 //===-- SVals.cpp - Abstract RValues for Path-Sens. Value Tracking --------===//
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 defines SVal, Loc, and NonLoc, classes that represent
10 // abstract r-values for use with path-sensitive value tracking.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/Type.h"
21 #include "clang/Basic/LLVM.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cassert>
34 
35 using namespace clang;
36 using namespace ento;
37 
38 //===----------------------------------------------------------------------===//
39 // Symbol iteration within an SVal.
40 //===----------------------------------------------------------------------===//
41 
42 //===----------------------------------------------------------------------===//
43 // Utility methods.
44 //===----------------------------------------------------------------------===//
45 
47  if (Optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>()) {
48  const MemRegion* R = X->getRegion();
49  if (const FunctionCodeRegion *CTR = R->getAs<FunctionCodeRegion>())
50  if (const auto *FD = dyn_cast<FunctionDecl>(CTR->getDecl()))
51  return FD;
52  }
53 
54  if (auto X = getAs<nonloc::PointerToMember>()) {
55  if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(X->getDecl()))
56  return MD;
57  }
58  return nullptr;
59 }
60 
61 /// If this SVal is a location (subclasses Loc) and wraps a symbol,
62 /// return that SymbolRef. Otherwise return 0.
63 ///
64 /// Implicit casts (ex: void* -> char*) can turn Symbolic region into Element
65 /// region. If that is the case, gets the underlining region.
66 /// When IncludeBaseRegions is set to true and the SubRegion is non-symbolic,
67 /// the first symbolic parent region is returned.
68 SymbolRef SVal::getAsLocSymbol(bool IncludeBaseRegions) const {
69  // FIXME: should we consider SymbolRef wrapped in CodeTextRegion?
70  if (const MemRegion *R = getAsRegion())
71  if (const SymbolicRegion *SymR =
72  IncludeBaseRegions ? R->getSymbolicBase()
73  : dyn_cast<SymbolicRegion>(R->StripCasts()))
74  return SymR->getSymbol();
75 
76  return nullptr;
77 }
78 
79 /// Get the symbol in the SVal or its base region.
81  Optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>();
82 
83  if (!X)
84  return nullptr;
85 
86  const MemRegion *R = X->getRegion();
87 
88  while (const auto *SR = dyn_cast<SubRegion>(R)) {
89  if (const auto *SymR = dyn_cast<SymbolicRegion>(SR))
90  return SymR->getSymbol();
91  else
92  R = SR->getSuperRegion();
93  }
94 
95  return nullptr;
96 }
97 
98 /// If this SVal wraps a symbol return that SymbolRef.
99 /// Otherwise, return 0.
100 ///
101 /// Casts are ignored during lookup.
102 /// \param IncludeBaseRegions The boolean that controls whether the search
103 /// should continue to the base regions if the region is not symbolic.
104 SymbolRef SVal::getAsSymbol(bool IncludeBaseRegions) const {
105  // FIXME: should we consider SymbolRef wrapped in CodeTextRegion?
106  if (Optional<nonloc::SymbolVal> X = getAs<nonloc::SymbolVal>())
107  return X->getSymbol();
108 
109  return getAsLocSymbol(IncludeBaseRegions);
110 }
111 
113  if (auto CI = getAs<nonloc::ConcreteInt>())
114  return &CI->getValue();
115  if (auto CI = getAs<loc::ConcreteInt>())
116  return &CI->getValue();
117  return nullptr;
118 }
119 
120 const MemRegion *SVal::getAsRegion() const {
121  if (Optional<loc::MemRegionVal> X = getAs<loc::MemRegionVal>())
122  return X->getRegion();
123 
124  if (Optional<nonloc::LocAsInteger> X = getAs<nonloc::LocAsInteger>())
125  return X->getLoc().getAsRegion();
126 
127  return nullptr;
128 }
129 
130 namespace {
131 class TypeRetrievingVisitor
132  : public FullSValVisitor<TypeRetrievingVisitor, QualType> {
133 private:
134  const ASTContext &Context;
135 
136 public:
137  TypeRetrievingVisitor(const ASTContext &Context) : Context(Context) {}
138 
139  QualType VisitLocMemRegionVal(loc::MemRegionVal MRV) {
140  return Visit(MRV.getRegion());
141  }
142  QualType VisitLocGotoLabel(loc::GotoLabel GL) {
143  return QualType{Context.VoidPtrTy};
144  }
145  template <class ConcreteInt> QualType VisitConcreteInt(ConcreteInt CI) {
146  const llvm::APSInt &Value = CI.getValue();
147  if (1 == Value.getBitWidth())
148  return Context.BoolTy;
149  return Context.getIntTypeForBitwidth(Value.getBitWidth(), Value.isSigned());
150  }
151  QualType VisitLocConcreteInt(loc::ConcreteInt CI) {
152  return VisitConcreteInt(CI);
153  }
154  QualType VisitNonLocConcreteInt(nonloc::ConcreteInt CI) {
155  return VisitConcreteInt(CI);
156  }
157  QualType VisitNonLocLocAsInteger(nonloc::LocAsInteger LI) {
158  QualType NestedType = Visit(LI.getLoc());
159  if (NestedType.isNull())
160  return NestedType;
161 
162  return Context.getIntTypeForBitwidth(LI.getNumBits(),
163  NestedType->isSignedIntegerType());
164  }
165  QualType VisitNonLocCompoundVal(nonloc::CompoundVal CV) {
166  return CV.getValue()->getType();
167  }
168  QualType VisitNonLocLazyCompoundVal(nonloc::LazyCompoundVal LCV) {
169  return LCV.getRegion()->getValueType();
170  }
171  QualType VisitNonLocSymbolVal(nonloc::SymbolVal SV) {
172  return Visit(SV.getSymbol());
173  }
174  QualType VisitSymbolicRegion(const SymbolicRegion *SR) {
175  return Visit(SR->getSymbol());
176  }
177  QualType VisitTypedRegion(const TypedRegion *TR) {
178  return TR->getLocationType();
179  }
180  QualType VisitSymExpr(const SymExpr *SE) { return SE->getType(); }
181 };
182 } // end anonymous namespace
183 
184 QualType SVal::getType(const ASTContext &Context) const {
185  TypeRetrievingVisitor TRV{Context};
186  return TRV.Visit(*this);
187 }
188 
189 const MemRegion *loc::MemRegionVal::stripCasts(bool StripBaseCasts) const {
190  return getRegion()->StripCasts(StripBaseCasts);
191 }
192 
194  return static_cast<const LazyCompoundValData*>(Data)->getStore();
195 }
196 
198  return static_cast<const LazyCompoundValData*>(Data)->getRegion();
199 }
200 
202  return getPTMData().isNull();
203 }
204 
206  const auto PTMD = this->getPTMData();
207  if (PTMD.isNull())
208  return nullptr;
209 
210  const NamedDecl *ND = nullptr;
211  if (PTMD.is<const NamedDecl *>())
212  ND = PTMD.get<const NamedDecl *>();
213  else
214  ND = PTMD.get<const PointerToMemberData *>()->getDeclaratorDecl();
215 
216  return ND;
217 }
218 
219 //===----------------------------------------------------------------------===//
220 // Other Iterators.
221 //===----------------------------------------------------------------------===//
222 
224  return getValue()->begin();
225 }
226 
228  return getValue()->end();
229 }
230 
232  const PTMDataType PTMD = getPTMData();
233  if (PTMD.is<const NamedDecl *>())
234  return {};
235  return PTMD.get<const PointerToMemberData *>()->begin();
236 }
237 
239  const PTMDataType PTMD = getPTMData();
240  if (PTMD.is<const NamedDecl *>())
241  return {};
242  return PTMD.get<const PointerToMemberData *>()->end();
243 }
244 
245 //===----------------------------------------------------------------------===//
246 // Useful predicates.
247 //===----------------------------------------------------------------------===//
248 
249 bool SVal::isConstant() const {
250  return getAs<nonloc::ConcreteInt>() || getAs<loc::ConcreteInt>();
251 }
252 
253 bool SVal::isConstant(int I) const {
254  if (Optional<loc::ConcreteInt> LV = getAs<loc::ConcreteInt>())
255  return LV->getValue() == I;
256  if (Optional<nonloc::ConcreteInt> NV = getAs<nonloc::ConcreteInt>())
257  return NV->getValue() == I;
258  return false;
259 }
260 
261 bool SVal::isZeroConstant() const {
262  return isConstant(0);
263 }
264 
265 //===----------------------------------------------------------------------===//
266 // Pretty-Printing.
267 //===----------------------------------------------------------------------===//
268 
269 LLVM_DUMP_METHOD void SVal::dump() const { dumpToStream(llvm::errs()); }
270 
271 void SVal::printJson(raw_ostream &Out, bool AddQuotes) const {
272  std::string Buf;
273  llvm::raw_string_ostream TempOut(Buf);
274 
275  dumpToStream(TempOut);
276 
277  Out << JsonFormat(TempOut.str(), AddQuotes);
278 }
279 
280 void SVal::dumpToStream(raw_ostream &os) const {
281  switch (getBaseKind()) {
282  case UnknownValKind:
283  os << "Unknown";
284  break;
285  case NonLocKind:
286  castAs<NonLoc>().dumpToStream(os);
287  break;
288  case LocKind:
289  castAs<Loc>().dumpToStream(os);
290  break;
291  case UndefinedValKind:
292  os << "Undefined";
293  break;
294  }
295 }
296 
297 void NonLoc::dumpToStream(raw_ostream &os) const {
298  switch (getSubKind()) {
299  case nonloc::ConcreteIntKind: {
300  const auto &Value = castAs<nonloc::ConcreteInt>().getValue();
301  os << Value << ' ' << (Value.isSigned() ? 'S' : 'U')
302  << Value.getBitWidth() << 'b';
303  break;
304  }
305  case nonloc::SymbolValKind:
306  os << castAs<nonloc::SymbolVal>().getSymbol();
307  break;
308 
309  case nonloc::LocAsIntegerKind: {
310  const nonloc::LocAsInteger& C = castAs<nonloc::LocAsInteger>();
311  os << C.getLoc() << " [as " << C.getNumBits() << " bit integer]";
312  break;
313  }
314  case nonloc::CompoundValKind: {
315  const nonloc::CompoundVal& C = castAs<nonloc::CompoundVal>();
316  os << "compoundVal{";
317  bool first = true;
318  for (const auto &I : C) {
319  if (first) {
320  os << ' '; first = false;
321  }
322  else
323  os << ", ";
324 
325  I.dumpToStream(os);
326  }
327  os << "}";
328  break;
329  }
330  case nonloc::LazyCompoundValKind: {
331  const nonloc::LazyCompoundVal &C = castAs<nonloc::LazyCompoundVal>();
332  os << "lazyCompoundVal{" << const_cast<void *>(C.getStore())
333  << ',' << C.getRegion()
334  << '}';
335  break;
336  }
337  case nonloc::PointerToMemberKind: {
338  os << "pointerToMember{";
339  const nonloc::PointerToMember &CastRes =
340  castAs<nonloc::PointerToMember>();
341  if (CastRes.getDecl())
342  os << "|" << CastRes.getDecl()->getQualifiedNameAsString() << "|";
343  bool first = true;
344  for (const auto &I : CastRes) {
345  if (first) {
346  os << ' '; first = false;
347  }
348  else
349  os << ", ";
350 
351  os << I->getType();
352  }
353 
354  os << '}';
355  break;
356  }
357  default:
358  assert(false && "Pretty-printed not implemented for this NonLoc.");
359  break;
360  }
361 }
362 
363 void Loc::dumpToStream(raw_ostream &os) const {
364  switch (getSubKind()) {
365  case loc::ConcreteIntKind:
366  os << castAs<loc::ConcreteInt>().getValue().getZExtValue() << " (Loc)";
367  break;
368  case loc::GotoLabelKind:
369  os << "&&" << castAs<loc::GotoLabel>().getLabel()->getName();
370  break;
371  case loc::MemRegionValKind:
372  os << '&' << castAs<loc::MemRegionVal>().getRegion()->getString();
373  break;
374  default:
375  llvm_unreachable("Pretty-printing not implemented for this Loc.");
376  }
377 }
clang::ento::SVal::dumpToStream
void dumpToStream(raw_ostream &OS) const
Definition: SVals.cpp:280
clang::ento::LazyCompoundValData
Definition: BasicValueFactory.h:62
SVals.h
clang::ento::nonloc::CompoundVal
Definition: SVals.h:377
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::ento::SVal::getAsFunctionDecl
const FunctionDecl * getAsFunctionDecl() const
getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a CodeTextRegion wrapping a FunctionDecl...
Definition: SVals.cpp:46
clang::ento::SVal::isConstant
bool isConstant() const
Definition: SVals.cpp:249
clang::ento::loc::MemRegionVal::stripCasts
const MemRegion * stripCasts(bool StripBaseCasts=true) const
Get the underlining region and strip casts.
Definition: SVals.cpp:189
clang::ento::SVal::getLocSymbolInBase
SymbolRef getLocSymbolInBase() const
Get the symbol in the SVal or its base region.
Definition: SVals.cpp:80
clang::ento::SVal::getAsRegion
const MemRegion * getAsRegion() const
Definition: SVals.cpp:120
clang::ento::MemRegion::StripCasts
const LLVM_ATTRIBUTE_RETURNS_NONNULL MemRegion * StripCasts(bool StripBaseAndDerivedCasts=true) const
Definition: MemRegion.cpp:1330
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:247
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:737
clang::ento::SVal::isZeroConstant
bool isZeroConstant() const
Definition: SVals.cpp:261
DeclCXX.h
SymbolManager.h
llvm::Optional
Definition: LLVM.h:40
clang::ento::nonloc::PointerToMember::begin
iterator begin() const
Definition: SVals.cpp:231
clang::ento::SVal::printJson
void printJson(raw_ostream &Out, bool AddQuotes) const
printJson - Pretty-prints in JSON format.
Definition: SVals.cpp:271
clang::tooling::X
static ToolExecutorPluginRegistry::Add< AllTUsToolExecutorPlugin > X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. " "Tool results are stored in memory.")
clang::ento::SVal::dump
void dump() const
Definition: SVals.cpp:269
clang::ento::Loc::dumpToStream
void dumpToStream(raw_ostream &Out) const
Definition: SVals.cpp:363
getValue
static SVal getValue(SVal val, SValBuilder &svalBuilder)
Definition: ArrayBoundCheckerV2.cpp:276
clang::ento::nonloc::PointerToMember::isNullMemberPointer
bool isNullMemberPointer() const
Definition: SVals.cpp:201
Decl.h
clang::ento::MemRegion
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:95
APSInt
llvm::APSInt APSInt
Definition: ByteCodeEmitter.cpp:19
clang::ento::SVal::getAsLocSymbol
SymbolRef getAsLocSymbol(bool IncludeBaseRegions=false) const
If this SVal is a location and wraps a symbol, return that SymbolRef.
Definition: SVals.cpp:68
JsonSupport.h
SymExpr.h
clang::ento::MemRegion::getSymbolicBase
const SymbolicRegion * getSymbolicBase() const
If this is a symbolic region, returns the region.
Definition: MemRegion.cpp:1353
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:209
clang::ento::SymExpr
Symbolic value.
Definition: SymExpr.h:29
clang::ento::nonloc::LazyCompoundVal::getStore
const void * getStore() const
It might return null.
Definition: SVals.cpp:193
clang::ento::nonloc::PointerToMember
Value representing pointer-to-member.
Definition: SVals.h:442
clang::ento::nonloc::PointerToMember::getDecl
const NamedDecl * getDecl() const
Definition: SVals.cpp:205
Type.h
Expr.h
ASTContext.h
clang::ASTContext::getIntTypeForBitwidth
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
Definition: ASTContext.cpp:11893
clang::ento::nonloc::PointerToMember::iterator
llvm::ImmutableList< const CXXBaseSpecifier * >::iterator iterator
Definition: SVals.h:462
clang::ento::NonLoc::dumpToStream
void dumpToStream(raw_ostream &Out) const
Definition: SVals.cpp:297
BasicValueFactory.h
clang::ento::nonloc::LazyCompoundVal
Definition: SVals.h:402
clang::ento::FullSValVisitor
FullSValVisitor - a convenient mixed visitor for all three: SVal, SymExpr and MemRegion subclasses.
Definition: SValVisitor.h:137
clang::ento::SymbolicRegion
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:770
clang::ento::MemRegion::getAs
const RegionTy * getAs() const
Definition: MemRegion.h:1337
clang::ento::nonloc::PointerToMember::PTMDataType
llvm::PointerUnion< const NamedDecl *, const PointerToMemberData * > PTMDataType
Definition: SVals.h:447
clang::ASTContext::VoidPtrTy
CanQualType VoidPtrTy
Definition: ASTContext.h:1133
clang::ento::nonloc::CompoundVal::iterator
llvm::ImmutableList< SVal >::iterator iterator
Definition: SVals.h:390
SValBuilder.h
clang::ento::SVal::getAsInteger
const llvm::APSInt * getAsInteger() const
If this SVal is loc::ConcreteInt or nonloc::ConcreteInt, return a pointer to APSInt which is held in ...
Definition: SVals.cpp:112
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:802
Value
Value
Definition: UninitializedValues.cpp:102
clang::ento::nonloc::CompoundVal::end
iterator end() const
Definition: SVals.cpp:227
clang::ento::FunctionCodeRegion
FunctionCodeRegion - A region that represents code texts of function.
Definition: MemRegion.h:580
LLVM.h
clang::Type::isSignedIntegerType
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2018
clang::ento::nonloc::LazyCompoundVal::getRegion
const LLVM_ATTRIBUTE_RETURNS_NONNULL TypedValueRegion * getRegion() const
Definition: SVals.cpp:197
clang::NamedDecl::getQualifiedNameAsString
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1608
clang::ento::nonloc::PointerToMember::end
iterator end() const
Definition: SVals.cpp:238
clang::ento::nonloc::LocAsInteger
Definition: SVals.h:345
clang
Definition: CalledOnceCheck.h:17
clang::ento::nonloc::CompoundVal::begin
iterator begin() const
Definition: SVals.cpp:223
MemRegion.h
clang::JsonFormat
std::string JsonFormat(StringRef RawSR, bool AddQuotes)
Definition: JsonSupport.h:28
clang::ento::PointerToMemberData
Definition: BasicValueFactory.h:86
clang::ento::TypedValueRegion
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:531
clang::ento::SVal::getAsSymbol
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition: SVals.cpp:104
SValVisitor.h
clang::ASTContext::BoolTy
CanQualType BoolTy
Definition: ASTContext.h:1107
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1877
clang::ento::SVal::getType
QualType getType(const ASTContext &) const
Try to get a reasonable type for the given value.
Definition: SVals.cpp:184
clang::ento::loc::MemRegionVal::getRegion
const MemRegion * getRegion() const
Get the underlining region.
Definition: SVals.h:513