xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision 0b12efc7a42c187400f7df18d5fd629d92d2747e)
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 areEquivalentIndirectionValues(Value *Val1, Value *Val2) {
53   if (auto *IndVal1 = dyn_cast<ReferenceValue>(Val1)) {
54     auto *IndVal2 = cast<ReferenceValue>(Val2);
55     return &IndVal1->getReferentLoc() == &IndVal2->getReferentLoc();
56   }
57   if (auto *IndVal1 = dyn_cast<PointerValue>(Val1)) {
58     auto *IndVal2 = cast<PointerValue>(Val2);
59     return &IndVal1->getPointeeLoc() == &IndVal2->getPointeeLoc();
60   }
61   return false;
62 }
63 
64 /// Returns true if and only if `Val1` is equivalent to `Val2`.
65 static bool equivalentValues(QualType Type, Value *Val1,
66                              const Environment &Env1, Value *Val2,
67                              const Environment &Env2,
68                              Environment::ValueModel &Model) {
69   return Val1 == Val2 || areEquivalentIndirectionValues(Val1, Val2) ||
70          Model.compareEquivalent(Type, *Val1, Env1, *Val2, Env2);
71 }
72 
73 /// Attempts to merge distinct values `Val1` and `Val2` in `Env1` and `Env2`,
74 /// respectively, of the same type `Type`. Merging generally produces a single
75 /// value that (soundly) approximates the two inputs, although the actual
76 /// meaning depends on `Model`.
77 static Value *mergeDistinctValues(QualType Type, Value *Val1,
78                                   const Environment &Env1, Value *Val2,
79                                   const Environment &Env2,
80                                   Environment &MergedEnv,
81                                   Environment::ValueModel &Model) {
82   // Join distinct boolean values preserving information about the constraints
83   // in the respective path conditions.
84   if (auto *Expr1 = dyn_cast<BoolValue>(Val1)) {
85     auto *Expr2 = cast<BoolValue>(Val2);
86     auto &MergedVal = MergedEnv.makeAtomicBoolValue();
87     MergedEnv.addToFlowCondition(MergedEnv.makeOr(
88         MergedEnv.makeAnd(Env1.getFlowConditionToken(),
89                           MergedEnv.makeIff(MergedVal, *Expr1)),
90         MergedEnv.makeAnd(Env2.getFlowConditionToken(),
91                           MergedEnv.makeIff(MergedVal, *Expr2))));
92     return &MergedVal;
93   }
94 
95   // FIXME: add unit tests that cover this statement.
96   if (areEquivalentIndirectionValues(Val1, Val2)) {
97     return Val1;
98   }
99 
100   // FIXME: Consider destroying `MergedValue` immediately if `ValueModel::merge`
101   // returns false to avoid storing unneeded values in `DACtx`.
102   if (Value *MergedVal = MergedEnv.createValue(Type))
103     if (Model.merge(Type, *Val1, Env1, *Val2, Env2, *MergedVal, MergedEnv))
104       return MergedVal;
105 
106   return nullptr;
107 }
108 
109 /// Initializes a global storage value.
110 static void initGlobalVar(const VarDecl &D, Environment &Env) {
111   if (!D.hasGlobalStorage() ||
112       Env.getStorageLocation(D, SkipPast::None) != nullptr)
113     return;
114 
115   auto &Loc = Env.createStorageLocation(D);
116   Env.setStorageLocation(D, Loc);
117   if (auto *Val = Env.createValue(D.getType()))
118     Env.setValue(Loc, *Val);
119 }
120 
121 /// Initializes a global storage value.
122 static void initGlobalVar(const Decl &D, Environment &Env) {
123   if (auto *V = dyn_cast<VarDecl>(&D))
124     initGlobalVar(*V, Env);
125 }
126 
127 /// Initializes global storage values that are declared or referenced from
128 /// sub-statements of `S`.
129 // FIXME: Add support for resetting globals after function calls to enable
130 // the implementation of sound analyses.
131 static void initGlobalVars(const Stmt &S, Environment &Env) {
132   for (auto *Child : S.children()) {
133     if (Child != nullptr)
134       initGlobalVars(*Child, Env);
135   }
136 
137   if (auto *DS = dyn_cast<DeclStmt>(&S)) {
138     if (DS->isSingleDecl()) {
139       initGlobalVar(*DS->getSingleDecl(), Env);
140     } else {
141       for (auto *D : DS->getDeclGroup())
142         initGlobalVar(*D, Env);
143     }
144   } else if (auto *E = dyn_cast<DeclRefExpr>(&S)) {
145     initGlobalVar(*E->getDecl(), Env);
146   } else if (auto *E = dyn_cast<MemberExpr>(&S)) {
147     initGlobalVar(*E->getMemberDecl(), Env);
148   }
149 }
150 
151 Environment::Environment(DataflowAnalysisContext &DACtx)
152     : DACtx(&DACtx), FlowConditionToken(&DACtx.makeFlowConditionToken()) {}
153 
154 Environment::Environment(const Environment &Other)
155     : DACtx(Other.DACtx), CallStack(Other.CallStack),
156       ReturnLoc(Other.ReturnLoc), ThisPointeeLoc(Other.ThisPointeeLoc),
157       DeclToLoc(Other.DeclToLoc), ExprToLoc(Other.ExprToLoc),
158       LocToVal(Other.LocToVal), MemberLocToStruct(Other.MemberLocToStruct),
159       FlowConditionToken(&DACtx->forkFlowCondition(*Other.FlowConditionToken)) {
160 }
161 
162 Environment &Environment::operator=(const Environment &Other) {
163   Environment Copy(Other);
164   *this = std::move(Copy);
165   return *this;
166 }
167 
168 Environment::Environment(DataflowAnalysisContext &DACtx,
169                          const DeclContext &DeclCtx)
170     : Environment(DACtx) {
171   CallStack.push_back(&DeclCtx);
172 
173   if (const auto *FuncDecl = dyn_cast<FunctionDecl>(&DeclCtx)) {
174     assert(FuncDecl->getBody() != nullptr);
175     initGlobalVars(*FuncDecl->getBody(), *this);
176     for (const auto *ParamDecl : FuncDecl->parameters()) {
177       assert(ParamDecl != nullptr);
178       auto &ParamLoc = createStorageLocation(*ParamDecl);
179       setStorageLocation(*ParamDecl, ParamLoc);
180       if (Value *ParamVal = createValue(ParamDecl->getType()))
181         setValue(ParamLoc, *ParamVal);
182     }
183 
184     QualType ReturnType = FuncDecl->getReturnType();
185     ReturnLoc = &createStorageLocation(ReturnType);
186   }
187 
188   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(&DeclCtx)) {
189     auto *Parent = MethodDecl->getParent();
190     assert(Parent != nullptr);
191     if (Parent->isLambda())
192       MethodDecl = dyn_cast<CXXMethodDecl>(Parent->getDeclContext());
193 
194     if (MethodDecl && !MethodDecl->isStatic()) {
195       QualType ThisPointeeType = MethodDecl->getThisObjectType();
196       // FIXME: Add support for union types.
197       if (!ThisPointeeType->isUnionType()) {
198         ThisPointeeLoc = &createStorageLocation(ThisPointeeType);
199         if (Value *ThisPointeeVal = createValue(ThisPointeeType))
200           setValue(*ThisPointeeLoc, *ThisPointeeVal);
201       }
202     }
203   }
204 }
205 
206 bool Environment::canDescend(unsigned MaxDepth,
207                              const DeclContext *Callee) const {
208   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
209 }
210 
211 Environment Environment::pushCall(const CallExpr *Call) const {
212   Environment Env(*this);
213 
214   // FIXME: Support references here.
215   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
216 
217   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
218     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
219       if (!isa<CXXThisExpr>(Arg))
220         Env.ThisPointeeLoc = getStorageLocation(*Arg, SkipPast::Reference);
221       // Otherwise (when the argument is `this`), retain the current
222       // environment's `ThisPointeeLoc`.
223     }
224   }
225 
226   Env.pushCallInternal(Call->getDirectCallee(),
227                        llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs()));
228 
229   return Env;
230 }
231 
232 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
233   Environment Env(*this);
234 
235   // FIXME: Support references here.
236   Env.ReturnLoc = getStorageLocation(*Call, SkipPast::Reference);
237 
238   Env.ThisPointeeLoc = Env.ReturnLoc;
239 
240   Env.pushCallInternal(Call->getConstructor(),
241                        llvm::makeArrayRef(Call->getArgs(), Call->getNumArgs()));
242 
243   return Env;
244 }
245 
246 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
247                                    ArrayRef<const Expr *> Args) {
248   CallStack.push_back(FuncDecl);
249 
250   // FIXME: In order to allow the callee to reference globals, we probably need
251   // to call `initGlobalVars` here in some way.
252 
253   auto ParamIt = FuncDecl->param_begin();
254 
255   // FIXME: Parameters don't always map to arguments 1:1; examples include
256   // overloaded operators implemented as member functions, and parameter packs.
257   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
258     assert(ParamIt != FuncDecl->param_end());
259 
260     const Expr *Arg = Args[ArgIndex];
261     auto *ArgLoc = getStorageLocation(*Arg, SkipPast::Reference);
262     if (ArgLoc == nullptr)
263       continue;
264 
265     const VarDecl *Param = *ParamIt;
266     auto &Loc = createStorageLocation(*Param);
267     setStorageLocation(*Param, Loc);
268 
269     QualType ParamType = Param->getType();
270     if (ParamType->isReferenceType()) {
271       auto &Val = takeOwnership(std::make_unique<ReferenceValue>(*ArgLoc));
272       setValue(Loc, Val);
273     } else if (auto *ArgVal = getValue(*ArgLoc)) {
274       setValue(Loc, *ArgVal);
275     } else if (Value *Val = createValue(ParamType)) {
276       setValue(Loc, *Val);
277     }
278   }
279 }
280 
281 void Environment::popCall(const Environment &CalleeEnv) {
282   // We ignore `DACtx` because it's already the same in both. We don't want the
283   // callee's `DeclCtx`, `ReturnLoc` or `ThisPointeeLoc`. We don't bring back
284   // `DeclToLoc` and `ExprToLoc` because we want to be able to later analyze the
285   // same callee in a different context, and `setStorageLocation` requires there
286   // to not already be a storage location assigned. Conceptually, these maps
287   // capture information from the local scope, so when popping that scope, we do
288   // not propagate the maps.
289   this->LocToVal = std::move(CalleeEnv.LocToVal);
290   this->MemberLocToStruct = std::move(CalleeEnv.MemberLocToStruct);
291   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
292 }
293 
294 bool Environment::equivalentTo(const Environment &Other,
295                                Environment::ValueModel &Model) const {
296   assert(DACtx == Other.DACtx);
297 
298   if (ReturnLoc != Other.ReturnLoc)
299     return false;
300 
301   if (ThisPointeeLoc != Other.ThisPointeeLoc)
302     return false;
303 
304   if (DeclToLoc != Other.DeclToLoc)
305     return false;
306 
307   if (ExprToLoc != Other.ExprToLoc)
308     return false;
309 
310   // Compare the contents for the intersection of their domains.
311   for (auto &Entry : LocToVal) {
312     const StorageLocation *Loc = Entry.first;
313     assert(Loc != nullptr);
314 
315     Value *Val = Entry.second;
316     assert(Val != nullptr);
317 
318     auto It = Other.LocToVal.find(Loc);
319     if (It == Other.LocToVal.end())
320       continue;
321     assert(It->second != nullptr);
322 
323     if (!equivalentValues(Loc->getType(), Val, *this, It->second, Other, Model))
324       return false;
325   }
326 
327   return true;
328 }
329 
330 LatticeJoinEffect Environment::join(const Environment &Other,
331                                     Environment::ValueModel &Model) {
332   assert(DACtx == Other.DACtx);
333   assert(ReturnLoc == Other.ReturnLoc);
334   assert(ThisPointeeLoc == Other.ThisPointeeLoc);
335   assert(CallStack == Other.CallStack);
336 
337   auto Effect = LatticeJoinEffect::Unchanged;
338 
339   Environment JoinedEnv(*DACtx);
340 
341   JoinedEnv.CallStack = CallStack;
342   JoinedEnv.ReturnLoc = ReturnLoc;
343   JoinedEnv.ThisPointeeLoc = ThisPointeeLoc;
344 
345   JoinedEnv.DeclToLoc = intersectDenseMaps(DeclToLoc, Other.DeclToLoc);
346   if (DeclToLoc.size() != JoinedEnv.DeclToLoc.size())
347     Effect = LatticeJoinEffect::Changed;
348 
349   JoinedEnv.ExprToLoc = intersectDenseMaps(ExprToLoc, Other.ExprToLoc);
350   if (ExprToLoc.size() != JoinedEnv.ExprToLoc.size())
351     Effect = LatticeJoinEffect::Changed;
352 
353   JoinedEnv.MemberLocToStruct =
354       intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
355   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
356     Effect = LatticeJoinEffect::Changed;
357 
358   // FIXME: set `Effect` as needed.
359   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
360       *FlowConditionToken, *Other.FlowConditionToken);
361 
362   for (auto &Entry : LocToVal) {
363     const StorageLocation *Loc = Entry.first;
364     assert(Loc != nullptr);
365 
366     Value *Val = Entry.second;
367     assert(Val != nullptr);
368 
369     auto It = Other.LocToVal.find(Loc);
370     if (It == Other.LocToVal.end())
371       continue;
372     assert(It->second != nullptr);
373 
374     if (Val == It->second) {
375       JoinedEnv.LocToVal.insert({Loc, Val});
376       continue;
377     }
378 
379     if (Value *MergedVal = mergeDistinctValues(
380             Loc->getType(), Val, *this, It->second, Other, JoinedEnv, Model))
381       JoinedEnv.LocToVal.insert({Loc, MergedVal});
382   }
383   if (LocToVal.size() != JoinedEnv.LocToVal.size())
384     Effect = LatticeJoinEffect::Changed;
385 
386   *this = std::move(JoinedEnv);
387 
388   return Effect;
389 }
390 
391 StorageLocation &Environment::createStorageLocation(QualType Type) {
392   return DACtx->createStorageLocation(Type);
393 }
394 
395 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
396   // Evaluated declarations are always assigned the same storage locations to
397   // ensure that the environment stabilizes across loop iterations. Storage
398   // locations for evaluated declarations are stored in the analysis context.
399   return DACtx->getStableStorageLocation(D);
400 }
401 
402 StorageLocation &Environment::createStorageLocation(const Expr &E) {
403   // Evaluated expressions are always assigned the same storage locations to
404   // ensure that the environment stabilizes across loop iterations. Storage
405   // locations for evaluated expressions are stored in the analysis context.
406   return DACtx->getStableStorageLocation(E);
407 }
408 
409 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
410   assert(DeclToLoc.find(&D) == DeclToLoc.end());
411   DeclToLoc[&D] = &Loc;
412 }
413 
414 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
415                                                  SkipPast SP) const {
416   auto It = DeclToLoc.find(&D);
417   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
418 }
419 
420 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
421   const Expr &CanonE = ignoreCFGOmittedNodes(E);
422   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
423   ExprToLoc[&CanonE] = &Loc;
424 }
425 
426 StorageLocation *Environment::getStorageLocation(const Expr &E,
427                                                  SkipPast SP) const {
428   // FIXME: Add a test with parens.
429   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
430   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
431 }
432 
433 StorageLocation *Environment::getThisPointeeStorageLocation() const {
434   return ThisPointeeLoc;
435 }
436 
437 StorageLocation *Environment::getReturnStorageLocation() const {
438   return ReturnLoc;
439 }
440 
441 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
442   return DACtx->getOrCreateNullPointerValue(PointeeType);
443 }
444 
445 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
446   LocToVal[&Loc] = &Val;
447 
448   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
449     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
450 
451     const QualType Type = AggregateLoc.getType();
452     assert(Type->isStructureOrClassType());
453 
454     for (const FieldDecl *Field : getObjectFields(Type)) {
455       assert(Field != nullptr);
456       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
457       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
458       if (auto *FieldVal = StructVal->getChild(*Field))
459         setValue(FieldLoc, *FieldVal);
460     }
461   }
462 
463   auto It = MemberLocToStruct.find(&Loc);
464   if (It != MemberLocToStruct.end()) {
465     // `Loc` is the location of a struct member so we need to also update the
466     // value of the member in the corresponding `StructValue`.
467 
468     assert(It->second.first != nullptr);
469     StructValue &StructVal = *It->second.first;
470 
471     assert(It->second.second != nullptr);
472     const ValueDecl &Member = *It->second.second;
473 
474     StructVal.setChild(Member, Val);
475   }
476 }
477 
478 Value *Environment::getValue(const StorageLocation &Loc) const {
479   auto It = LocToVal.find(&Loc);
480   return It == LocToVal.end() ? nullptr : It->second;
481 }
482 
483 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
484   auto *Loc = getStorageLocation(D, SP);
485   if (Loc == nullptr)
486     return nullptr;
487   return getValue(*Loc);
488 }
489 
490 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
491   auto *Loc = getStorageLocation(E, SP);
492   if (Loc == nullptr)
493     return nullptr;
494   return getValue(*Loc);
495 }
496 
497 Value *Environment::createValue(QualType Type) {
498   llvm::DenseSet<QualType> Visited;
499   int CreatedValuesCount = 0;
500   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
501                                                 CreatedValuesCount);
502   if (CreatedValuesCount > MaxCompositeValueSize) {
503     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
504                  << '\n';
505   }
506   return Val;
507 }
508 
509 Value *Environment::createValueUnlessSelfReferential(
510     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
511     int &CreatedValuesCount) {
512   assert(!Type.isNull());
513 
514   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
515   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
516       Depth > MaxCompositeValueDepth)
517     return nullptr;
518 
519   if (Type->isBooleanType()) {
520     CreatedValuesCount++;
521     return &makeAtomicBoolValue();
522   }
523 
524   if (Type->isIntegerType()) {
525     CreatedValuesCount++;
526     return &takeOwnership(std::make_unique<IntegerValue>());
527   }
528 
529   if (Type->isReferenceType()) {
530     CreatedValuesCount++;
531     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
532     auto &PointeeLoc = createStorageLocation(PointeeType);
533 
534     if (Visited.insert(PointeeType.getCanonicalType()).second) {
535       Value *PointeeVal = createValueUnlessSelfReferential(
536           PointeeType, Visited, Depth, CreatedValuesCount);
537       Visited.erase(PointeeType.getCanonicalType());
538 
539       if (PointeeVal != nullptr)
540         setValue(PointeeLoc, *PointeeVal);
541     }
542 
543     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
544   }
545 
546   if (Type->isPointerType()) {
547     CreatedValuesCount++;
548     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
549     auto &PointeeLoc = createStorageLocation(PointeeType);
550 
551     if (Visited.insert(PointeeType.getCanonicalType()).second) {
552       Value *PointeeVal = createValueUnlessSelfReferential(
553           PointeeType, Visited, Depth, CreatedValuesCount);
554       Visited.erase(PointeeType.getCanonicalType());
555 
556       if (PointeeVal != nullptr)
557         setValue(PointeeLoc, *PointeeVal);
558     }
559 
560     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
561   }
562 
563   if (Type->isStructureOrClassType()) {
564     CreatedValuesCount++;
565     // FIXME: Initialize only fields that are accessed in the context that is
566     // being analyzed.
567     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
568     for (const FieldDecl *Field : getObjectFields(Type)) {
569       assert(Field != nullptr);
570 
571       QualType FieldType = Field->getType();
572       if (Visited.contains(FieldType.getCanonicalType()))
573         continue;
574 
575       Visited.insert(FieldType.getCanonicalType());
576       if (auto *FieldValue = createValueUnlessSelfReferential(
577               FieldType, Visited, Depth + 1, CreatedValuesCount))
578         FieldValues.insert({Field, FieldValue});
579       Visited.erase(FieldType.getCanonicalType());
580     }
581 
582     return &takeOwnership(
583         std::make_unique<StructValue>(std::move(FieldValues)));
584   }
585 
586   return nullptr;
587 }
588 
589 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
590   switch (SP) {
591   case SkipPast::None:
592     return Loc;
593   case SkipPast::Reference:
594     // References cannot be chained so we only need to skip past one level of
595     // indirection.
596     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
597       return Val->getReferentLoc();
598     return Loc;
599   case SkipPast::ReferenceThenPointer:
600     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
601     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
602       return Val->getPointeeLoc();
603     return LocPastRef;
604   }
605   llvm_unreachable("bad SkipPast kind");
606 }
607 
608 const StorageLocation &Environment::skip(const StorageLocation &Loc,
609                                          SkipPast SP) const {
610   return skip(*const_cast<StorageLocation *>(&Loc), SP);
611 }
612 
613 void Environment::addToFlowCondition(BoolValue &Val) {
614   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
615 }
616 
617 bool Environment::flowConditionImplies(BoolValue &Val) const {
618   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
619 }
620 
621 void Environment::dump() const {
622   DACtx->dumpFlowCondition(*FlowConditionToken);
623 }
624 
625 } // namespace dataflow
626 } // namespace clang
627