xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision a6ddc68487823d48c0ec0ddd649ace4a2732d0b0)
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   const auto *FuncDecl = Call->getDirectCallee();
207   assert(FuncDecl != nullptr);
208   assert(FuncDecl->getBody() != nullptr);
209   // FIXME: In order to allow the callee to reference globals, we probably need
210   // to call `initGlobalVars` here in some way.
211 
212   auto ParamIt = FuncDecl->param_begin();
213   auto ArgIt = Call->arg_begin();
214   auto ArgEnd = Call->arg_end();
215 
216   // FIXME: Parameters don't always map to arguments 1:1; examples include
217   // overloaded operators implemented as member functions, and parameter packs.
218   for (; ArgIt != ArgEnd; ++ParamIt, ++ArgIt) {
219     assert(ParamIt != FuncDecl->param_end());
220 
221     const Expr *Arg = *ArgIt;
222     auto *ArgLoc = Env.getStorageLocation(*Arg, SkipPast::Reference);
223     assert(ArgLoc != nullptr);
224 
225     const VarDecl *Param = *ParamIt;
226     auto &Loc = Env.createStorageLocation(*Param);
227     Env.setStorageLocation(*Param, Loc);
228 
229     QualType ParamType = Param->getType();
230     if (ParamType->isReferenceType()) {
231       auto &Val = Env.takeOwnership(std::make_unique<ReferenceValue>(*ArgLoc));
232       Env.setValue(Loc, Val);
233     } else if (auto *ArgVal = Env.getValue(*ArgLoc)) {
234       Env.setValue(Loc, *ArgVal);
235     } else if (Value *Val = Env.createValue(ParamType)) {
236       Env.setValue(Loc, *Val);
237     }
238   }
239 
240   return Env;
241 }
242 
243 void Environment::popCall(const Environment &CalleeEnv) {
244   // We ignore `DACtx` because it's already the same in both. We don't bring
245   // back `DeclToLoc` and `ExprToLoc` because we want to be able to later
246   // analyze the same callee in a different context, and `setStorageLocation`
247   // requires there to not already be a storage location assigned. Conceptually,
248   // these maps capture information from the local scope, so when popping that
249   // scope, we do not propagate the maps.
250   this->LocToVal = std::move(CalleeEnv.LocToVal);
251   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
252   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
253 }
254 
255 bool Environment::equivalentTo(const Environment &Other,
256                                Environment::ValueModel &Model) const {
257   assert(DACtx == Other.DACtx);
258 
259   if (DeclToLoc != Other.DeclToLoc)
260     return false;
261 
262   if (ExprToLoc != Other.ExprToLoc)
263     return false;
264 
265   // Compare the contents for the intersection of their domains.
266   for (auto &Entry : LocToVal) {
267     const StorageLocation *Loc = Entry.first;
268     assert(Loc != nullptr);
269 
270     Value *Val = Entry.second;
271     assert(Val != nullptr);
272 
273     auto It = Other.LocToVal.find(Loc);
274     if (It == Other.LocToVal.end())
275       continue;
276     assert(It->second != nullptr);
277 
278     if (!equivalentValues(Loc->getType(), Val, *this, It->second, Other, Model))
279       return false;
280   }
281 
282   return true;
283 }
284 
285 LatticeJoinEffect Environment::join(const Environment &Other,
286                                     Environment::ValueModel &Model) {
287   assert(DACtx == Other.DACtx);
288 
289   auto Effect = LatticeJoinEffect::Unchanged;
290 
291   Environment JoinedEnv(*DACtx);
292 
293   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
294   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
295     Effect = LatticeJoinEffect::Changed;
296 
297   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
298   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
299     Effect = LatticeJoinEffect::Changed;
300 
301   JoinedEnv.MemberLocToStruct =
302       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
303   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
304     Effect = LatticeJoinEffect::Changed;
305 
306   // FIXME: set `Effect` as needed.
307   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
308       *FlowConditionToken, *Other.FlowConditionToken);
309 
310   for (auto &Entry : LocToVal) {
311     const StorageLocation *Loc = Entry.first;
312     assert(Loc != nullptr);
313 
314     Value *Val = Entry.second;
315     assert(Val != nullptr);
316 
317     auto It = Other.LocToVal.find(Loc);
318     if (It == Other.LocToVal.end())
319       continue;
320     assert(It->second != nullptr);
321 
322     if (Val == It->second) {
323       JoinedEnv.LocToVal.insert({Loc, Val});
324       continue;
325     }
326 
327     if (Value *MergedVal = mergeDistinctValues(
328             Loc->getType(), Val, *this, It->second, Other, JoinedEnv, Model))
329       JoinedEnv.LocToVal.insert({Loc, MergedVal});
330   }
331   if (LocToVal.size() != JoinedEnv.LocToVal.size())
332     Effect = LatticeJoinEffect::Changed;
333 
334   *this = std::move(JoinedEnv);
335 
336   return Effect;
337 }
338 
339 StorageLocation &Environment::createStorageLocation(QualType Type) {
340   return DACtx->getStableStorageLocation(Type);
341 }
342 
343 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
344   // Evaluated declarations are always assigned the same storage locations to
345   // ensure that the environment stabilizes across loop iterations. Storage
346   // locations for evaluated declarations are stored in the analysis context.
347   return DACtx->getStableStorageLocation(D);
348 }
349 
350 StorageLocation &Environment::createStorageLocation(const Expr &E) {
351   // Evaluated expressions are always assigned the same storage locations to
352   // ensure that the environment stabilizes across loop iterations. Storage
353   // locations for evaluated expressions are stored in the analysis context.
354   return DACtx->getStableStorageLocation(E);
355 }
356 
357 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
358   assert(DeclToLoc.find(&D) == DeclToLoc.end());
359   DeclToLoc[&D] = &Loc;
360 }
361 
362 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
363                                                  SkipPast SP) const {
364   auto It = DeclToLoc.find(&D);
365   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
366 }
367 
368 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
369   const Expr &CanonE = ignoreCFGOmittedNodes(E);
370   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
371   ExprToLoc[&CanonE] = &Loc;
372 }
373 
374 StorageLocation *Environment::getStorageLocation(const Expr &E,
375                                                  SkipPast SP) const {
376   // FIXME: Add a test with parens.
377   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
378   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
379 }
380 
381 StorageLocation *Environment::getThisPointeeStorageLocation() const {
382   return DACtx->getThisPointeeStorageLocation();
383 }
384 
385 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
386   return DACtx->getOrCreateNullPointerValue(PointeeType);
387 }
388 
389 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
390   LocToVal[&Loc] = &Val;
391 
392   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
393     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
394 
395     const QualType Type = AggregateLoc.getType();
396     assert(Type->isStructureOrClassType());
397 
398     for (const FieldDecl *Field : getObjectFields(Type)) {
399       assert(Field != nullptr);
400       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
401       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
402       if (auto *FieldVal = StructVal->getChild(*Field))
403         setValue(FieldLoc, *FieldVal);
404     }
405   }
406 
407   auto It = MemberLocToStruct.find(&Loc);
408   if (It != MemberLocToStruct.end()) {
409     // `Loc` is the location of a struct member so we need to also update the
410     // value of the member in the corresponding `StructValue`.
411 
412     assert(It->second.first != nullptr);
413     StructValue &StructVal = *It->second.first;
414 
415     assert(It->second.second != nullptr);
416     const ValueDecl &Member = *It->second.second;
417 
418     StructVal.setChild(Member, Val);
419   }
420 }
421 
422 Value *Environment::getValue(const StorageLocation &Loc) const {
423   auto It = LocToVal.find(&Loc);
424   return It == LocToVal.end() ? nullptr : It->second;
425 }
426 
427 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
428   auto *Loc = getStorageLocation(D, SP);
429   if (Loc == nullptr)
430     return nullptr;
431   return getValue(*Loc);
432 }
433 
434 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
435   auto *Loc = getStorageLocation(E, SP);
436   if (Loc == nullptr)
437     return nullptr;
438   return getValue(*Loc);
439 }
440 
441 Value *Environment::createValue(QualType Type) {
442   llvm::DenseSet<QualType> Visited;
443   int CreatedValuesCount = 0;
444   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
445                                                 CreatedValuesCount);
446   if (CreatedValuesCount > MaxCompositeValueSize) {
447     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
448                  << '\n';
449   }
450   return Val;
451 }
452 
453 Value *Environment::createValueUnlessSelfReferential(
454     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
455     int &CreatedValuesCount) {
456   assert(!Type.isNull());
457 
458   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
459   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
460       Depth > MaxCompositeValueDepth)
461     return nullptr;
462 
463   if (Type->isBooleanType()) {
464     CreatedValuesCount++;
465     return &makeAtomicBoolValue();
466   }
467 
468   if (Type->isIntegerType()) {
469     CreatedValuesCount++;
470     return &takeOwnership(std::make_unique<IntegerValue>());
471   }
472 
473   if (Type->isReferenceType()) {
474     CreatedValuesCount++;
475     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
476     auto &PointeeLoc = createStorageLocation(PointeeType);
477 
478     if (Visited.insert(PointeeType.getCanonicalType()).second) {
479       Value *PointeeVal = createValueUnlessSelfReferential(
480           PointeeType, Visited, Depth, CreatedValuesCount);
481       Visited.erase(PointeeType.getCanonicalType());
482 
483       if (PointeeVal != nullptr)
484         setValue(PointeeLoc, *PointeeVal);
485     }
486 
487     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
488   }
489 
490   if (Type->isPointerType()) {
491     CreatedValuesCount++;
492     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
493     auto &PointeeLoc = createStorageLocation(PointeeType);
494 
495     if (Visited.insert(PointeeType.getCanonicalType()).second) {
496       Value *PointeeVal = createValueUnlessSelfReferential(
497           PointeeType, Visited, Depth, CreatedValuesCount);
498       Visited.erase(PointeeType.getCanonicalType());
499 
500       if (PointeeVal != nullptr)
501         setValue(PointeeLoc, *PointeeVal);
502     }
503 
504     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
505   }
506 
507   if (Type->isStructureOrClassType()) {
508     CreatedValuesCount++;
509     // FIXME: Initialize only fields that are accessed in the context that is
510     // being analyzed.
511     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
512     for (const FieldDecl *Field : getObjectFields(Type)) {
513       assert(Field != nullptr);
514 
515       QualType FieldType = Field->getType();
516       if (Visited.contains(FieldType.getCanonicalType()))
517         continue;
518 
519       Visited.insert(FieldType.getCanonicalType());
520       if (auto *FieldValue = createValueUnlessSelfReferential(
521               FieldType, Visited, Depth + 1, CreatedValuesCount))
522         FieldValues.insert({Field, FieldValue});
523       Visited.erase(FieldType.getCanonicalType());
524     }
525 
526     return &takeOwnership(
527         std::make_unique<StructValue>(std::move(FieldValues)));
528   }
529 
530   return nullptr;
531 }
532 
533 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
534   switch (SP) {
535   case SkipPast::None:
536     return Loc;
537   case SkipPast::Reference:
538     // References cannot be chained so we only need to skip past one level of
539     // indirection.
540     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
541       return Val->getReferentLoc();
542     return Loc;
543   case SkipPast::ReferenceThenPointer:
544     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
545     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
546       return Val->getPointeeLoc();
547     return LocPastRef;
548   }
549   llvm_unreachable("bad SkipPast kind");
550 }
551 
552 const StorageLocation &Environment::skip(const StorageLocation &Loc,
553                                          SkipPast SP) const {
554   return skip(*const_cast<StorageLocation *>(&Loc), SP);
555 }
556 
557 void Environment::addToFlowCondition(BoolValue &Val) {
558   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
559 }
560 
561 bool Environment::flowConditionImplies(BoolValue &Val) const {
562   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
563 }
564 
565 void Environment::dump() const {
566   DACtx->dumpFlowCondition(*FlowConditionToken);
567 }
568 
569 } // namespace dataflow
570 } // namespace clang
571