xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision d9e717338f8042664177250315364094262c7073)
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 VarDecl *> &Vars) {
160   if (auto *V = dyn_cast<VarDecl>(&D))
161     if (V->hasGlobalStorage())
162       Vars.insert(V);
163 }
164 
165 static void insertIfFunction(const Decl &D,
166                              llvm::DenseSet<const FunctionDecl *> &Funcs) {
167   if (auto *FD = dyn_cast<FunctionDecl>(&D))
168     Funcs.insert(FD);
169 }
170 
171 static void
172 getFieldsGlobalsAndFuncs(const Decl &D,
173                          llvm::DenseSet<const FieldDecl *> &Fields,
174                          llvm::DenseSet<const VarDecl *> &Vars,
175                          llvm::DenseSet<const FunctionDecl *> &Funcs) {
176   insertIfGlobal(D, Vars);
177   insertIfFunction(D, Funcs);
178   if (const auto *Decomp = dyn_cast<DecompositionDecl>(&D))
179     for (const auto *B : Decomp->bindings())
180       if (auto *ME = dyn_cast_or_null<MemberExpr>(B->getBinding()))
181         // FIXME: should we be using `E->getFoundDecl()`?
182         if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
183           Fields.insert(FD);
184 }
185 
186 /// Traverses `S` and inserts into `Fields`, `Vars` and `Funcs` any fields,
187 /// global variables and functions that are declared in or referenced from
188 /// sub-statements.
189 static void
190 getFieldsGlobalsAndFuncs(const Stmt &S,
191                          llvm::DenseSet<const FieldDecl *> &Fields,
192                          llvm::DenseSet<const VarDecl *> &Vars,
193                          llvm::DenseSet<const FunctionDecl *> &Funcs) {
194   for (auto *Child : S.children())
195     if (Child != nullptr)
196       getFieldsGlobalsAndFuncs(*Child, Fields, Vars, Funcs);
197 
198   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
199     if (DS->isSingleDecl())
200       getFieldsGlobalsAndFuncs(*DS->getSingleDecl(), Fields, Vars, Funcs);
201     else
202       for (auto *D : DS->getDeclGroup())
203         getFieldsGlobalsAndFuncs(*D, Fields, Vars, Funcs);
204   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
205     insertIfGlobal(*E->getDecl(), Vars);
206     insertIfFunction(*E->getDecl(), Funcs);
207   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
208     // FIXME: should we be using `E->getFoundDecl()`?
209     const ValueDecl *VD = E->getMemberDecl();
210     insertIfGlobal(*VD, Vars);
211     insertIfFunction(*VD, Funcs);
212     if (const auto *FD = dyn_cast<FieldDecl>(VD))
213       Fields.insert(FD);
214   }
215 }
216 
217 // FIXME: Add support for resetting globals after function calls to enable
218 // the implementation of sound analyses.
219 void Environment::initFieldsGlobalsAndFuncs(const FunctionDecl *FuncDecl) {
220   assert(FuncDecl->getBody() != nullptr);
221 
222   llvm::DenseSet<const FieldDecl *> Fields;
223   llvm::DenseSet<const VarDecl *> Vars;
224   llvm::DenseSet<const FunctionDecl *> Funcs;
225 
226   // Look for global variable and field references in the
227   // constructor-initializers.
228   if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FuncDecl)) {
229     for (const auto *Init : CtorDecl->inits()) {
230       if (const auto *M = Init->getAnyMember())
231           Fields.insert(M);
232       const Expr *E = Init->getInit();
233       assert(E != nullptr);
234       getFieldsGlobalsAndFuncs(*E, Fields, Vars, Funcs);
235     }
236     // Add all fields mentioned in default member initializers.
237     for (const FieldDecl *F : CtorDecl->getParent()->fields())
238       if (const auto *I = F->getInClassInitializer())
239           getFieldsGlobalsAndFuncs(*I, Fields, Vars, Funcs);
240   }
241   getFieldsGlobalsAndFuncs(*FuncDecl->getBody(), Fields, Vars, Funcs);
242 
243   // These have to be added before the lines that follow to ensure that
244   // `create*` work correctly for structs.
245   DACtx->addModeledFields(Fields);
246 
247   for (const VarDecl *D : Vars) {
248     if (getStorageLocation(*D, SkipPast::None) != nullptr)
249       continue;
250     auto &Loc = createStorageLocation(*D);
251     setStorageLocation(*D, Loc);
252     if (auto *Val = createValue(D->getType()))
253       setValue(Loc, *Val);
254   }
255 
256   for (const FunctionDecl *FD : Funcs) {
257     if (getStorageLocation(*FD, SkipPast::None) != nullptr)
258       continue;
259     auto &Loc = createStorageLocation(FD->getType());
260     setStorageLocation(*FD, Loc);
261   }
262 }
263 
264 Environment::Environment(DataflowAnalysisContext &DACtx)
265     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
266 
267 Environment::Environment(const Environment &Other)
268     : DACtx(Other.DACtx), CallStack(Other.CallStack),
269       ReturnLoc(Other.ReturnLoc), ThisPointeeLoc(Other.ThisPointeeLoc),
270       DeclToLoc(Other.DeclToLoc), ExprToLoc(Other.ExprToLoc),
271       LocToVal(Other.LocToVal), MemberLocToStruct(Other.MemberLocToStruct),
272       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
273 }
274 
275 Environment &Environment::operator=(const Environment &Other) {
276   Environment Copy(Other);
277   *this = std::move(Copy);
278   return *this;
279 }
280 
281 Environment::Environment(DataflowAnalysisContext &DACtx,
282                          const DeclContext &DeclCtx)
283     : Environment(DACtx) {
284   CallStack.push_back(&DeclCtx);
285 
286   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
287     assert(FuncDecl->getBody() != nullptr);
288 
289     initFieldsGlobalsAndFuncs(FuncDecl);
290 
291     for (const auto *ParamDecl : FuncDecl->parameters()) {
292       assert(ParamDecl != nullptr);
293       auto &ParamLoc = createStorageLocation(*ParamDecl);
294       setStorageLocation(*ParamDecl, ParamLoc);
295       if (Value *ParamVal = createValue(ParamDecl->getType()))
296         setValue(ParamLoc, *ParamVal);
297     }
298 
299     QualType ReturnType = FuncDecl->getReturnType();
300     ReturnLoc = &createStorageLocation(ReturnType);
301   }
302 
303   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
304     auto *Parent = MethodDecl->getParent();
305     assert(Parent != nullptr);
306     if (Parent->isLambda())
307       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
308 
309     // FIXME: Initialize the ThisPointeeLoc of lambdas too.
310     if (MethodDecl && !MethodDecl->isStatic()) {
311       QualType ThisPointeeType = MethodDecl->getThisObjectType();
312       ThisPointeeLoc = &createStorageLocation(ThisPointeeType);
313       if (Value *ThisPointeeVal = createValue(ThisPointeeType))
314         setValue(*ThisPointeeLoc, *ThisPointeeVal);
315     }
316   }
317 }
318 
319 bool Environment::canDescend(unsigned MaxDepth,
320                              const DeclContext *Callee) const {
321   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
322 }
323 
324 Environment Environment::pushCall(const CallExpr *Call) const {
325   Environment Env(*this);
326 
327   // FIXME: Support references here.
328   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
329 
330   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
331     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
332       if (!isa<CXXThisExpr>(Arg))
333         Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
334       // Otherwise (when the argument is `this`), retain the current
335       // environment's `ThisPointeeLoc`.
336     }
337   }
338 
339   Env.pushCallInternal(Call->getDirectCallee(),
340                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
341 
342   return Env;
343 }
344 
345 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
346   Environment Env(*this);
347 
348   // FIXME: Support references here.
349   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
350 
351   Env.ThisPointeeLoc = Env.ReturnLoc;
352 
353   Env.pushCallInternal(Call->getConstructor(),
354                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
355 
356   return Env;
357 }
358 
359 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
360                                    ArrayRef<const Expr *> Args) {
361   CallStack.push_back(FuncDecl);
362 
363   initFieldsGlobalsAndFuncs(FuncDecl);
364 
365   const auto *ParamIt = FuncDecl->param_begin();
366 
367   // FIXME: Parameters don't always map to arguments 1:1; examples include
368   // overloaded operators implemented as member functions, and parameter packs.
369   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
370     assert(ParamIt != FuncDecl->param_end());
371 
372     const Expr *Arg = Args[ArgIndex];
373     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
374     if (ArgLoc == nullptr)
375       continue;
376 
377     const VarDecl *Param = *ParamIt;
378     auto &Loc = createStorageLocation(*Param);
379     setStorageLocation(*Param, Loc);
380 
381     QualType ParamType = Param->getType();
382     if (ParamType->isReferenceType()) {
383       auto &Val = create<ReferenceValue>(*ArgLoc);
384       setValue(Loc, Val);
385     } else if (auto *ArgVal = getValue(*ArgLoc)) {
386       setValue(Loc, *ArgVal);
387     } else if (Value *Val = createValue(ParamType)) {
388       setValue(Loc, *Val);
389     }
390   }
391 }
392 
393 void Environment::popCall(const Environment &CalleeEnv) {
394   // We ignore `DACtx` because it's already the same in both. We don't want the
395   // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back
396   // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze the
397   // same callee in a different context, and `setStorageLocation` requires there
398   // to not already be a storage location assigned. Conceptually, these maps
399   // capture information from the local scope, so when popping that scope, we do
400   // not propagate the maps.
401   this->LocToVal = std::move(CalleeEnv.LocToVal);
402   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
403   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
404 }
405 
406 bool Environment::equivalentTo(const Environment &Other,
407                                Environment::ValueModel &Model) const {
408   assert(DACtx == Other.DACtx);
409 
410   if (ReturnLoc != Other.ReturnLoc)
411     return false;
412 
413   if (ThisPointeeLoc != Other.ThisPointeeLoc)
414     return false;
415 
416   if (DeclToLoc != Other.DeclToLoc)
417     return false;
418 
419   if (ExprToLoc != Other.ExprToLoc)
420     return false;
421 
422   // Compare the contents for the intersection of their domains.
423   for (auto &Entry : LocToVal) {
424     const StorageLocation *Loc = Entry.first;
425     assert(Loc != nullptr);
426 
427     Value *Val = Entry.second;
428     assert(Val != nullptr);
429 
430     auto It = Other.LocToVal.find(Loc);
431     if (It == Other.LocToVal.end())
432       continue;
433     assert(It->second != nullptr);
434 
435     if (!areEquivalentValues(*Val, *It->second) &&
436         !compareDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
437                                Model))
438       return false;
439   }
440 
441   return true;
442 }
443 
444 LatticeJoinEffect Environment::widen(const Environment &PrevEnv,
445                                      Environment::ValueModel &Model) {
446   assert(DACtx == PrevEnv.DACtx);
447   assert(ReturnLoc == PrevEnv.ReturnLoc);
448   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
449   assert(CallStack == PrevEnv.CallStack);
450 
451   auto Effect = LatticeJoinEffect::Unchanged;
452 
453   // By the API, `PrevEnv` is a previous version of the environment for the same
454   // block, so we have some guarantees about its shape. In particular, it will
455   // be the result of a join or widen operation on previous values for this
456   // block. For `DeclToLoc` and `ExprToLoc`, join guarantees that these maps are
457   // subsets of the maps in `PrevEnv`. So, as long as we maintain this property
458   // here, we don't need change their current values to widen.
459   //
460   // FIXME: `MemberLocToStruct` does not share the above property, because
461   // `join` can cause the map size to increase (when we add fresh data in places
462   // of conflict). Once this issue with join is resolved, re-enable the
463   // assertion below or replace with something that captures the desired
464   // invariant.
465   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
466   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
467   // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size());
468 
469   llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal;
470   for (auto &Entry : LocToVal) {
471     const StorageLocation *Loc = Entry.first;
472     assert(Loc != nullptr);
473 
474     Value *Val = Entry.second;
475     assert(Val != nullptr);
476 
477     auto PrevIt = PrevEnv.LocToVal.find(Loc);
478     if (PrevIt == PrevEnv.LocToVal.end())
479       continue;
480     assert(PrevIt->second != nullptr);
481 
482     if (areEquivalentValues(*Val, *PrevIt->second)) {
483       WidenedLocToVal.insert({Loc, Val});
484       continue;
485     }
486 
487     Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second,
488                                             PrevEnv, *Val, *this, Model);
489     WidenedLocToVal.insert({Loc, &WidenedVal});
490     if (&WidenedVal != PrevIt->second)
491       Effect = LatticeJoinEffect::Changed;
492   }
493   LocToVal = std::move(WidenedLocToVal);
494   // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we
495   // have a systematic way of soundly comparing this map.
496   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
497       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
498       LocToVal.size() != PrevEnv.LocToVal.size() ||
499       MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size())
500     Effect = LatticeJoinEffect::Changed;
501 
502   return Effect;
503 }
504 
505 LatticeJoinEffect Environment::join(const Environment &Other,
506                                     Environment::ValueModel &Model) {
507   assert(DACtx == Other.DACtx);
508   assert(ReturnLoc == Other.ReturnLoc);
509   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
510   assert(CallStack == Other.CallStack);
511 
512   auto Effect = LatticeJoinEffect::Unchanged;
513 
514   Environment JoinedEnv(*DACtx);
515 
516   JoinedEnv.CallStack = CallStack;
517   JoinedEnv.ReturnLoc = ReturnLoc;
518   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
519 
520   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
521   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
522     Effect = LatticeJoinEffect::Changed;
523 
524   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
525   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
526     Effect = LatticeJoinEffect::Changed;
527 
528   JoinedEnv.MemberLocToStruct =
529       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
530   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
531     Effect = LatticeJoinEffect::Changed;
532 
533   // FIXME: set `Effect` as needed.
534   // FIXME: update join to detect backedges and simplify the flow condition
535   // accordingly.
536   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
537       *FlowConditionToken, *Other.FlowConditionToken);
538 
539   for (auto &Entry : LocToVal) {
540     const StorageLocation *Loc = Entry.first;
541     assert(Loc != nullptr);
542 
543     Value *Val = Entry.second;
544     assert(Val != nullptr);
545 
546     auto It = Other.LocToVal.find(Loc);
547     if (It == Other.LocToVal.end())
548       continue;
549     assert(It->second != nullptr);
550 
551     if (areEquivalentValues(*Val, *It->second)) {
552       JoinedEnv.LocToVal.insert({Loc, Val});
553       continue;
554     }
555 
556     if (Value *MergedVal =
557             mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
558                                 JoinedEnv, Model)) {
559       JoinedEnv.LocToVal.insert({Loc, MergedVal});
560       Effect = LatticeJoinEffect::Changed;
561     }
562   }
563   if (LocToVal.size() != JoinedEnv.LocToVal.size())
564     Effect = LatticeJoinEffect::Changed;
565 
566   *this = std::move(JoinedEnv);
567 
568   return Effect;
569 }
570 
571 StorageLocation &Environment::createStorageLocation(QualType Type) {
572   return DACtx->createStorageLocation(Type);
573 }
574 
575 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
576   // Evaluated declarations are always assigned the same storage locations to
577   // ensure that the environment stabilizes across loop iterations. Storage
578   // locations for evaluated declarations are stored in the analysis context.
579   return DACtx->getStableStorageLocation(D);
580 }
581 
582 StorageLocation &Environment::createStorageLocation(const Expr &E) {
583   // Evaluated expressions are always assigned the same storage locations to
584   // ensure that the environment stabilizes across loop iterations. Storage
585   // locations for evaluated expressions are stored in the analysis context.
586   return DACtx->getStableStorageLocation(E);
587 }
588 
589 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
590   assert(!DeclToLoc.contains(&D));
591   DeclToLoc[&D] = &Loc;
592 }
593 
594 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
595                                                  SkipPast SP) const {
596   auto It = DeclToLoc.find(&D);
597   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
598 }
599 
600 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
601   const Expr &CanonE = ignoreCFGOmittedNodes(E);
602   assert(!ExprToLoc.contains(&CanonE));
603   ExprToLoc[&CanonE] = &Loc;
604 }
605 
606 StorageLocation *Environment::getStorageLocation(const Expr &E,
607                                                  SkipPast SP) const {
608   // FIXME: Add a test with parens.
609   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
610   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
611 }
612 
613 StorageLocation *Environment::getThisPointeeStorageLocation() const {
614   return ThisPointeeLoc;
615 }
616 
617 StorageLocation *Environment::getReturnStorageLocation() const {
618   return ReturnLoc;
619 }
620 
621 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
622   return DACtx->getOrCreateNullPointerValue(PointeeType);
623 }
624 
625 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
626   LocToVal[&Loc] = &Val;
627 
628   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
629     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
630 
631     const QualType Type = AggregateLoc.getType();
632     assert(Type->isRecordType());
633 
634     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
635       assert(Field != nullptr);
636       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
637       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
638       if (auto *FieldVal = StructVal->getChild(*Field))
639         setValue(FieldLoc, *FieldVal);
640     }
641   }
642 
643   auto It = MemberLocToStruct.find(&Loc);
644   if (It != MemberLocToStruct.end()) {
645     // `Loc` is the location of a struct member so we need to also update the
646     // value of the member in the corresponding `StructValue`.
647 
648     assert(It->second.first != nullptr);
649     StructValue &StructVal = *It->second.first;
650 
651     assert(It->second.second != nullptr);
652     const ValueDecl &Member = *It->second.second;
653 
654     StructVal.setChild(Member, Val);
655   }
656 }
657 
658 Value *Environment::getValue(const StorageLocation &Loc) const {
659   auto It = LocToVal.find(&Loc);
660   return It == LocToVal.end() ? nullptr : It->second;
661 }
662 
663 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
664   auto *Loc = getStorageLocation(D, SP);
665   if (Loc == nullptr)
666     return nullptr;
667   return getValue(*Loc);
668 }
669 
670 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
671   auto *Loc = getStorageLocation(E, SP);
672   if (Loc == nullptr)
673     return nullptr;
674   return getValue(*Loc);
675 }
676 
677 Value *Environment::createValue(QualType Type) {
678   llvm::DenseSet<QualType> Visited;
679   int CreatedValuesCount = 0;
680   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
681                                                 CreatedValuesCount);
682   if (CreatedValuesCount > MaxCompositeValueSize) {
683     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
684                  << '\n';
685   }
686   return Val;
687 }
688 
689 Value *Environment::createValueUnlessSelfReferential(
690     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
691     int &CreatedValuesCount) {
692   assert(!Type.isNull());
693 
694   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
695   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
696       Depth > MaxCompositeValueDepth)
697     return nullptr;
698 
699   if (Type->isBooleanType()) {
700     CreatedValuesCount++;
701     return &makeAtomicBoolValue();
702   }
703 
704   if (Type->isIntegerType()) {
705     // FIXME: consider instead `return nullptr`, given that we do nothing useful
706     // with integers, and so distinguishing them serves no purpose, but could
707     // prevent convergence.
708     CreatedValuesCount++;
709     return &create<IntegerValue>();
710   }
711 
712   if (Type->isReferenceType() || Type->isPointerType()) {
713     CreatedValuesCount++;
714     QualType PointeeType = Type->getPointeeType();
715     auto &PointeeLoc = createStorageLocation(PointeeType);
716 
717     if (Visited.insert(PointeeType.getCanonicalType()).second) {
718       Value *PointeeVal = createValueUnlessSelfReferential(
719           PointeeType, Visited, Depth, CreatedValuesCount);
720       Visited.erase(PointeeType.getCanonicalType());
721 
722       if (PointeeVal != nullptr)
723         setValue(PointeeLoc, *PointeeVal);
724     }
725 
726     if (Type->isReferenceType())
727       return &create<ReferenceValue>(PointeeLoc);
728     else
729       return &create<PointerValue>(PointeeLoc);
730   }
731 
732   if (Type->isRecordType()) {
733     CreatedValuesCount++;
734     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
735     for (const FieldDecl *Field : DACtx->getReferencedFields(Type)) {
736       assert(Field != nullptr);
737 
738       QualType FieldType = Field->getType();
739       if (Visited.contains(FieldType.getCanonicalType()))
740         continue;
741 
742       Visited.insert(FieldType.getCanonicalType());
743       if (auto *FieldValue = createValueUnlessSelfReferential(
744               FieldType, Visited, Depth + 1, CreatedValuesCount))
745         FieldValues.insert({Field, FieldValue});
746       Visited.erase(FieldType.getCanonicalType());
747     }
748 
749     return &create<StructValue>(std::move(FieldValues));
750   }
751 
752   return nullptr;
753 }
754 
755 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
756   switch (SP) {
757   case SkipPast::None:
758     return Loc;
759   case SkipPast::Reference:
760     // References cannot be chained so we only need to skip past one level of
761     // indirection.
762     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
763       return Val->getReferentLoc();
764     return Loc;
765   case SkipPast::ReferenceThenPointer:
766     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
767     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
768       return Val->getPointeeLoc();
769     return LocPastRef;
770   }
771   llvm_unreachable("bad SkipPast kind");
772 }
773 
774 const StorageLocation &Environment::skip(const StorageLocation &Loc,
775                                          SkipPast SP) const {
776   return skip(*const_cast<StorageLocation *>(&Loc), SP);
777 }
778 
779 void Environment::addToFlowCondition(BoolValue &Val) {
780   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
781 }
782 
783 bool Environment::flowConditionImplies(BoolValue &Val) const {
784   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
785 }
786 
787 void Environment::dump(raw_ostream &OS) const {
788   // FIXME: add printing for remaining fields and allow caller to decide what
789   // fields are printed.
790   OS << "DeclToLoc:\n";
791   for (auto [D, L] : DeclToLoc)
792     OS << "  [" << D->getName() << ", " << L << "]\n";
793 
794   OS << "ExprToLoc:\n";
795   for (auto [E, L] : ExprToLoc)
796     OS << "  [" << E << ", " << L << "]\n";
797 
798   OS << "LocToVal:\n";
799   for (auto [L, V] : LocToVal) {
800     OS << "  [" << L << ", " << V << ": " << *V << "]\n";
801   }
802 
803   OS << "FlowConditionToken:\n";
804   DACtx->dumpFlowCondition(*FlowConditionToken, OS);
805 }
806 
807 void Environment::dump() const {
808   dump(llvm::dbgs());
809 }
810 
811 } // namespace dataflow
812 } // namespace clang
813