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