1 //== SymbolManager.h - Management of Symbolic Values ------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines SymbolManager, a class that manages symbolic values
11 // created for use by ExprEngine and related classes.
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
16 #include "clang/Analysis/Analyses/LiveVariables.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
19 #include "llvm/Support/raw_ostream.h"
21 using namespace clang;
24 void SymExpr::anchor() { }
26 LLVM_DUMP_METHOD void SymExpr::dump() const {
27 dumpToStream(llvm::errs());
30 void SymIntExpr::dumpToStream(raw_ostream &os) const {
32 getLHS()->dumpToStream(os);
34 << BinaryOperator::getOpcodeStr(getOpcode()) << ' ';
35 if (getRHS().isUnsigned())
36 os << getRHS().getZExtValue();
38 os << getRHS().getSExtValue();
39 if (getRHS().isUnsigned())
43 void IntSymExpr::dumpToStream(raw_ostream &os) const {
44 if (getLHS().isUnsigned())
45 os << getLHS().getZExtValue();
47 os << getLHS().getSExtValue();
48 if (getLHS().isUnsigned())
51 << BinaryOperator::getOpcodeStr(getOpcode())
53 getRHS()->dumpToStream(os);
57 void SymSymExpr::dumpToStream(raw_ostream &os) const {
59 getLHS()->dumpToStream(os);
61 << BinaryOperator::getOpcodeStr(getOpcode())
63 getRHS()->dumpToStream(os);
67 void SymbolCast::dumpToStream(raw_ostream &os) const {
68 os << '(' << ToTy.getAsString() << ") (";
69 Operand->dumpToStream(os);
73 void SymbolConjured::dumpToStream(raw_ostream &os) const {
74 os << "conj_$" << getSymbolID() << '{' << T.getAsString() << '}';
77 void SymbolDerived::dumpToStream(raw_ostream &os) const {
78 os << "derived_$" << getSymbolID() << '{'
79 << getParentSymbol() << ',' << getRegion() << '}';
82 void SymbolExtent::dumpToStream(raw_ostream &os) const {
83 os << "extent_$" << getSymbolID() << '{' << getRegion() << '}';
86 void SymbolMetadata::dumpToStream(raw_ostream &os) const {
87 os << "meta_$" << getSymbolID() << '{'
88 << getRegion() << ',' << T.getAsString() << '}';
91 void SymbolData::anchor() { }
93 void SymbolRegionValue::dumpToStream(raw_ostream &os) const {
94 os << "reg_$" << getSymbolID()
95 << '<' << getType().getAsString() << ' ' << R << '>';
98 bool SymExpr::symbol_iterator::operator==(const symbol_iterator &X) const {
102 bool SymExpr::symbol_iterator::operator!=(const symbol_iterator &X) const {
106 SymExpr::symbol_iterator::symbol_iterator(const SymExpr *SE) {
110 SymExpr::symbol_iterator &SymExpr::symbol_iterator::operator++() {
111 assert(!itr.empty() && "attempting to iterate on an 'end' iterator");
116 SymbolRef SymExpr::symbol_iterator::operator*() {
117 assert(!itr.empty() && "attempting to dereference an 'end' iterator");
121 void SymExpr::symbol_iterator::expand() {
122 const SymExpr *SE = itr.pop_back_val();
124 switch (SE->getKind()) {
125 case SymExpr::SymbolRegionValueKind:
126 case SymExpr::SymbolConjuredKind:
127 case SymExpr::SymbolDerivedKind:
128 case SymExpr::SymbolExtentKind:
129 case SymExpr::SymbolMetadataKind:
131 case SymExpr::SymbolCastKind:
132 itr.push_back(cast<SymbolCast>(SE)->getOperand());
134 case SymExpr::SymIntExprKind:
135 itr.push_back(cast<SymIntExpr>(SE)->getLHS());
137 case SymExpr::IntSymExprKind:
138 itr.push_back(cast<IntSymExpr>(SE)->getRHS());
140 case SymExpr::SymSymExprKind: {
141 const SymSymExpr *x = cast<SymSymExpr>(SE);
142 itr.push_back(x->getLHS());
143 itr.push_back(x->getRHS());
147 llvm_unreachable("unhandled expansion case");
150 unsigned SymExpr::computeComplexity() const {
152 for (symbol_iterator I = symbol_begin(), E = symbol_end(); I != E; ++I)
157 const SymbolRegionValue*
158 SymbolManager::getRegionValueSymbol(const TypedValueRegion* R) {
159 llvm::FoldingSetNodeID profile;
160 SymbolRegionValue::Profile(profile, R);
162 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
164 SD = (SymExpr*) BPAlloc.Allocate<SymbolRegionValue>();
165 new (SD) SymbolRegionValue(SymbolCounter, R);
166 DataSet.InsertNode(SD, InsertPos);
170 return cast<SymbolRegionValue>(SD);
173 const SymbolConjured* SymbolManager::conjureSymbol(const Stmt *E,
174 const LocationContext *LCtx,
177 const void *SymbolTag) {
178 llvm::FoldingSetNodeID profile;
179 SymbolConjured::Profile(profile, E, T, Count, LCtx, SymbolTag);
181 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
183 SD = (SymExpr*) BPAlloc.Allocate<SymbolConjured>();
184 new (SD) SymbolConjured(SymbolCounter, E, LCtx, T, Count, SymbolTag);
185 DataSet.InsertNode(SD, InsertPos);
189 return cast<SymbolConjured>(SD);
193 SymbolManager::getDerivedSymbol(SymbolRef parentSymbol,
194 const TypedValueRegion *R) {
196 llvm::FoldingSetNodeID profile;
197 SymbolDerived::Profile(profile, parentSymbol, R);
199 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
201 SD = (SymExpr*) BPAlloc.Allocate<SymbolDerived>();
202 new (SD) SymbolDerived(SymbolCounter, parentSymbol, R);
203 DataSet.InsertNode(SD, InsertPos);
207 return cast<SymbolDerived>(SD);
211 SymbolManager::getExtentSymbol(const SubRegion *R) {
212 llvm::FoldingSetNodeID profile;
213 SymbolExtent::Profile(profile, R);
215 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
217 SD = (SymExpr*) BPAlloc.Allocate<SymbolExtent>();
218 new (SD) SymbolExtent(SymbolCounter, R);
219 DataSet.InsertNode(SD, InsertPos);
223 return cast<SymbolExtent>(SD);
226 const SymbolMetadata *
227 SymbolManager::getMetadataSymbol(const MemRegion* R, const Stmt *S, QualType T,
228 const LocationContext *LCtx,
229 unsigned Count, const void *SymbolTag) {
231 llvm::FoldingSetNodeID profile;
232 SymbolMetadata::Profile(profile, R, S, T, LCtx, Count, SymbolTag);
234 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
236 SD = (SymExpr*) BPAlloc.Allocate<SymbolMetadata>();
237 new (SD) SymbolMetadata(SymbolCounter, R, S, T, LCtx, Count, SymbolTag);
238 DataSet.InsertNode(SD, InsertPos);
242 return cast<SymbolMetadata>(SD);
246 SymbolManager::getCastSymbol(const SymExpr *Op,
247 QualType From, QualType To) {
248 llvm::FoldingSetNodeID ID;
249 SymbolCast::Profile(ID, Op, From, To);
251 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
253 data = (SymbolCast*) BPAlloc.Allocate<SymbolCast>();
254 new (data) SymbolCast(Op, From, To);
255 DataSet.InsertNode(data, InsertPos);
258 return cast<SymbolCast>(data);
261 const SymIntExpr *SymbolManager::getSymIntExpr(const SymExpr *lhs,
262 BinaryOperator::Opcode op,
263 const llvm::APSInt& v,
265 llvm::FoldingSetNodeID ID;
266 SymIntExpr::Profile(ID, lhs, op, v, t);
268 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
271 data = (SymIntExpr*) BPAlloc.Allocate<SymIntExpr>();
272 new (data) SymIntExpr(lhs, op, v, t);
273 DataSet.InsertNode(data, InsertPos);
276 return cast<SymIntExpr>(data);
279 const IntSymExpr *SymbolManager::getIntSymExpr(const llvm::APSInt& lhs,
280 BinaryOperator::Opcode op,
283 llvm::FoldingSetNodeID ID;
284 IntSymExpr::Profile(ID, lhs, op, rhs, t);
286 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
289 data = (IntSymExpr*) BPAlloc.Allocate<IntSymExpr>();
290 new (data) IntSymExpr(lhs, op, rhs, t);
291 DataSet.InsertNode(data, InsertPos);
294 return cast<IntSymExpr>(data);
297 const SymSymExpr *SymbolManager::getSymSymExpr(const SymExpr *lhs,
298 BinaryOperator::Opcode op,
301 llvm::FoldingSetNodeID ID;
302 SymSymExpr::Profile(ID, lhs, op, rhs, t);
304 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
307 data = (SymSymExpr*) BPAlloc.Allocate<SymSymExpr>();
308 new (data) SymSymExpr(lhs, op, rhs, t);
309 DataSet.InsertNode(data, InsertPos);
312 return cast<SymSymExpr>(data);
315 QualType SymbolConjured::getType() const {
319 QualType SymbolDerived::getType() const {
320 return R->getValueType();
323 QualType SymbolExtent::getType() const {
324 ASTContext &Ctx = R->getMemRegionManager()->getContext();
325 return Ctx.getSizeType();
328 QualType SymbolMetadata::getType() const {
332 QualType SymbolRegionValue::getType() const {
333 return R->getValueType();
336 SymbolManager::~SymbolManager() {
337 llvm::DeleteContainerSeconds(SymbolDependencies);
340 bool SymbolManager::canSymbolicate(QualType T) {
341 T = T.getCanonicalType();
343 if (Loc::isLocType(T))
346 if (T->isIntegralOrEnumerationType())
349 if (T->isRecordType() && !T->isUnionType())
355 void SymbolManager::addSymbolDependency(const SymbolRef Primary,
356 const SymbolRef Dependent) {
357 SymbolDependTy::iterator I = SymbolDependencies.find(Primary);
358 SymbolRefSmallVectorTy *dependencies = nullptr;
359 if (I == SymbolDependencies.end()) {
360 dependencies = new SymbolRefSmallVectorTy();
361 SymbolDependencies[Primary] = dependencies;
363 dependencies = I->second;
365 dependencies->push_back(Dependent);
368 const SymbolRefSmallVectorTy *SymbolManager::getDependentSymbols(
369 const SymbolRef Primary) {
370 SymbolDependTy::const_iterator I = SymbolDependencies.find(Primary);
371 if (I == SymbolDependencies.end())
376 void SymbolReaper::markDependentsLive(SymbolRef sym) {
377 // Do not mark dependents more then once.
378 SymbolMapTy::iterator LI = TheLiving.find(sym);
379 assert(LI != TheLiving.end() && "The primary symbol is not live.");
380 if (LI->second == HaveMarkedDependents)
382 LI->second = HaveMarkedDependents;
384 if (const SymbolRefSmallVectorTy *Deps = SymMgr.getDependentSymbols(sym)) {
385 for (SymbolRefSmallVectorTy::const_iterator I = Deps->begin(),
386 E = Deps->end(); I != E; ++I) {
387 if (TheLiving.find(*I) != TheLiving.end())
394 void SymbolReaper::markLive(SymbolRef sym) {
395 TheLiving[sym] = NotProcessed;
397 markDependentsLive(sym);
400 void SymbolReaper::markLive(const MemRegion *region) {
401 RegionRoots.insert(region);
402 markElementIndicesLive(region);
405 void SymbolReaper::markElementIndicesLive(const MemRegion *region) {
406 for (auto SR = dyn_cast<SubRegion>(region); SR;
407 SR = dyn_cast<SubRegion>(SR->getSuperRegion())) {
408 if (auto ER = dyn_cast<ElementRegion>(SR)) {
409 SVal Idx = ER->getIndex();
410 for (auto SI = Idx.symbol_begin(), SE = Idx.symbol_end(); SI != SE; ++SI)
416 void SymbolReaper::markInUse(SymbolRef sym) {
417 if (isa<SymbolMetadata>(sym))
418 MetadataInUse.insert(sym);
421 bool SymbolReaper::maybeDead(SymbolRef sym) {
429 bool SymbolReaper::isLiveRegion(const MemRegion *MR) {
430 if (RegionRoots.count(MR))
433 MR = MR->getBaseRegion();
435 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
436 return isLive(SR->getSymbol());
438 if (const VarRegion *VR = dyn_cast<VarRegion>(MR))
439 return isLive(VR, true);
441 // FIXME: This is a gross over-approximation. What we really need is a way to
442 // tell if anything still refers to this region. Unlike SymbolicRegions,
443 // AllocaRegions don't have associated symbols, though, so we don't actually
444 // have a way to track their liveness.
445 if (isa<AllocaRegion>(MR))
448 if (isa<CXXThisRegion>(MR))
451 if (isa<MemSpaceRegion>(MR))
454 if (isa<CodeTextRegion>(MR))
460 bool SymbolReaper::isLive(SymbolRef sym) {
461 if (TheLiving.count(sym)) {
462 markDependentsLive(sym);
468 switch (sym->getKind()) {
469 case SymExpr::SymbolRegionValueKind:
470 KnownLive = isLiveRegion(cast<SymbolRegionValue>(sym)->getRegion());
472 case SymExpr::SymbolConjuredKind:
475 case SymExpr::SymbolDerivedKind:
476 KnownLive = isLive(cast<SymbolDerived>(sym)->getParentSymbol());
478 case SymExpr::SymbolExtentKind:
479 KnownLive = isLiveRegion(cast<SymbolExtent>(sym)->getRegion());
481 case SymExpr::SymbolMetadataKind:
482 KnownLive = MetadataInUse.count(sym) &&
483 isLiveRegion(cast<SymbolMetadata>(sym)->getRegion());
485 MetadataInUse.erase(sym);
487 case SymExpr::SymIntExprKind:
488 KnownLive = isLive(cast<SymIntExpr>(sym)->getLHS());
490 case SymExpr::IntSymExprKind:
491 KnownLive = isLive(cast<IntSymExpr>(sym)->getRHS());
493 case SymExpr::SymSymExprKind:
494 KnownLive = isLive(cast<SymSymExpr>(sym)->getLHS()) &&
495 isLive(cast<SymSymExpr>(sym)->getRHS());
497 case SymExpr::SymbolCastKind:
498 KnownLive = isLive(cast<SymbolCast>(sym)->getOperand());
509 SymbolReaper::isLive(const Stmt *ExprVal, const LocationContext *ELCtx) const {
514 // If the reaper's location context is a parent of the expression's
515 // location context, then the expression value is now "out of scope".
516 if (LCtx->isParentOf(ELCtx))
521 // If no statement is provided, everything is this and parent contexts is live.
525 return LCtx->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, ExprVal);
528 bool SymbolReaper::isLive(const VarRegion *VR, bool includeStoreBindings) const{
529 const StackFrameContext *VarContext = VR->getStackFrame();
536 const StackFrameContext *CurrentContext = LCtx->getCurrentStackFrame();
538 if (VarContext == CurrentContext) {
539 // If no statement is provided, everything is live.
543 if (LCtx->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, VR->getDecl()))
546 if (!includeStoreBindings)
549 unsigned &cachedQuery =
550 const_cast<SymbolReaper*>(this)->includedRegionCache[VR];
553 return cachedQuery == 1;
556 // Query the store to see if the region occurs in any live bindings.
557 if (Store store = reapedStore.getStore()) {
559 reapedStore.getStoreManager().includedInBindings(store, VR);
560 cachedQuery = hasRegion ? 1 : 2;
567 return VarContext->isParentOf(CurrentContext);