xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision d2e4aaf6ac3bc7c72a81f050512afa17a9ceb54b)
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 (auto *Expr1 = dyn_cast<BoolValue>(&Val1)) {
97     auto *Expr2 = cast<BoolValue>(&Val2);
98     auto &MergedVal = MergedEnv.makeAtomicBoolValue();
99     MergedEnv.addToFlowCondition(MergedEnv.makeOr(
100         MergedEnv.makeAnd(Env1.getFlowConditionToken(),
101                           MergedEnv.makeIff(MergedVal, *Expr1)),
102         MergedEnv.makeAnd(Env2.getFlowConditionToken(),
103                           MergedEnv.makeIff(MergedVal, *Expr2))));
104     return &MergedVal;
105   }
106 
107   // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge`
108   // returns false to avoid storing unneeded values in `DACtx`.
109   if (Value *MergedVal = MergedEnv.createValue(Type))
110     if (Model.merge(Type, Val1, Env1, Val2, Env2, *MergedVal, MergedEnv))
111       return MergedVal;
112 
113   return nullptr;
114 }
115 
116 // When widening does not change `Current`, return value will equal `&Prev`.
117 static Value &widenDistinctValues(QualType Type, Value &Prev,
118                                   const Environment &PrevEnv, Value &Current,
119                                   Environment &CurrentEnv,
120                                   Environment::ValueModel &Model) {
121   // Boolean-model widening.
122   if (isa<BoolValue>(&Prev)) {
123     assert(isa<BoolValue>(Current));
124     // Widen to Top, because we know they are different values. If previous was
125     // already Top, re-use that to (implicitly) indicate that no change occured.
126     if (isa<TopBoolValue>(Prev))
127       return Prev;
128     return CurrentEnv.makeTopBoolValue();
129   }
130 
131   // FIXME: Add other built-in model widening.
132 
133   // Custom-model widening.
134   if (auto *W = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv))
135     return *W;
136 
137   // Default of widening is a no-op: leave the current value unchanged.
138   return Current;
139 }
140 
141 /// Initializes a global storage value.
142 static void initGlobalVar(const VarDecl &D, Environment &Env) {
143   if (!D.hasGlobalStorage() ||
144       Env.getStorageLocation(D, SkipPast::None) != nullptr)
145     return;
146 
147   auto &Loc = Env.createStorageLocation(D);
148   Env.setStorageLocation(D, Loc);
149   if (auto *Val = Env.createValue(D.getType()))
150     Env.setValue(Loc, *Val);
151 }
152 
153 /// Initializes a global storage value.
154 static void initGlobalVar(const Decl &D, Environment &Env) {
155   if (auto *V = dyn_cast<VarDecl>(&D))
156     initGlobalVar(*V, Env);
157 }
158 
159 /// Initializes global storage values that are declared or referenced from
160 /// sub-statements of `S`.
161 // FIXME: Add support for resetting globals after function calls to enable
162 // the implementation of sound analyses.
163 static void initGlobalVars(const Stmt &S, Environment &Env) {
164   for (auto *Child : S.children()) {
165     if (Child != nullptr)
166       initGlobalVars(*Child, Env);
167   }
168 
169   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
170     if (DS->isSingleDecl()) {
171       initGlobalVar(*DS->getSingleDecl(), Env);
172     } else {
173       for (auto *D : DS->getDeclGroup())
174         initGlobalVar(*D, Env);
175     }
176   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
177     initGlobalVar(*E->getDecl(), Env);
178   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
179     initGlobalVar(*E->getMemberDecl(), Env);
180   }
181 }
182 
183 Environment::Environment(DataflowAnalysisContext &DACtx)
184     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
185 
186 Environment::Environment(const Environment &Other)
187     : DACtx(Other.DACtx), CallStack(Other.CallStack),
188       ReturnLoc(Other.ReturnLoc), ThisPointeeLoc(Other.ThisPointeeLoc),
189       DeclToLoc(Other.DeclToLoc), ExprToLoc(Other.ExprToLoc),
190       LocToVal(Other.LocToVal), MemberLocToStruct(Other.MemberLocToStruct),
191       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
192 }
193 
194 Environment &Environment::operator=(const Environment &Other) {
195   Environment Copy(Other);
196   *this = std::move(Copy);
197   return *this;
198 }
199 
200 Environment::Environment(DataflowAnalysisContext &DACtx,
201                          const DeclContext &DeclCtx)
202     : Environment(DACtx) {
203   CallStack.push_back(&DeclCtx);
204 
205   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
206     assert(FuncDecl->getBody() != nullptr);
207     initGlobalVars(*FuncDecl->getBody(), *this);
208     for (const auto *ParamDecl : FuncDecl->parameters()) {
209       assert(ParamDecl != nullptr);
210       auto &ParamLoc = createStorageLocation(*ParamDecl);
211       setStorageLocation(*ParamDecl, ParamLoc);
212       if (Value *ParamVal = createValue(ParamDecl->getType()))
213         setValue(ParamLoc, *ParamVal);
214     }
215 
216     QualType ReturnType = FuncDecl->getReturnType();
217     ReturnLoc = &createStorageLocation(ReturnType);
218   }
219 
220   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
221     auto *Parent = MethodDecl->getParent();
222     assert(Parent != nullptr);
223     if (Parent->isLambda())
224       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
225 
226     if (MethodDecl && !MethodDecl->isStatic()) {
227       QualType ThisPointeeType = MethodDecl->getThisObjectType();
228       // FIXME: Add support for union types.
229       if (!ThisPointeeType->isUnionType()) {
230         ThisPointeeLoc = &createStorageLocation(ThisPointeeType);
231         if (Value *ThisPointeeVal = createValue(ThisPointeeType))
232           setValue(*ThisPointeeLoc, *ThisPointeeVal);
233       }
234     }
235   }
236 }
237 
238 bool Environment::canDescend(unsigned MaxDepth,
239                              const DeclContext *Callee) const {
240   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
241 }
242 
243 Environment Environment::pushCall(const CallExpr *Call) const {
244   Environment Env(*this);
245 
246   // FIXME: Support references here.
247   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
248 
249   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
250     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
251       if (!isa<CXXThisExpr>(Arg))
252         Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
253       // Otherwise (when the argument is `this`), retain the current
254       // environment's `ThisPointeeLoc`.
255     }
256   }
257 
258   Env.pushCallInternal(Call->getDirectCallee(),
259                        llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs()));
260 
261   return Env;
262 }
263 
264 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
265   Environment Env(*this);
266 
267   // FIXME: Support references here.
268   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
269 
270   Env.ThisPointeeLoc = Env.ReturnLoc;
271 
272   Env.pushCallInternal(Call->getConstructor(),
273                        llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs()));
274 
275   return Env;
276 }
277 
278 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
279                                    ArrayRef<const Expr *> Args) {
280   CallStack.push_back(FuncDecl);
281 
282   // FIXME: In order to allow the callee to reference globals, we probably need
283   // to call `initGlobalVars` here in some way.
284 
285   auto ParamIt = FuncDecl->param_begin();
286 
287   // FIXME: Parameters don't always map to arguments 1:1; examples include
288   // overloaded operators implemented as member functions, and parameter packs.
289   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
290     assert(ParamIt != FuncDecl->param_end());
291 
292     const Expr *Arg = Args[ArgIndex];
293     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
294     if (ArgLoc == nullptr)
295       continue;
296 
297     const VarDecl *Param = *ParamIt;
298     auto &Loc = createStorageLocation(*Param);
299     setStorageLocation(*Param, Loc);
300 
301     QualType ParamType = Param->getType();
302     if (ParamType->isReferenceType()) {
303       auto &Val = takeOwnership(std::make_unique<ReferenceValue>(*ArgLoc));
304       setValue(Loc, Val);
305     } else if (auto *ArgVal = getValue(*ArgLoc)) {
306       setValue(Loc, *ArgVal);
307     } else if (Value *Val = createValue(ParamType)) {
308       setValue(Loc, *Val);
309     }
310   }
311 }
312 
313 void Environment::popCall(const Environment &CalleeEnv) {
314   // We ignore `DACtx` because it's already the same in both. We don't want the
315   // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back
316   // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze the
317   // same callee in a different context, and `setStorageLocation` requires there
318   // to not already be a storage location assigned. Conceptually, these maps
319   // capture information from the local scope, so when popping that scope, we do
320   // not propagate the maps.
321   this->LocToVal = std::move(CalleeEnv.LocToVal);
322   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
323   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
324 }
325 
326 bool Environment::equivalentTo(const Environment &Other,
327                                Environment::ValueModel &Model) const {
328   assert(DACtx == Other.DACtx);
329 
330   if (ReturnLoc != Other.ReturnLoc)
331     return false;
332 
333   if (ThisPointeeLoc != Other.ThisPointeeLoc)
334     return false;
335 
336   if (DeclToLoc != Other.DeclToLoc)
337     return false;
338 
339   if (ExprToLoc != Other.ExprToLoc)
340     return false;
341 
342   // Compare the contents for the intersection of their domains.
343   for (auto &Entry : LocToVal) {
344     const StorageLocation *Loc = Entry.first;
345     assert(Loc != nullptr);
346 
347     Value *Val = Entry.second;
348     assert(Val != nullptr);
349 
350     auto It = Other.LocToVal.find(Loc);
351     if (It == Other.LocToVal.end())
352       continue;
353     assert(It->second != nullptr);
354 
355     if (!areEquivalentValues(*Val, *It->second) &&
356         !compareDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
357                                Model))
358       return false;
359   }
360 
361   return true;
362 }
363 
364 LatticeJoinEffect Environment::widen(const Environment &PrevEnv,
365                                      Environment::ValueModel &Model) {
366   assert(DACtx == PrevEnv.DACtx);
367   assert(ReturnLoc == PrevEnv.ReturnLoc);
368   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
369   assert(CallStack == PrevEnv.CallStack);
370 
371   auto Effect = LatticeJoinEffect::Unchanged;
372 
373   // By the API, `PrevEnv` is a previous version of the environment for the same
374   // block, so we have some guarantees about its shape. In particular, it will
375   // be the result of a join or widen operation on previous values for this
376   // block. For `DeclToLoc` and `ExprToLoc`, join guarantees that these maps are
377   // subsets of the maps in `PrevEnv`. So, as long as we maintain this property
378   // here, we don't need change their current values to widen.
379   //
380   // FIXME: `MemberLocToStruct` does not share the above property, because
381   // `join` can cause the map size to increase (when we add fresh data in places
382   // of conflict). Once this issue with join is resolved, re-enable the
383   // assertion below or replace with something that captures the desired
384   // invariant.
385   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
386   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
387   // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size());
388 
389   llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal;
390   for (auto &Entry : LocToVal) {
391     const StorageLocation *Loc = Entry.first;
392     assert(Loc != nullptr);
393 
394     Value *Val = Entry.second;
395     assert(Val != nullptr);
396 
397     auto PrevIt = PrevEnv.LocToVal.find(Loc);
398     if (PrevIt == PrevEnv.LocToVal.end())
399       continue;
400     assert(PrevIt->second != nullptr);
401 
402     if (areEquivalentValues(*Val, *PrevIt->second)) {
403       WidenedLocToVal.insert({Loc, Val});
404       continue;
405     }
406 
407     Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second,
408                                             PrevEnv, *Val, *this, Model);
409     WidenedLocToVal.insert({Loc, &WidenedVal});
410     if (&WidenedVal != PrevIt->second)
411       Effect = LatticeJoinEffect::Changed;
412   }
413   LocToVal = std::move(WidenedLocToVal);
414   // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we
415   // have a systematic way of soundly comparing this map.
416   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
417       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
418       LocToVal.size() != PrevEnv.LocToVal.size() ||
419       MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size())
420     Effect = LatticeJoinEffect::Changed;
421 
422   return Effect;
423 }
424 
425 LatticeJoinEffect Environment::join(const Environment &Other,
426                                     Environment::ValueModel &Model) {
427   assert(DACtx == Other.DACtx);
428   assert(ReturnLoc == Other.ReturnLoc);
429   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
430   assert(CallStack == Other.CallStack);
431 
432   auto Effect = LatticeJoinEffect::Unchanged;
433 
434   Environment JoinedEnv(*DACtx);
435 
436   JoinedEnv.CallStack = CallStack;
437   JoinedEnv.ReturnLoc = ReturnLoc;
438   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
439 
440   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
441   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
442     Effect = LatticeJoinEffect::Changed;
443 
444   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
445   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
446     Effect = LatticeJoinEffect::Changed;
447 
448   JoinedEnv.MemberLocToStruct =
449       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
450   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
451     Effect = LatticeJoinEffect::Changed;
452 
453   // FIXME: set `Effect` as needed.
454   // FIXME: update join to detect backedges and simplify the flow condition
455   // accordingly.
456   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
457       *FlowConditionToken, *Other.FlowConditionToken);
458 
459   for (auto &Entry : LocToVal) {
460     const StorageLocation *Loc = Entry.first;
461     assert(Loc != nullptr);
462 
463     Value *Val = Entry.second;
464     assert(Val != nullptr);
465 
466     auto It = Other.LocToVal.find(Loc);
467     if (It == Other.LocToVal.end())
468       continue;
469     assert(It->second != nullptr);
470 
471     if (areEquivalentValues(*Val, *It->second)) {
472       JoinedEnv.LocToVal.insert({Loc, Val});
473       continue;
474     }
475 
476     if (Value *MergedVal =
477             mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
478                                 JoinedEnv, Model)) {
479       JoinedEnv.LocToVal.insert({Loc, MergedVal});
480       Effect = LatticeJoinEffect::Changed;
481     }
482   }
483   if (LocToVal.size() != JoinedEnv.LocToVal.size())
484     Effect = LatticeJoinEffect::Changed;
485 
486   *this = std::move(JoinedEnv);
487 
488   return Effect;
489 }
490 
491 StorageLocation &Environment::createStorageLocation(QualType Type) {
492   return DACtx->createStorageLocation(Type);
493 }
494 
495 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
496   // Evaluated declarations are always assigned the same storage locations to
497   // ensure that the environment stabilizes across loop iterations. Storage
498   // locations for evaluated declarations are stored in the analysis context.
499   return DACtx->getStableStorageLocation(D);
500 }
501 
502 StorageLocation &Environment::createStorageLocation(const Expr &E) {
503   // Evaluated expressions are always assigned the same storage locations to
504   // ensure that the environment stabilizes across loop iterations. Storage
505   // locations for evaluated expressions are stored in the analysis context.
506   return DACtx->getStableStorageLocation(E);
507 }
508 
509 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
510   assert(DeclToLoc.find(&D) == DeclToLoc.end());
511   DeclToLoc[&D] = &Loc;
512 }
513 
514 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
515                                                  SkipPast SP) const {
516   auto It = DeclToLoc.find(&D);
517   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
518 }
519 
520 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
521   const Expr &CanonE = ignoreCFGOmittedNodes(E);
522   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
523   ExprToLoc[&CanonE] = &Loc;
524 }
525 
526 StorageLocation *Environment::getStorageLocation(const Expr &E,
527                                                  SkipPast SP) const {
528   // FIXME: Add a test with parens.
529   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
530   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
531 }
532 
533 StorageLocation *Environment::getThisPointeeStorageLocation() const {
534   return ThisPointeeLoc;
535 }
536 
537 StorageLocation *Environment::getReturnStorageLocation() const {
538   return ReturnLoc;
539 }
540 
541 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
542   return DACtx->getOrCreateNullPointerValue(PointeeType);
543 }
544 
545 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
546   LocToVal[&Loc] = &Val;
547 
548   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
549     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
550 
551     const QualType Type = AggregateLoc.getType();
552     assert(Type->isStructureOrClassType());
553 
554     for (const FieldDecl *Field : getObjectFields(Type)) {
555       assert(Field != nullptr);
556       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
557       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
558       if (auto *FieldVal = StructVal->getChild(*Field))
559         setValue(FieldLoc, *FieldVal);
560     }
561   }
562 
563   auto It = MemberLocToStruct.find(&Loc);
564   if (It != MemberLocToStruct.end()) {
565     // `Loc` is the location of a struct member so we need to also update the
566     // value of the member in the corresponding `StructValue`.
567 
568     assert(It->second.first != nullptr);
569     StructValue &StructVal = *It->second.first;
570 
571     assert(It->second.second != nullptr);
572     const ValueDecl &Member = *It->second.second;
573 
574     StructVal.setChild(Member, Val);
575   }
576 }
577 
578 Value *Environment::getValue(const StorageLocation &Loc) const {
579   auto It = LocToVal.find(&Loc);
580   return It == LocToVal.end() ? nullptr : It->second;
581 }
582 
583 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
584   auto *Loc = getStorageLocation(D, SP);
585   if (Loc == nullptr)
586     return nullptr;
587   return getValue(*Loc);
588 }
589 
590 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
591   auto *Loc = getStorageLocation(E, SP);
592   if (Loc == nullptr)
593     return nullptr;
594   return getValue(*Loc);
595 }
596 
597 Value *Environment::createValue(QualType Type) {
598   llvm::DenseSet<QualType> Visited;
599   int CreatedValuesCount = 0;
600   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
601                                                 CreatedValuesCount);
602   if (CreatedValuesCount > MaxCompositeValueSize) {
603     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
604                  << '\n';
605   }
606   return Val;
607 }
608 
609 Value *Environment::createValueUnlessSelfReferential(
610     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
611     int &CreatedValuesCount) {
612   assert(!Type.isNull());
613 
614   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
615   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
616       Depth > MaxCompositeValueDepth)
617     return nullptr;
618 
619   if (Type->isBooleanType()) {
620     CreatedValuesCount++;
621     return &makeAtomicBoolValue();
622   }
623 
624   if (Type->isIntegerType()) {
625     // FIXME: consider instead `return nullptr`, given that we do nothing useful
626     // with integers, and so distinguishing them serves no purpose, but could
627     // prevent convergence.
628     CreatedValuesCount++;
629     return &takeOwnership(std::make_unique<IntegerValue>());
630   }
631 
632   if (Type->isReferenceType()) {
633     CreatedValuesCount++;
634     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
635     auto &PointeeLoc = createStorageLocation(PointeeType);
636 
637     if (Visited.insert(PointeeType.getCanonicalType()).second) {
638       Value *PointeeVal = createValueUnlessSelfReferential(
639           PointeeType, Visited, Depth, CreatedValuesCount);
640       Visited.erase(PointeeType.getCanonicalType());
641 
642       if (PointeeVal != nullptr)
643         setValue(PointeeLoc, *PointeeVal);
644     }
645 
646     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
647   }
648 
649   if (Type->isPointerType()) {
650     CreatedValuesCount++;
651     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
652     auto &PointeeLoc = createStorageLocation(PointeeType);
653 
654     if (Visited.insert(PointeeType.getCanonicalType()).second) {
655       Value *PointeeVal = createValueUnlessSelfReferential(
656           PointeeType, Visited, Depth, CreatedValuesCount);
657       Visited.erase(PointeeType.getCanonicalType());
658 
659       if (PointeeVal != nullptr)
660         setValue(PointeeLoc, *PointeeVal);
661     }
662 
663     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
664   }
665 
666   if (Type->isStructureOrClassType()) {
667     CreatedValuesCount++;
668     // FIXME: Initialize only fields that are accessed in the context that is
669     // being analyzed.
670     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
671     for (const FieldDecl *Field : getObjectFields(Type)) {
672       assert(Field != nullptr);
673 
674       QualType FieldType = Field->getType();
675       if (Visited.contains(FieldType.getCanonicalType()))
676         continue;
677 
678       Visited.insert(FieldType.getCanonicalType());
679       if (auto *FieldValue = createValueUnlessSelfReferential(
680               FieldType, Visited, Depth + 1, CreatedValuesCount))
681         FieldValues.insert({Field, FieldValue});
682       Visited.erase(FieldType.getCanonicalType());
683     }
684 
685     return &takeOwnership(
686         std::make_unique<StructValue>(std::move(FieldValues)));
687   }
688 
689   return nullptr;
690 }
691 
692 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
693   switch (SP) {
694   case SkipPast::None:
695     return Loc;
696   case SkipPast::Reference:
697     // References cannot be chained so we only need to skip past one level of
698     // indirection.
699     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
700       return Val->getReferentLoc();
701     return Loc;
702   case SkipPast::ReferenceThenPointer:
703     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
704     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
705       return Val->getPointeeLoc();
706     return LocPastRef;
707   }
708   llvm_unreachable("bad SkipPast kind");
709 }
710 
711 const StorageLocation &Environment::skip(const StorageLocation &Loc,
712                                          SkipPast SP) const {
713   return skip(*const_cast<StorageLocation *>(&Loc), SP);
714 }
715 
716 void Environment::addToFlowCondition(BoolValue &Val) {
717   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
718 }
719 
720 bool Environment::flowConditionImplies(BoolValue &Val) const {
721   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
722 }
723 
724 void Environment::dump() const {
725   DACtx->dumpFlowCondition(*FlowConditionToken);
726 }
727 
728 } // namespace dataflow
729 } // namespace clang
730