xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision fa2b83d07ecab3b24b4c5ee2e7dc4b6bbc895317)
1 //===-- DataflowEnvironment.cpp ---------------------------------*- C++ -*-===//
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 an Environment class that is used by dataflow analyses
10 //  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
11 //  program at given program points.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/Type.h"
19 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
20 #include "clang/Analysis/FlowSensitive/Value.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include <cassert>
26 #include <memory>
27 #include <utility>
28 
29 namespace clang {
30 namespace dataflow {
31 
32 // FIXME: convert these to parameters of the analysis or environment. Current
33 // settings have been experimentaly validated, but only for a particular
34 // analysis.
35 static constexpr int MaxCompositeValueDepth = 3;
36 static constexpr int MaxCompositeValueSize = 1000;
37 
38 /// Returns a map consisting of key-value entries that are present in both maps.
39 template <typename K, typename V>
40 llvm::DenseMap<K, V> intersectDenseMaps(const llvm::DenseMap<K, V> &Map1,
41                                         const llvm::DenseMap<K, V> &Map2) {
42   llvm::DenseMap<K, V> Result;
43   for (auto &Entry : Map1) {
44     auto It = Map2.find(Entry.first);
45     if (It != Map2.end() && Entry.second == It->second)
46       Result.insert({Entry.first, Entry.second});
47   }
48   return Result;
49 }
50 
51 static bool areEquivalentIndirectionValues(Value *Val1, Value *Val2) {
52   if (auto *IndVal1 = dyn_cast<ReferenceValue>(Val1)) {
53     auto *IndVal2 = cast<ReferenceValue>(Val2);
54     return &IndVal1->getReferentLoc() == &IndVal2->getReferentLoc();
55   }
56   if (auto *IndVal1 = dyn_cast<PointerValue>(Val1)) {
57     auto *IndVal2 = cast<PointerValue>(Val2);
58     return &IndVal1->getPointeeLoc() == &IndVal2->getPointeeLoc();
59   }
60   return false;
61 }
62 
63 /// Returns true if and only if `Val1` is equivalent to `Val2`.
64 static bool equivalentValues(QualType Type, Value *Val1,
65                              const Environment &Env1, Value *Val2,
66                              const Environment &Env2,
67                              Environment::ValueModel &Model) {
68   return Val1 == Val2 || areEquivalentIndirectionValues(Val1, Val2) ||
69          Model.compareEquivalent(Type, *Val1, Env1, *Val2, Env2);
70 }
71 
72 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`,
73 /// respectively, of the same type `Type`. Merging generally produces a single
74 /// value that (soundly) approximates the two inputs, although the actual
75 /// meaning depends on `Model`.
76 static Value *mergeDistinctValues(QualType Type, Value *Val1,
77                                   const Environment &Env1, Value *Val2,
78                                   const Environment &Env2,
79                                   Environment &MergedEnv,
80                                   Environment::ValueModel &Model) {
81   // Join distinct boolean values preserving information about the constraints
82   // in the respective path conditions.
83   //
84   // FIXME: Does not work for backedges, since the two (or more) paths will not
85   // have mutually exclusive conditions.
86   if (auto *Expr1 = dyn_cast<BoolValue>(Val1)) {
87     auto *Expr2 = cast<BoolValue>(Val2);
88     auto &MergedVal = MergedEnv.makeAtomicBoolValue();
89     MergedEnv.addToFlowCondition(MergedEnv.makeOr(
90         MergedEnv.makeAnd(Env1.getFlowConditionToken(),
91                           MergedEnv.makeIff(MergedVal, *Expr1)),
92         MergedEnv.makeAnd(Env2.getFlowConditionToken(),
93                           MergedEnv.makeIff(MergedVal, *Expr2))));
94     return &MergedVal;
95   }
96 
97   // FIXME: add unit tests that cover this statement.
98   if (areEquivalentIndirectionValues(Val1, Val2)) {
99     return Val1;
100   }
101 
102   // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge`
103   // returns false to avoid storing unneeded values in `DACtx`.
104   if (Value *MergedVal = MergedEnv.createValue(Type))
105     if (Model.merge(Type, *Val1, Env1, *Val2, Env2, *MergedVal, MergedEnv))
106       return MergedVal;
107 
108   return nullptr;
109 }
110 
111 /// Initializes a global storage value.
112 static void initGlobalVar(const VarDecl &D, Environment &Env) {
113   if (!D.hasGlobalStorage() ||
114       Env.getStorageLocation(D, SkipPast::None) != nullptr)
115     return;
116 
117   auto &Loc = Env.createStorageLocation(D);
118   Env.setStorageLocation(D, Loc);
119   if (auto *Val = Env.createValue(D.getType()))
120     Env.setValue(Loc, *Val);
121 }
122 
123 /// Initializes a global storage value.
124 static void initGlobalVar(const Decl &D, Environment &Env) {
125   if (auto *V = dyn_cast<VarDecl>(&D))
126     initGlobalVar(*V, Env);
127 }
128 
129 /// Initializes global storage values that are declared or referenced from
130 /// sub-statements of `S`.
131 // FIXME: Add support for resetting globals after function calls to enable
132 // the implementation of sound analyses.
133 static void initGlobalVars(const Stmt &S, Environment &Env) {
134   for (auto *Child : S.children()) {
135     if (Child != nullptr)
136       initGlobalVars(*Child, Env);
137   }
138 
139   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
140     if (DS->isSingleDecl()) {
141       initGlobalVar(*DS->getSingleDecl(), Env);
142     } else {
143       for (auto *D : DS->getDeclGroup())
144         initGlobalVar(*D, Env);
145     }
146   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
147     initGlobalVar(*E->getDecl(), Env);
148   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
149     initGlobalVar(*E->getMemberDecl(), Env);
150   }
151 }
152 
153 Environment::Environment(DataflowAnalysisContext &DACtx)
154     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
155 
156 Environment::Environment(const Environment &Other)
157     : DACtx(Other.DACtx), DeclToLoc(Other.DeclToLoc),
158       ExprToLoc(Other.ExprToLoc), LocToVal(Other.LocToVal),
159       MemberLocToStruct(Other.MemberLocToStruct),
160       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
161 }
162 
163 Environment &Environment::operator=(const Environment &Other) {
164   Environment Copy(Other);
165   *this = std::move(Copy);
166   return *this;
167 }
168 
169 Environment::Environment(DataflowAnalysisContext &DACtx,
170                          const DeclContext &DeclCtx)
171     : Environment(DACtx) {
172   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
173     assert(FuncDecl->getBody() != nullptr);
174     initGlobalVars(*FuncDecl->getBody(), *this);
175     for (const auto *ParamDecl : FuncDecl->parameters()) {
176       assert(ParamDecl != nullptr);
177       auto &ParamLoc = createStorageLocation(*ParamDecl);
178       setStorageLocation(*ParamDecl, ParamLoc);
179       if (Value *ParamVal = createValue(ParamDecl->getType()))
180         setValue(ParamLoc, *ParamVal);
181     }
182   }
183 
184   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
185     auto *Parent = MethodDecl->getParent();
186     assert(Parent != nullptr);
187     if (Parent->isLambda())
188       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
189 
190     if (MethodDecl && !MethodDecl->isStatic()) {
191       QualType ThisPointeeType = MethodDecl->getThisObjectType();
192       // FIXME: Add support for union types.
193       if (!ThisPointeeType->isUnionType()) {
194         auto &ThisPointeeLoc = createStorageLocation(ThisPointeeType);
195         DACtx.setThisPointeeStorageLocation(ThisPointeeLoc);
196         if (Value *ThisPointeeVal = createValue(ThisPointeeType))
197           setValue(ThisPointeeLoc, *ThisPointeeVal);
198       }
199     }
200   }
201 }
202 
203 Environment Environment::pushCall(const CallExpr *Call) const {
204   Environment Env(*this);
205 
206   // FIXME: Currently this only works if the callee is never a method and the
207   // same callee is never analyzed from multiple separate callsites. To
208   // generalize this, we'll need to store a "context" field (probably a stack of
209   // `const CallExpr *`s) in the `Environment`, and then change the
210   // `DataflowAnalysisContext` class to hold a map from contexts to "frames",
211   // where each frame stores its own version of what are currently the
212   // `DeclToLoc`, `ExprToLoc`, and `ThisPointeeLoc` fields.
213 
214   const auto *FuncDecl = Call->getDirectCallee();
215   assert(FuncDecl != nullptr);
216   const auto *Body = FuncDecl->getBody();
217   assert(Body != nullptr);
218   // FIXME: In order to allow the callee to reference globals, we probably need
219   // to call `initGlobalVars` here in some way.
220 
221   auto ParamIt = FuncDecl->param_begin();
222   auto ParamEnd = FuncDecl->param_end();
223   auto ArgIt = Call->arg_begin();
224   auto ArgEnd = Call->arg_end();
225 
226   // FIXME: Parameters don't always map to arguments 1:1; examples include
227   // overloaded operators implemented as member functions, and parameter packs.
228   for (; ArgIt != ArgEnd; ++ParamIt, ++ArgIt) {
229     assert(ParamIt != ParamEnd);
230 
231     const VarDecl *Param = *ParamIt;
232     const Expr *Arg = *ArgIt;
233     auto *ArgLoc = Env.getStorageLocation(*Arg, SkipPast::Reference);
234     assert(ArgLoc != nullptr);
235     Env.setStorageLocation(*Param, *ArgLoc);
236   }
237 
238   return Env;
239 }
240 
241 bool Environment::equivalentTo(const Environment &Other,
242                                Environment::ValueModel &Model) const {
243   assert(DACtx == Other.DACtx);
244 
245   if (DeclToLoc != Other.DeclToLoc)
246     return false;
247 
248   if (ExprToLoc != Other.ExprToLoc)
249     return false;
250 
251   // Compare the contents for the intersection of their domains.
252   for (auto &Entry : LocToVal) {
253     const StorageLocation *Loc = Entry.first;
254     assert(Loc != nullptr);
255 
256     Value *Val = Entry.second;
257     assert(Val != nullptr);
258 
259     auto It = Other.LocToVal.find(Loc);
260     if (It == Other.LocToVal.end())
261       continue;
262     assert(It->second != nullptr);
263 
264     if (!equivalentValues(Loc->getType(), Val, *this, It->second, Other, Model))
265       return false;
266   }
267 
268   return true;
269 }
270 
271 LatticeJoinEffect Environment::join(const Environment &Other,
272                                     Environment::ValueModel &Model) {
273   assert(DACtx == Other.DACtx);
274 
275   auto Effect = LatticeJoinEffect::Unchanged;
276 
277   Environment JoinedEnv(*DACtx);
278 
279   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
280   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
281     Effect = LatticeJoinEffect::Changed;
282 
283   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
284   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
285     Effect = LatticeJoinEffect::Changed;
286 
287   JoinedEnv.MemberLocToStruct =
288       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
289   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
290     Effect = LatticeJoinEffect::Changed;
291 
292   // FIXME: set `Effect` as needed.
293   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
294       *FlowConditionToken, *Other.FlowConditionToken);
295 
296   for (auto &Entry : LocToVal) {
297     const StorageLocation *Loc = Entry.first;
298     assert(Loc != nullptr);
299 
300     Value *Val = Entry.second;
301     assert(Val != nullptr);
302 
303     auto It = Other.LocToVal.find(Loc);
304     if (It == Other.LocToVal.end())
305       continue;
306     assert(It->second != nullptr);
307 
308     if (Val == It->second) {
309       JoinedEnv.LocToVal.insert({Loc, Val});
310       continue;
311     }
312 
313     if (Value *MergedVal = mergeDistinctValues(
314             Loc->getType(), Val, *this, It->second, Other, JoinedEnv, Model))
315       JoinedEnv.LocToVal.insert({Loc, MergedVal});
316   }
317   if (LocToVal.size() != JoinedEnv.LocToVal.size())
318     Effect = LatticeJoinEffect::Changed;
319 
320   *this = std::move(JoinedEnv);
321 
322   return Effect;
323 }
324 
325 StorageLocation &Environment::createStorageLocation(QualType Type) {
326   return DACtx->getStableStorageLocation(Type);
327 }
328 
329 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
330   // Evaluated declarations are always assigned the same storage locations to
331   // ensure that the environment stabilizes across loop iterations. Storage
332   // locations for evaluated declarations are stored in the analysis context.
333   return DACtx->getStableStorageLocation(D);
334 }
335 
336 StorageLocation &Environment::createStorageLocation(const Expr &E) {
337   // Evaluated expressions are always assigned the same storage locations to
338   // ensure that the environment stabilizes across loop iterations. Storage
339   // locations for evaluated expressions are stored in the analysis context.
340   return DACtx->getStableStorageLocation(E);
341 }
342 
343 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
344   assert(DeclToLoc.find(&D) == DeclToLoc.end());
345   DeclToLoc[&D] = &Loc;
346 }
347 
348 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
349                                                  SkipPast SP) const {
350   auto It = DeclToLoc.find(&D);
351   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
352 }
353 
354 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
355   const Expr &CanonE = ignoreCFGOmittedNodes(E);
356   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
357   ExprToLoc[&CanonE] = &Loc;
358 }
359 
360 StorageLocation *Environment::getStorageLocation(const Expr &E,
361                                                  SkipPast SP) const {
362   // FIXME: Add a test with parens.
363   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
364   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
365 }
366 
367 StorageLocation *Environment::getThisPointeeStorageLocation() const {
368   return DACtx->getThisPointeeStorageLocation();
369 }
370 
371 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
372   return DACtx->getOrCreateNullPointerValue(PointeeType);
373 }
374 
375 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
376   LocToVal[&Loc] = &Val;
377 
378   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
379     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
380 
381     const QualType Type = AggregateLoc.getType();
382     assert(Type->isStructureOrClassType());
383 
384     for (const FieldDecl *Field : getObjectFields(Type)) {
385       assert(Field != nullptr);
386       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
387       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
388       if (auto *FieldVal = StructVal->getChild(*Field))
389         setValue(FieldLoc, *FieldVal);
390     }
391   }
392 
393   auto It = MemberLocToStruct.find(&Loc);
394   if (It != MemberLocToStruct.end()) {
395     // `Loc` is the location of a struct member so we need to also update the
396     // value of the member in the corresponding `StructValue`.
397 
398     assert(It->second.first != nullptr);
399     StructValue &StructVal = *It->second.first;
400 
401     assert(It->second.second != nullptr);
402     const ValueDecl &Member = *It->second.second;
403 
404     StructVal.setChild(Member, Val);
405   }
406 }
407 
408 Value *Environment::getValue(const StorageLocation &Loc) const {
409   auto It = LocToVal.find(&Loc);
410   return It == LocToVal.end() ? nullptr : It->second;
411 }
412 
413 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
414   auto *Loc = getStorageLocation(D, SP);
415   if (Loc == nullptr)
416     return nullptr;
417   return getValue(*Loc);
418 }
419 
420 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
421   auto *Loc = getStorageLocation(E, SP);
422   if (Loc == nullptr)
423     return nullptr;
424   return getValue(*Loc);
425 }
426 
427 Value *Environment::createValue(QualType Type) {
428   llvm::DenseSet<QualType> Visited;
429   int CreatedValuesCount = 0;
430   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
431                                                 CreatedValuesCount);
432   if (CreatedValuesCount > MaxCompositeValueSize) {
433     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
434                  << '\n';
435   }
436   return Val;
437 }
438 
439 Value *Environment::createValueUnlessSelfReferential(
440     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
441     int &CreatedValuesCount) {
442   assert(!Type.isNull());
443 
444   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
445   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
446       Depth > MaxCompositeValueDepth)
447     return nullptr;
448 
449   if (Type->isBooleanType()) {
450     CreatedValuesCount++;
451     return &makeAtomicBoolValue();
452   }
453 
454   if (Type->isIntegerType()) {
455     CreatedValuesCount++;
456     return &takeOwnership(std::make_unique<IntegerValue>());
457   }
458 
459   if (Type->isReferenceType()) {
460     CreatedValuesCount++;
461     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
462     auto &PointeeLoc = createStorageLocation(PointeeType);
463 
464     if (Visited.insert(PointeeType.getCanonicalType()).second) {
465       Value *PointeeVal = createValueUnlessSelfReferential(
466           PointeeType, Visited, Depth, CreatedValuesCount);
467       Visited.erase(PointeeType.getCanonicalType());
468 
469       if (PointeeVal != nullptr)
470         setValue(PointeeLoc, *PointeeVal);
471     }
472 
473     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
474   }
475 
476   if (Type->isPointerType()) {
477     CreatedValuesCount++;
478     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
479     auto &PointeeLoc = createStorageLocation(PointeeType);
480 
481     if (Visited.insert(PointeeType.getCanonicalType()).second) {
482       Value *PointeeVal = createValueUnlessSelfReferential(
483           PointeeType, Visited, Depth, CreatedValuesCount);
484       Visited.erase(PointeeType.getCanonicalType());
485 
486       if (PointeeVal != nullptr)
487         setValue(PointeeLoc, *PointeeVal);
488     }
489 
490     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
491   }
492 
493   if (Type->isStructureOrClassType()) {
494     CreatedValuesCount++;
495     // FIXME: Initialize only fields that are accessed in the context that is
496     // being analyzed.
497     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
498     for (const FieldDecl *Field : getObjectFields(Type)) {
499       assert(Field != nullptr);
500 
501       QualType FieldType = Field->getType();
502       if (Visited.contains(FieldType.getCanonicalType()))
503         continue;
504 
505       Visited.insert(FieldType.getCanonicalType());
506       if (auto *FieldValue = createValueUnlessSelfReferential(
507               FieldType, Visited, Depth + 1, CreatedValuesCount))
508         FieldValues.insert({Field, FieldValue});
509       Visited.erase(FieldType.getCanonicalType());
510     }
511 
512     return &takeOwnership(
513         std::make_unique<StructValue>(std::move(FieldValues)));
514   }
515 
516   return nullptr;
517 }
518 
519 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
520   switch (SP) {
521   case SkipPast::None:
522     return Loc;
523   case SkipPast::Reference:
524     // References cannot be chained so we only need to skip past one level of
525     // indirection.
526     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
527       return Val->getReferentLoc();
528     return Loc;
529   case SkipPast::ReferenceThenPointer:
530     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
531     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
532       return Val->getPointeeLoc();
533     return LocPastRef;
534   }
535   llvm_unreachable("bad SkipPast kind");
536 }
537 
538 const StorageLocation &Environment::skip(const StorageLocation &Loc,
539                                          SkipPast SP) const {
540   return skip(*const_cast<StorageLocation *>(&Loc), SP);
541 }
542 
543 void Environment::addToFlowCondition(BoolValue &Val) {
544   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
545 }
546 
547 bool Environment::flowConditionImplies(BoolValue &Val) const {
548   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
549 }
550 
551 void Environment::dump() const {
552   DACtx->dumpFlowCondition(*FlowConditionToken);
553 }
554 
555 } // namespace dataflow
556 } // namespace clang
557