xref: /freebsd/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision 66fd12cf4896eb08ad8e7a2627537f84ead84dd3)
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/ADT/STLExtras.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include <cassert>
27 #include <memory>
28 #include <utility>
29 
30 namespace clang {
31 namespace dataflow {
32 
33 // FIXME: convert these to parameters of the analysis or environment. Current
34 // settings have been experimentaly validated, but only for a particular
35 // analysis.
36 static constexpr int MaxCompositeValueDepth = 3;
37 static constexpr int MaxCompositeValueSize = 1000;
38 
39 /// Returns a map consisting of key-value entries that are present in both maps.
40 template <typename K, typename V>
41 llvm::DenseMap<K, V> intersectDenseMaps(const llvm::DenseMap<K, V> &Map1,
42                                         const llvm::DenseMap<K, V> &Map2) {
43   llvm::DenseMap<K, V> Result;
44   for (auto &Entry : Map1) {
45     auto It = Map2.find(Entry.first);
46     if (It != Map2.end() && Entry.second == It->second)
47       Result.insert({Entry.first, Entry.second});
48   }
49   return Result;
50 }
51 
52 static bool compareDistinctValues(QualType Type, Value &Val1,
53                                   const Environment &Env1, Value &Val2,
54                                   const Environment &Env2,
55                                   Environment::ValueModel &Model) {
56   // Note: Potentially costly, but, for booleans, we could check whether both
57   // can be proven equivalent in their respective environments.
58 
59   // FIXME: move the reference/pointers logic from `areEquivalentValues` to here
60   // and implement separate, join/widen specific handling for
61   // reference/pointers.
62   switch (Model.compare(Type, Val1, Env1, Val2, Env2)) {
63   case ComparisonResult::Same:
64     return true;
65   case ComparisonResult::Different:
66     return false;
67   case ComparisonResult::Unknown:
68     switch (Val1.getKind()) {
69     case Value::Kind::Integer:
70     case Value::Kind::Reference:
71     case Value::Kind::Pointer:
72     case Value::Kind::Struct:
73       // FIXME: this choice intentionally introduces unsoundness to allow
74       // for convergence. Once we have widening support for the
75       // reference/pointer and struct built-in models, this should be
76       // `false`.
77       return true;
78     default:
79       return false;
80     }
81   }
82   llvm_unreachable("All cases covered in switch");
83 }
84 
85 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`,
86 /// respectively, of the same type `Type`. Merging generally produces a single
87 /// value that (soundly) approximates the two inputs, although the actual
88 /// meaning depends on `Model`.
89 static Value *mergeDistinctValues(QualType Type, Value &Val1,
90                                   const Environment &Env1, Value &Val2,
91                                   const Environment &Env2,
92                                   Environment &MergedEnv,
93                                   Environment::ValueModel &Model) {
94   // Join distinct boolean values preserving information about the constraints
95   // in the respective path conditions.
96   if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) {
97     // FIXME: Checking both values should be unnecessary, since they should have
98     // a consistent shape.  However, right now we can end up with BoolValue's in
99     // integer-typed variables due to our incorrect handling of
100     // boolean-to-integer casts (we just propagate the BoolValue to the result
101     // of the cast). So, a join can encounter an integer in one branch but a
102     // bool in the other.
103     // For example:
104     // ```
105     // std::optional<bool> o;
106     // int x;
107     // if (o.has_value())
108     //   x = o.value();
109     // ```
110     auto *Expr1 = cast<BoolValue>(&Val1);
111     auto *Expr2 = cast<BoolValue>(&Val2);
112     auto &MergedVal = MergedEnv.makeAtomicBoolValue();
113     MergedEnv.addToFlowCondition(MergedEnv.makeOr(
114         MergedEnv.makeAnd(Env1.getFlowConditionToken(),
115                           MergedEnv.makeIff(MergedVal, *Expr1)),
116         MergedEnv.makeAnd(Env2.getFlowConditionToken(),
117                           MergedEnv.makeIff(MergedVal, *Expr2))));
118     return &MergedVal;
119   }
120 
121   // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge`
122   // returns false to avoid storing unneeded values in `DACtx`.
123   // FIXME: Creating the value based on the type alone creates misshapen values
124   // for lvalues, since the type does not reflect the need for `ReferenceValue`.
125   if (Value *MergedVal = MergedEnv.createValue(Type))
126     if (Model.merge(Type, Val1, Env1, Val2, Env2, *MergedVal, MergedEnv))
127       return MergedVal;
128 
129   return nullptr;
130 }
131 
132 // When widening does not change `Current`, return value will equal `&Prev`.
133 static Value &widenDistinctValues(QualType Type, Value &Prev,
134                                   const Environment &PrevEnv, Value &Current,
135                                   Environment &CurrentEnv,
136                                   Environment::ValueModel &Model) {
137   // Boolean-model widening.
138   if (isa<BoolValue>(&Prev)) {
139     assert(isa<BoolValue>(Current));
140     // Widen to Top, because we know they are different values. If previous was
141     // already Top, re-use that to (implicitly) indicate that no change occured.
142     if (isa<TopBoolValue>(Prev))
143       return Prev;
144     return CurrentEnv.makeTopBoolValue();
145   }
146 
147   // FIXME: Add other built-in model widening.
148 
149   // Custom-model widening.
150   if (auto *W = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv))
151     return *W;
152 
153   // Default of widening is a no-op: leave the current value unchanged.
154   return Current;
155 }
156 
157 /// Initializes a global storage value.
158 static void insertIfGlobal(const Decl &D,
159                            llvm::DenseSet<const FieldDecl *> &Fields,
160                            llvm::DenseSet<const VarDecl *> &Vars) {
161   if (auto *V = dyn_cast<VarDecl>(&D))
162     if (V->hasGlobalStorage())
163       Vars.insert(V);
164 }
165 
166 static void getFieldsAndGlobalVars(const Decl &D,
167                                    llvm::DenseSet<const FieldDecl *> &Fields,
168                                    llvm::DenseSet<const VarDecl *> &Vars) {
169   insertIfGlobal(D, Fields, Vars);
170   if (const auto *Decomp = dyn_cast<DecompositionDecl>(&D))
171     for (const auto *B : Decomp->bindings())
172       if (auto *ME = dyn_cast_or_null<MemberExpr>(B->getBinding()))
173         // FIXME: should we be using `E->getFoundDecl()`?
174         if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
175           Fields.insert(FD);
176 }
177 
178 /// Traverses `S` and inserts into `Vars` any global storage values that are
179 /// declared in or referenced from sub-statements.
180 static void getFieldsAndGlobalVars(const Stmt &S,
181                                    llvm::DenseSet<const FieldDecl *> &Fields,
182                                    llvm::DenseSet<const VarDecl *> &Vars) {
183   for (auto *Child : S.children())
184     if (Child != nullptr)
185       getFieldsAndGlobalVars(*Child, Fields, Vars);
186 
187   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
188     if (DS->isSingleDecl())
189       getFieldsAndGlobalVars(*DS->getSingleDecl(), Fields, Vars);
190     else
191       for (auto *D : DS->getDeclGroup())
192           getFieldsAndGlobalVars(*D, Fields, Vars);
193   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
194     insertIfGlobal(*E->getDecl(), Fields, Vars);
195   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
196     // FIXME: should we be using `E->getFoundDecl()`?
197     const ValueDecl *VD = E->getMemberDecl();
198     insertIfGlobal(*VD, Fields, Vars);
199     if (const auto *FD = dyn_cast<FieldDecl>(VD))
200       Fields.insert(FD);
201   }
202 }
203 
204 // FIXME: Add support for resetting globals after function calls to enable
205 // the implementation of sound analyses.
206 void Environment::initVars(llvm::DenseSet<const VarDecl *> Vars) {
207   for (const VarDecl *D : Vars) {
208     if (getStorageLocation(*D, SkipPast::None) != nullptr)
209       continue;
210     auto &Loc = createStorageLocation(*D);
211     setStorageLocation(*D, Loc);
212     if (auto *Val = createValue(D->getType()))
213       setValue(Loc, *Val);
214   }
215 }
216 
217 Environment::Environment(DataflowAnalysisContext &DACtx)
218     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
219 
220 Environment::Environment(const Environment &Other)
221     : DACtx(Other.DACtx), CallStack(Other.CallStack),
222       ReturnLoc(Other.ReturnLoc), ThisPointeeLoc(Other.ThisPointeeLoc),
223       DeclToLoc(Other.DeclToLoc), ExprToLoc(Other.ExprToLoc),
224       LocToVal(Other.LocToVal), MemberLocToStruct(Other.MemberLocToStruct),
225       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
226 }
227 
228 Environment &Environment::operator=(const Environment &Other) {
229   Environment Copy(Other);
230   *this = std::move(Copy);
231   return *this;
232 }
233 
234 Environment::Environment(DataflowAnalysisContext &DACtx,
235                          const DeclContext &DeclCtx)
236     : Environment(DACtx) {
237   CallStack.push_back(&DeclCtx);
238 
239   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
240     assert(FuncDecl->getBody() != nullptr);
241 
242     llvm::DenseSet<const FieldDecl *> Fields;
243     llvm::DenseSet<const VarDecl *> Vars;
244 
245     // Look for global variable references in the constructor-initializers.
246     if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(&DeclCtx)) {
247       for (const auto *Init : CtorDecl->inits()) {
248         if (const auto *M = Init->getAnyMember())
249           Fields.insert(M);
250         const Expr *E = Init->getInit();
251         assert(E != nullptr);
252         getFieldsAndGlobalVars(*E, Fields, Vars);
253       }
254     }
255     getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
256 
257     // These have to be added before the lines that follow to ensure that
258     // `create*` work correctly for structs.
259     DACtx.addModeledFields(Fields);
260 
261     initVars(Vars);
262 
263     for (const auto *ParamDecl : FuncDecl->parameters()) {
264       assert(ParamDecl != nullptr);
265       auto &ParamLoc = createStorageLocation(*ParamDecl);
266       setStorageLocation(*ParamDecl, ParamLoc);
267       if (Value *ParamVal = createValue(ParamDecl->getType()))
268         setValue(ParamLoc, *ParamVal);
269     }
270 
271     QualType ReturnType = FuncDecl->getReturnType();
272     ReturnLoc = &createStorageLocation(ReturnType);
273   }
274 
275   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
276     auto *Parent = MethodDecl->getParent();
277     assert(Parent != nullptr);
278     if (Parent->isLambda())
279       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
280 
281     // FIXME: Initialize the ThisPointeeLoc of lambdas too.
282     if (MethodDecl && !MethodDecl->isStatic()) {
283       QualType ThisPointeeType = MethodDecl->getThisObjectType();
284       ThisPointeeLoc = &createStorageLocation(ThisPointeeType);
285       if (Value *ThisPointeeVal = createValue(ThisPointeeType))
286         setValue(*ThisPointeeLoc, *ThisPointeeVal);
287     }
288   }
289 }
290 
291 bool Environment::canDescend(unsigned MaxDepth,
292                              const DeclContext *Callee) const {
293   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
294 }
295 
296 Environment Environment::pushCall(const CallExpr *Call) const {
297   Environment Env(*this);
298 
299   // FIXME: Support references here.
300   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
301 
302   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
303     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
304       if (!isa<CXXThisExpr>(Arg))
305         Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
306       // Otherwise (when the argument is `this`), retain the current
307       // environment's `ThisPointeeLoc`.
308     }
309   }
310 
311   Env.pushCallInternal(Call->getDirectCallee(),
312                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
313 
314   return Env;
315 }
316 
317 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
318   Environment Env(*this);
319 
320   // FIXME: Support references here.
321   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
322 
323   Env.ThisPointeeLoc = Env.ReturnLoc;
324 
325   Env.pushCallInternal(Call->getConstructor(),
326                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
327 
328   return Env;
329 }
330 
331 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
332                                    ArrayRef<const Expr *> Args) {
333   CallStack.push_back(FuncDecl);
334 
335   // FIXME: Share this code with the constructor, rather than duplicating it.
336   llvm::DenseSet<const FieldDecl *> Fields;
337   llvm::DenseSet<const VarDecl *> Vars;
338   // Look for global variable references in the constructor-initializers.
339   if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FuncDecl)) {
340     for (const auto *Init : CtorDecl->inits()) {
341       if (const auto *M = Init->getAnyMember())
342         Fields.insert(M);
343       const Expr *E = Init->getInit();
344       assert(E != nullptr);
345       getFieldsAndGlobalVars(*E, Fields, Vars);
346     }
347   }
348   getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
349 
350   // These have to be added before the lines that follow to ensure that
351   // `create*` work correctly for structs.
352   DACtx->addModeledFields(Fields);
353 
354   initVars(Vars);
355 
356   const auto *ParamIt = FuncDecl->param_begin();
357 
358   // FIXME: Parameters don't always map to arguments 1:1; examples include
359   // overloaded operators implemented as member functions, and parameter packs.
360   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
361     assert(ParamIt != FuncDecl->param_end());
362 
363     const Expr *Arg = Args[ArgIndex];
364     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
365     if (ArgLoc == nullptr)
366       continue;
367 
368     const VarDecl *Param = *ParamIt;
369     auto &Loc = createStorageLocation(*Param);
370     setStorageLocation(*Param, Loc);
371 
372     QualType ParamType = Param->getType();
373     if (ParamType->isReferenceType()) {
374       auto &Val = takeOwnership(std::make_unique<ReferenceValue>(*ArgLoc));
375       setValue(Loc, Val);
376     } else if (auto *ArgVal = getValue(*ArgLoc)) {
377       setValue(Loc, *ArgVal);
378     } else if (Value *Val = createValue(ParamType)) {
379       setValue(Loc, *Val);
380     }
381   }
382 }
383 
384 void Environment::popCall(const Environment &CalleeEnv) {
385   // We ignore `DACtx` because it's already the same in both. We don't want the
386   // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back
387   // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze the
388   // same callee in a different context, and `setStorageLocation` requires there
389   // to not already be a storage location assigned. Conceptually, these maps
390   // capture information from the local scope, so when popping that scope, we do
391   // not propagate the maps.
392   this->LocToVal = std::move(CalleeEnv.LocToVal);
393   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
394   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
395 }
396 
397 bool Environment::equivalentTo(const Environment &Other,
398                                Environment::ValueModel &Model) const {
399   assert(DACtx == Other.DACtx);
400 
401   if (ReturnLoc != Other.ReturnLoc)
402     return false;
403 
404   if (ThisPointeeLoc != Other.ThisPointeeLoc)
405     return false;
406 
407   if (DeclToLoc != Other.DeclToLoc)
408     return false;
409 
410   if (ExprToLoc != Other.ExprToLoc)
411     return false;
412 
413   // Compare the contents for the intersection of their domains.
414   for (auto &Entry : LocToVal) {
415     const StorageLocation *Loc = Entry.first;
416     assert(Loc != nullptr);
417 
418     Value *Val = Entry.second;
419     assert(Val != nullptr);
420 
421     auto It = Other.LocToVal.find(Loc);
422     if (It == Other.LocToVal.end())
423       continue;
424     assert(It->second != nullptr);
425 
426     if (!areEquivalentValues(*Val, *It->second) &&
427         !compareDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
428                                Model))
429       return false;
430   }
431 
432   return true;
433 }
434 
435 LatticeJoinEffect Environment::widen(const Environment &PrevEnv,
436                                      Environment::ValueModel &Model) {
437   assert(DACtx == PrevEnv.DACtx);
438   assert(ReturnLoc == PrevEnv.ReturnLoc);
439   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
440   assert(CallStack == PrevEnv.CallStack);
441 
442   auto Effect = LatticeJoinEffect::Unchanged;
443 
444   // By the API, `PrevEnv` is a previous version of the environment for the same
445   // block, so we have some guarantees about its shape. In particular, it will
446   // be the result of a join or widen operation on previous values for this
447   // block. For `DeclToLoc` and `ExprToLoc`, join guarantees that these maps are
448   // subsets of the maps in `PrevEnv`. So, as long as we maintain this property
449   // here, we don't need change their current values to widen.
450   //
451   // FIXME: `MemberLocToStruct` does not share the above property, because
452   // `join` can cause the map size to increase (when we add fresh data in places
453   // of conflict). Once this issue with join is resolved, re-enable the
454   // assertion below or replace with something that captures the desired
455   // invariant.
456   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
457   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
458   // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size());
459 
460   llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal;
461   for (auto &Entry : LocToVal) {
462     const StorageLocation *Loc = Entry.first;
463     assert(Loc != nullptr);
464 
465     Value *Val = Entry.second;
466     assert(Val != nullptr);
467 
468     auto PrevIt = PrevEnv.LocToVal.find(Loc);
469     if (PrevIt == PrevEnv.LocToVal.end())
470       continue;
471     assert(PrevIt->second != nullptr);
472 
473     if (areEquivalentValues(*Val, *PrevIt->second)) {
474       WidenedLocToVal.insert({Loc, Val});
475       continue;
476     }
477 
478     Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second,
479                                             PrevEnv, *Val, *this, Model);
480     WidenedLocToVal.insert({Loc, &WidenedVal});
481     if (&WidenedVal != PrevIt->second)
482       Effect = LatticeJoinEffect::Changed;
483   }
484   LocToVal = std::move(WidenedLocToVal);
485   // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we
486   // have a systematic way of soundly comparing this map.
487   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
488       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
489       LocToVal.size() != PrevEnv.LocToVal.size() ||
490       MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size())
491     Effect = LatticeJoinEffect::Changed;
492 
493   return Effect;
494 }
495 
496 LatticeJoinEffect Environment::join(const Environment &Other,
497                                     Environment::ValueModel &Model) {
498   assert(DACtx == Other.DACtx);
499   assert(ReturnLoc == Other.ReturnLoc);
500   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
501   assert(CallStack == Other.CallStack);
502 
503   auto Effect = LatticeJoinEffect::Unchanged;
504 
505   Environment JoinedEnv(*DACtx);
506 
507   JoinedEnv.CallStack = CallStack;
508   JoinedEnv.ReturnLoc = ReturnLoc;
509   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
510 
511   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
512   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
513     Effect = LatticeJoinEffect::Changed;
514 
515   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
516   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
517     Effect = LatticeJoinEffect::Changed;
518 
519   JoinedEnv.MemberLocToStruct =
520       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
521   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
522     Effect = LatticeJoinEffect::Changed;
523 
524   // FIXME: set `Effect` as needed.
525   // FIXME: update join to detect backedges and simplify the flow condition
526   // accordingly.
527   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
528       *FlowConditionToken, *Other.FlowConditionToken);
529 
530   for (auto &Entry : LocToVal) {
531     const StorageLocation *Loc = Entry.first;
532     assert(Loc != nullptr);
533 
534     Value *Val = Entry.second;
535     assert(Val != nullptr);
536 
537     auto It = Other.LocToVal.find(Loc);
538     if (It == Other.LocToVal.end())
539       continue;
540     assert(It->second != nullptr);
541 
542     if (areEquivalentValues(*Val, *It->second)) {
543       JoinedEnv.LocToVal.insert({Loc, Val});
544       continue;
545     }
546 
547     if (Value *MergedVal =
548             mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
549                                 JoinedEnv, Model)) {
550       JoinedEnv.LocToVal.insert({Loc, MergedVal});
551       Effect = LatticeJoinEffect::Changed;
552     }
553   }
554   if (LocToVal.size() != JoinedEnv.LocToVal.size())
555     Effect = LatticeJoinEffect::Changed;
556 
557   *this = std::move(JoinedEnv);
558 
559   return Effect;
560 }
561 
562 StorageLocation &Environment::createStorageLocation(QualType Type) {
563   return DACtx->createStorageLocation(Type);
564 }
565 
566 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
567   // Evaluated declarations are always assigned the same storage locations to
568   // ensure that the environment stabilizes across loop iterations. Storage
569   // locations for evaluated declarations are stored in the analysis context.
570   return DACtx->getStableStorageLocation(D);
571 }
572 
573 StorageLocation &Environment::createStorageLocation(const Expr &E) {
574   // Evaluated expressions are always assigned the same storage locations to
575   // ensure that the environment stabilizes across loop iterations. Storage
576   // locations for evaluated expressions are stored in the analysis context.
577   return DACtx->getStableStorageLocation(E);
578 }
579 
580 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
581   assert(DeclToLoc.find(&D) == DeclToLoc.end());
582   DeclToLoc[&D] = &Loc;
583 }
584 
585 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
586                                                  SkipPast SP) const {
587   auto It = DeclToLoc.find(&D);
588   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
589 }
590 
591 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
592   const Expr &CanonE = ignoreCFGOmittedNodes(E);
593   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
594   ExprToLoc[&CanonE] = &Loc;
595 }
596 
597 StorageLocation *Environment::getStorageLocation(const Expr &E,
598                                                  SkipPast SP) const {
599   // FIXME: Add a test with parens.
600   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
601   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
602 }
603 
604 StorageLocation *Environment::getThisPointeeStorageLocation() const {
605   return ThisPointeeLoc;
606 }
607 
608 StorageLocation *Environment::getReturnStorageLocation() const {
609   return ReturnLoc;
610 }
611 
612 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
613   return DACtx->getOrCreateNullPointerValue(PointeeType);
614 }
615 
616 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
617   LocToVal[&Loc] = &Val;
618 
619   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
620     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
621 
622     const QualType Type = AggregateLoc.getType();
623     assert(Type->isStructureOrClassType() || Type->isUnionType());
624 
625     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
626       assert(Field != nullptr);
627       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
628       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
629       if (auto *FieldVal = StructVal->getChild(*Field))
630         setValue(FieldLoc, *FieldVal);
631     }
632   }
633 
634   auto It = MemberLocToStruct.find(&Loc);
635   if (It != MemberLocToStruct.end()) {
636     // `Loc` is the location of a struct member so we need to also update the
637     // value of the member in the corresponding `StructValue`.
638 
639     assert(It->second.first != nullptr);
640     StructValue &StructVal = *It->second.first;
641 
642     assert(It->second.second != nullptr);
643     const ValueDecl &Member = *It->second.second;
644 
645     StructVal.setChild(Member, Val);
646   }
647 }
648 
649 Value *Environment::getValue(const StorageLocation &Loc) const {
650   auto It = LocToVal.find(&Loc);
651   return It == LocToVal.end() ? nullptr : It->second;
652 }
653 
654 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
655   auto *Loc = getStorageLocation(D, SP);
656   if (Loc == nullptr)
657     return nullptr;
658   return getValue(*Loc);
659 }
660 
661 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
662   auto *Loc = getStorageLocation(E, SP);
663   if (Loc == nullptr)
664     return nullptr;
665   return getValue(*Loc);
666 }
667 
668 Value *Environment::createValue(QualType Type) {
669   llvm::DenseSet<QualType> Visited;
670   int CreatedValuesCount = 0;
671   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
672                                                 CreatedValuesCount);
673   if (CreatedValuesCount > MaxCompositeValueSize) {
674     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
675                  << '\n';
676   }
677   return Val;
678 }
679 
680 Value *Environment::createValueUnlessSelfReferential(
681     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
682     int &CreatedValuesCount) {
683   assert(!Type.isNull());
684 
685   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
686   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
687       Depth > MaxCompositeValueDepth)
688     return nullptr;
689 
690   if (Type->isBooleanType()) {
691     CreatedValuesCount++;
692     return &makeAtomicBoolValue();
693   }
694 
695   if (Type->isIntegerType()) {
696     // FIXME: consider instead `return nullptr`, given that we do nothing useful
697     // with integers, and so distinguishing them serves no purpose, but could
698     // prevent convergence.
699     CreatedValuesCount++;
700     return &takeOwnership(std::make_unique<IntegerValue>());
701   }
702 
703   if (Type->isReferenceType()) {
704     CreatedValuesCount++;
705     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
706     auto &PointeeLoc = createStorageLocation(PointeeType);
707 
708     if (Visited.insert(PointeeType.getCanonicalType()).second) {
709       Value *PointeeVal = createValueUnlessSelfReferential(
710           PointeeType, Visited, Depth, CreatedValuesCount);
711       Visited.erase(PointeeType.getCanonicalType());
712 
713       if (PointeeVal != nullptr)
714         setValue(PointeeLoc, *PointeeVal);
715     }
716 
717     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
718   }
719 
720   if (Type->isPointerType()) {
721     CreatedValuesCount++;
722     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
723     auto &PointeeLoc = createStorageLocation(PointeeType);
724 
725     if (Visited.insert(PointeeType.getCanonicalType()).second) {
726       Value *PointeeVal = createValueUnlessSelfReferential(
727           PointeeType, Visited, Depth, CreatedValuesCount);
728       Visited.erase(PointeeType.getCanonicalType());
729 
730       if (PointeeVal != nullptr)
731         setValue(PointeeLoc, *PointeeVal);
732     }
733 
734     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
735   }
736 
737   if (Type->isStructureOrClassType() || Type->isUnionType()) {
738     CreatedValuesCount++;
739     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
740     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
741       assert(Field != nullptr);
742 
743       QualType FieldType = Field->getType();
744       if (Visited.contains(FieldType.getCanonicalType()))
745         continue;
746 
747       Visited.insert(FieldType.getCanonicalType());
748       if (auto *FieldValue = createValueUnlessSelfReferential(
749               FieldType, Visited, Depth + 1, CreatedValuesCount))
750         FieldValues.insert({Field, FieldValue});
751       Visited.erase(FieldType.getCanonicalType());
752     }
753 
754     return &takeOwnership(
755         std::make_unique<StructValue>(std::move(FieldValues)));
756   }
757 
758   return nullptr;
759 }
760 
761 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
762   switch (SP) {
763   case SkipPast::None:
764     return Loc;
765   case SkipPast::Reference:
766     // References cannot be chained so we only need to skip past one level of
767     // indirection.
768     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
769       return Val->getReferentLoc();
770     return Loc;
771   case SkipPast::ReferenceThenPointer:
772     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
773     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
774       return Val->getPointeeLoc();
775     return LocPastRef;
776   }
777   llvm_unreachable("bad SkipPast kind");
778 }
779 
780 const StorageLocation &Environment::skip(const StorageLocation &Loc,
781                                          SkipPast SP) const {
782   return skip(*const_cast<StorageLocation *>(&Loc), SP);
783 }
784 
785 void Environment::addToFlowCondition(BoolValue &Val) {
786   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
787 }
788 
789 bool Environment::flowConditionImplies(BoolValue &Val) const {
790   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
791 }
792 
793 void Environment::dump(raw_ostream &OS) const {
794   // FIXME: add printing for remaining fields and allow caller to decide what
795   // fields are printed.
796   OS << "DeclToLoc:\n";
797   for (auto [D, L] : DeclToLoc)
798     OS << "  [" << D->getName() << ", " << L << "]\n";
799 
800   OS << "ExprToLoc:\n";
801   for (auto [E, L] : ExprToLoc)
802     OS << "  [" << E << ", " << L << "]\n";
803 
804   OS << "LocToVal:\n";
805   for (auto [L, V] : LocToVal) {
806     OS << "  [" << L << ", " << V << ": " << *V << "]\n";
807   }
808 
809   OS << "FlowConditionToken:\n";
810   DACtx->dumpFlowCondition(*FlowConditionToken);
811 }
812 
813 void Environment::dump() const {
814   dump(llvm::dbgs());
815 }
816 
817 } // namespace dataflow
818 } // namespace clang
819