xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision a18cf8d14f5552c13bd1cef112ba5b88a7fc75ff)
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` <= `*this`, meaning `join(PrevEnv, *this) =
374   // *this`. That guarantees that these maps are subsets of the maps in
375   // `PrevEnv`. So, we don't need change their current values to widen (in
376   // contrast to `join`).
377   //
378   // FIXME: The above is violated for `MemberLocToStruct`, because `join` can
379   // cause the map size to increase (when we add fresh data in places of
380   // conflict). Once this issue with join is resolved, re-enable the assertion
381   // below or replace with something that captures the desired invariant.
382   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
383   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
384   // assert(MemberLocToStruct.size() <= PrevEnv.MemberLocToStruct.size());
385 
386   llvm::DenseMap<const StorageLocation *, Value *> WidenedLocToVal;
387   for (auto &Entry : LocToVal) {
388     const StorageLocation *Loc = Entry.first;
389     assert(Loc != nullptr);
390 
391     Value *Val = Entry.second;
392     assert(Val != nullptr);
393 
394     auto PrevIt = PrevEnv.LocToVal.find(Loc);
395     if (PrevIt == PrevEnv.LocToVal.end())
396       continue;
397     assert(PrevIt->second != nullptr);
398 
399     if (areEquivalentValues(*Val, *PrevIt->second)) {
400       WidenedLocToVal.insert({Loc, Val});
401       continue;
402     }
403 
404     Value &WidenedVal = widenDistinctValues(Loc->getType(), *PrevIt->second,
405                                             PrevEnv, *Val, *this, Model);
406     WidenedLocToVal.insert({Loc, &WidenedVal});
407     if (&WidenedVal != PrevIt->second)
408       Effect = LatticeJoinEffect::Changed;
409   }
410   LocToVal = std::move(WidenedLocToVal);
411   // FIXME: update the equivalence calculation for `MemberLocToStruct`, once we
412   // have a systematic way of soundly comparing this map.
413   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
414       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
415       LocToVal.size() != PrevEnv.LocToVal.size() ||
416       MemberLocToStruct.size() != PrevEnv.MemberLocToStruct.size())
417     Effect = LatticeJoinEffect::Changed;
418 
419   return Effect;
420 }
421 
422 LatticeJoinEffect Environment::join(const Environment &Other,
423                                     Environment::ValueModel &Model) {
424   assert(DACtx == Other.DACtx);
425   assert(ReturnLoc == Other.ReturnLoc);
426   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
427   assert(CallStack == Other.CallStack);
428 
429   auto Effect = LatticeJoinEffect::Unchanged;
430 
431   Environment JoinedEnv(*DACtx);
432 
433   JoinedEnv.CallStack = CallStack;
434   JoinedEnv.ReturnLoc = ReturnLoc;
435   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
436 
437   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
438   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
439     Effect = LatticeJoinEffect::Changed;
440 
441   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
442   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
443     Effect = LatticeJoinEffect::Changed;
444 
445   JoinedEnv.MemberLocToStruct =
446       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
447   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
448     Effect = LatticeJoinEffect::Changed;
449 
450   // FIXME: set `Effect` as needed.
451   // FIXME: update join to detect backedges and simplify the flow condition
452   // accordingly.
453   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
454       *FlowConditionToken, *Other.FlowConditionToken);
455 
456   for (auto &Entry : LocToVal) {
457     const StorageLocation *Loc = Entry.first;
458     assert(Loc != nullptr);
459 
460     Value *Val = Entry.second;
461     assert(Val != nullptr);
462 
463     auto It = Other.LocToVal.find(Loc);
464     if (It == Other.LocToVal.end())
465       continue;
466     assert(It->second != nullptr);
467 
468     if (areEquivalentValues(*Val, *It->second)) {
469       JoinedEnv.LocToVal.insert({Loc, Val});
470       continue;
471     }
472 
473     if (Value *MergedVal =
474             mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
475                                 JoinedEnv, Model)) {
476       JoinedEnv.LocToVal.insert({Loc, MergedVal});
477       Effect = LatticeJoinEffect::Changed;
478     }
479   }
480   if (LocToVal.size() != JoinedEnv.LocToVal.size())
481     Effect = LatticeJoinEffect::Changed;
482 
483   *this = std::move(JoinedEnv);
484 
485   return Effect;
486 }
487 
488 StorageLocation &Environment::createStorageLocation(QualType Type) {
489   return DACtx->createStorageLocation(Type);
490 }
491 
492 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
493   // Evaluated declarations are always assigned the same storage locations to
494   // ensure that the environment stabilizes across loop iterations. Storage
495   // locations for evaluated declarations are stored in the analysis context.
496   return DACtx->getStableStorageLocation(D);
497 }
498 
499 StorageLocation &Environment::createStorageLocation(const Expr &E) {
500   // Evaluated expressions are always assigned the same storage locations to
501   // ensure that the environment stabilizes across loop iterations. Storage
502   // locations for evaluated expressions are stored in the analysis context.
503   return DACtx->getStableStorageLocation(E);
504 }
505 
506 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
507   assert(DeclToLoc.find(&D) == DeclToLoc.end());
508   DeclToLoc[&D] = &Loc;
509 }
510 
511 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
512                                                  SkipPast SP) const {
513   auto It = DeclToLoc.find(&D);
514   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
515 }
516 
517 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
518   const Expr &CanonE = ignoreCFGOmittedNodes(E);
519   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
520   ExprToLoc[&CanonE] = &Loc;
521 }
522 
523 StorageLocation *Environment::getStorageLocation(const Expr &E,
524                                                  SkipPast SP) const {
525   // FIXME: Add a test with parens.
526   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
527   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
528 }
529 
530 StorageLocation *Environment::getThisPointeeStorageLocation() const {
531   return ThisPointeeLoc;
532 }
533 
534 StorageLocation *Environment::getReturnStorageLocation() const {
535   return ReturnLoc;
536 }
537 
538 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
539   return DACtx->getOrCreateNullPointerValue(PointeeType);
540 }
541 
542 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
543   LocToVal[&Loc] = &Val;
544 
545   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
546     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
547 
548     const QualType Type = AggregateLoc.getType();
549     assert(Type->isStructureOrClassType());
550 
551     for (const FieldDecl *Field : getObjectFields(Type)) {
552       assert(Field != nullptr);
553       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
554       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
555       if (auto *FieldVal = StructVal->getChild(*Field))
556         setValue(FieldLoc, *FieldVal);
557     }
558   }
559 
560   auto It = MemberLocToStruct.find(&Loc);
561   if (It != MemberLocToStruct.end()) {
562     // `Loc` is the location of a struct member so we need to also update the
563     // value of the member in the corresponding `StructValue`.
564 
565     assert(It->second.first != nullptr);
566     StructValue &StructVal = *It->second.first;
567 
568     assert(It->second.second != nullptr);
569     const ValueDecl &Member = *It->second.second;
570 
571     StructVal.setChild(Member, Val);
572   }
573 }
574 
575 Value *Environment::getValue(const StorageLocation &Loc) const {
576   auto It = LocToVal.find(&Loc);
577   return It == LocToVal.end() ? nullptr : It->second;
578 }
579 
580 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
581   auto *Loc = getStorageLocation(D, SP);
582   if (Loc == nullptr)
583     return nullptr;
584   return getValue(*Loc);
585 }
586 
587 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
588   auto *Loc = getStorageLocation(E, SP);
589   if (Loc == nullptr)
590     return nullptr;
591   return getValue(*Loc);
592 }
593 
594 Value *Environment::createValue(QualType Type) {
595   llvm::DenseSet<QualType> Visited;
596   int CreatedValuesCount = 0;
597   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
598                                                 CreatedValuesCount);
599   if (CreatedValuesCount > MaxCompositeValueSize) {
600     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
601                  << '\n';
602   }
603   return Val;
604 }
605 
606 Value *Environment::createValueUnlessSelfReferential(
607     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
608     int &CreatedValuesCount) {
609   assert(!Type.isNull());
610 
611   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
612   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
613       Depth > MaxCompositeValueDepth)
614     return nullptr;
615 
616   if (Type->isBooleanType()) {
617     CreatedValuesCount++;
618     return &makeAtomicBoolValue();
619   }
620 
621   if (Type->isIntegerType()) {
622     // FIXME: consider instead `return nullptr`, given that we do nothing useful
623     // with integers, and so distinguishing them serves no purpose, but could
624     // prevent convergence.
625     CreatedValuesCount++;
626     return &takeOwnership(std::make_unique<IntegerValue>());
627   }
628 
629   if (Type->isReferenceType()) {
630     CreatedValuesCount++;
631     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
632     auto &PointeeLoc = createStorageLocation(PointeeType);
633 
634     if (Visited.insert(PointeeType.getCanonicalType()).second) {
635       Value *PointeeVal = createValueUnlessSelfReferential(
636           PointeeType, Visited, Depth, CreatedValuesCount);
637       Visited.erase(PointeeType.getCanonicalType());
638 
639       if (PointeeVal != nullptr)
640         setValue(PointeeLoc, *PointeeVal);
641     }
642 
643     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
644   }
645 
646   if (Type->isPointerType()) {
647     CreatedValuesCount++;
648     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
649     auto &PointeeLoc = createStorageLocation(PointeeType);
650 
651     if (Visited.insert(PointeeType.getCanonicalType()).second) {
652       Value *PointeeVal = createValueUnlessSelfReferential(
653           PointeeType, Visited, Depth, CreatedValuesCount);
654       Visited.erase(PointeeType.getCanonicalType());
655 
656       if (PointeeVal != nullptr)
657         setValue(PointeeLoc, *PointeeVal);
658     }
659 
660     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
661   }
662 
663   if (Type->isStructureOrClassType()) {
664     CreatedValuesCount++;
665     // FIXME: Initialize only fields that are accessed in the context that is
666     // being analyzed.
667     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
668     for (const FieldDecl *Field : getObjectFields(Type)) {
669       assert(Field != nullptr);
670 
671       QualType FieldType = Field->getType();
672       if (Visited.contains(FieldType.getCanonicalType()))
673         continue;
674 
675       Visited.insert(FieldType.getCanonicalType());
676       if (auto *FieldValue = createValueUnlessSelfReferential(
677               FieldType, Visited, Depth + 1, CreatedValuesCount))
678         FieldValues.insert({Field, FieldValue});
679       Visited.erase(FieldType.getCanonicalType());
680     }
681 
682     return &takeOwnership(
683         std::make_unique<StructValue>(std::move(FieldValues)));
684   }
685 
686   return nullptr;
687 }
688 
689 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
690   switch (SP) {
691   case SkipPast::None:
692     return Loc;
693   case SkipPast::Reference:
694     // References cannot be chained so we only need to skip past one level of
695     // indirection.
696     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
697       return Val->getReferentLoc();
698     return Loc;
699   case SkipPast::ReferenceThenPointer:
700     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
701     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
702       return Val->getPointeeLoc();
703     return LocPastRef;
704   }
705   llvm_unreachable("bad SkipPast kind");
706 }
707 
708 const StorageLocation &Environment::skip(const StorageLocation &Loc,
709                                          SkipPast SP) const {
710   return skip(*const_cast<StorageLocation *>(&Loc), SP);
711 }
712 
713 void Environment::addToFlowCondition(BoolValue &Val) {
714   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
715 }
716 
717 bool Environment::flowConditionImplies(BoolValue &Val) const {
718   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
719 }
720 
721 void Environment::dump() const {
722   DACtx->dumpFlowCondition(*FlowConditionToken);
723 }
724 
725 } // namespace dataflow
726 } // namespace clang
727