xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision 84dd12b29064095cdef3949e8fd5c91b93f36004)
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   assert(JoinedEnv.MemberLocToStruct.size() <=
448          std::min(MemberLocToStruct.size(), Other.MemberLocToStruct.size()));
449 
450   intersectDenseMaps(MemberLocToStruct, Other.MemberLocToStruct);
451   if (MemberLocToStruct.size() != JoinedEnv.MemberLocToStruct.size())
452     Effect = LatticeJoinEffect::Changed;
453 
454   // FIXME: set `Effect` as needed.
455   // FIXME: update join to detect backedges and simplify the flow condition
456   // accordingly.
457   JoinedEnv.FlowConditionToken = &DACtx->joinFlowConditions(
458       *FlowConditionToken, *Other.FlowConditionToken);
459 
460   for (auto &Entry : LocToVal) {
461     const StorageLocation *Loc = Entry.first;
462     assert(Loc != nullptr);
463 
464     Value *Val = Entry.second;
465     assert(Val != nullptr);
466 
467     auto It = Other.LocToVal.find(Loc);
468     if (It == Other.LocToVal.end())
469       continue;
470     assert(It->second != nullptr);
471 
472     if (areEquivalentValues(*Val, *It->second)) {
473       JoinedEnv.LocToVal.insert({Loc, Val});
474       continue;
475     }
476 
477     if (Value *MergedVal =
478             mergeDistinctValues(Loc->getType(), *Val, *this, *It->second, Other,
479                                 JoinedEnv, Model)) {
480       JoinedEnv.LocToVal.insert({Loc, MergedVal});
481       Effect = LatticeJoinEffect::Changed;
482     }
483   }
484   if (LocToVal.size() != JoinedEnv.LocToVal.size())
485     Effect = LatticeJoinEffect::Changed;
486 
487   *this = std::move(JoinedEnv);
488 
489   return Effect;
490 }
491 
492 StorageLocation &Environment::createStorageLocation(QualType Type) {
493   return DACtx->createStorageLocation(Type);
494 }
495 
496 StorageLocation &Environment::createStorageLocation(const VarDecl &D) {
497   // Evaluated declarations are always assigned the same storage locations to
498   // ensure that the environment stabilizes across loop iterations. Storage
499   // locations for evaluated declarations are stored in the analysis context.
500   return DACtx->getStableStorageLocation(D);
501 }
502 
503 StorageLocation &Environment::createStorageLocation(const Expr &E) {
504   // Evaluated expressions are always assigned the same storage locations to
505   // ensure that the environment stabilizes across loop iterations. Storage
506   // locations for evaluated expressions are stored in the analysis context.
507   return DACtx->getStableStorageLocation(E);
508 }
509 
510 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
511   assert(DeclToLoc.find(&D) == DeclToLoc.end());
512   DeclToLoc[&D] = &Loc;
513 }
514 
515 StorageLocation *Environment::getStorageLocation(const ValueDecl &D,
516                                                  SkipPast SP) const {
517   auto It = DeclToLoc.find(&D);
518   return It == DeclToLoc.end() ? nullptr : &skip(*It->second, SP);
519 }
520 
521 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
522   const Expr &CanonE = ignoreCFGOmittedNodes(E);
523   assert(ExprToLoc.find(&CanonE) == ExprToLoc.end());
524   ExprToLoc[&CanonE] = &Loc;
525 }
526 
527 StorageLocation *Environment::getStorageLocation(const Expr &E,
528                                                  SkipPast SP) const {
529   // FIXME: Add a test with parens.
530   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
531   return It == ExprToLoc.end() ? nullptr : &skip(*It->second, SP);
532 }
533 
534 StorageLocation *Environment::getThisPointeeStorageLocation() const {
535   return ThisPointeeLoc;
536 }
537 
538 StorageLocation *Environment::getReturnStorageLocation() const {
539   return ReturnLoc;
540 }
541 
542 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
543   return DACtx->getOrCreateNullPointerValue(PointeeType);
544 }
545 
546 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
547   LocToVal[&Loc] = &Val;
548 
549   if (auto *StructVal = dyn_cast<StructValue>(&Val)) {
550     auto &AggregateLoc = *cast<AggregateStorageLocation>(&Loc);
551 
552     const QualType Type = AggregateLoc.getType();
553     assert(Type->isStructureOrClassType());
554 
555     for (const FieldDecl *Field : getObjectFields(Type)) {
556       assert(Field != nullptr);
557       StorageLocation &FieldLoc = AggregateLoc.getChild(*Field);
558       MemberLocToStruct[&FieldLoc] = std::make_pair(StructVal, Field);
559       if (auto *FieldVal = StructVal->getChild(*Field))
560         setValue(FieldLoc, *FieldVal);
561     }
562   }
563 
564   auto It = MemberLocToStruct.find(&Loc);
565   if (It != MemberLocToStruct.end()) {
566     // `Loc` is the location of a struct member so we need to also update the
567     // value of the member in the corresponding `StructValue`.
568 
569     assert(It->second.first != nullptr);
570     StructValue &StructVal = *It->second.first;
571 
572     assert(It->second.second != nullptr);
573     const ValueDecl &Member = *It->second.second;
574 
575     StructVal.setChild(Member, Val);
576   }
577 }
578 
579 Value *Environment::getValue(const StorageLocation &Loc) const {
580   auto It = LocToVal.find(&Loc);
581   return It == LocToVal.end() ? nullptr : It->second;
582 }
583 
584 Value *Environment::getValue(const ValueDecl &D, SkipPast SP) const {
585   auto *Loc = getStorageLocation(D, SP);
586   if (Loc == nullptr)
587     return nullptr;
588   return getValue(*Loc);
589 }
590 
591 Value *Environment::getValue(const Expr &E, SkipPast SP) const {
592   auto *Loc = getStorageLocation(E, SP);
593   if (Loc == nullptr)
594     return nullptr;
595   return getValue(*Loc);
596 }
597 
598 Value *Environment::createValue(QualType Type) {
599   llvm::DenseSet<QualType> Visited;
600   int CreatedValuesCount = 0;
601   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
602                                                 CreatedValuesCount);
603   if (CreatedValuesCount > MaxCompositeValueSize) {
604     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
605                  << '\n';
606   }
607   return Val;
608 }
609 
610 Value *Environment::createValueUnlessSelfReferential(
611     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
612     int &CreatedValuesCount) {
613   assert(!Type.isNull());
614 
615   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
616   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
617       Depth > MaxCompositeValueDepth)
618     return nullptr;
619 
620   if (Type->isBooleanType()) {
621     CreatedValuesCount++;
622     return &makeAtomicBoolValue();
623   }
624 
625   if (Type->isIntegerType()) {
626     // FIXME: consider instead `return nullptr`, given that we do nothing useful
627     // with integers, and so distinguishing them serves no purpose, but could
628     // prevent convergence.
629     CreatedValuesCount++;
630     return &takeOwnership(std::make_unique<IntegerValue>());
631   }
632 
633   if (Type->isReferenceType()) {
634     CreatedValuesCount++;
635     QualType PointeeType = Type->castAs<ReferenceType>()->getPointeeType();
636     auto &PointeeLoc = createStorageLocation(PointeeType);
637 
638     if (Visited.insert(PointeeType.getCanonicalType()).second) {
639       Value *PointeeVal = createValueUnlessSelfReferential(
640           PointeeType, Visited, Depth, CreatedValuesCount);
641       Visited.erase(PointeeType.getCanonicalType());
642 
643       if (PointeeVal != nullptr)
644         setValue(PointeeLoc, *PointeeVal);
645     }
646 
647     return &takeOwnership(std::make_unique<ReferenceValue>(PointeeLoc));
648   }
649 
650   if (Type->isPointerType()) {
651     CreatedValuesCount++;
652     QualType PointeeType = Type->castAs<PointerType>()->getPointeeType();
653     auto &PointeeLoc = createStorageLocation(PointeeType);
654 
655     if (Visited.insert(PointeeType.getCanonicalType()).second) {
656       Value *PointeeVal = createValueUnlessSelfReferential(
657           PointeeType, Visited, Depth, CreatedValuesCount);
658       Visited.erase(PointeeType.getCanonicalType());
659 
660       if (PointeeVal != nullptr)
661         setValue(PointeeLoc, *PointeeVal);
662     }
663 
664     return &takeOwnership(std::make_unique<PointerValue>(PointeeLoc));
665   }
666 
667   if (Type->isStructureOrClassType()) {
668     CreatedValuesCount++;
669     // FIXME: Initialize only fields that are accessed in the context that is
670     // being analyzed.
671     llvm::DenseMap<const ValueDecl *, Value *> FieldValues;
672     for (const FieldDecl *Field : getObjectFields(Type)) {
673       assert(Field != nullptr);
674 
675       QualType FieldType = Field->getType();
676       if (Visited.contains(FieldType.getCanonicalType()))
677         continue;
678 
679       Visited.insert(FieldType.getCanonicalType());
680       if (auto *FieldValue = createValueUnlessSelfReferential(
681               FieldType, Visited, Depth + 1, CreatedValuesCount))
682         FieldValues.insert({Field, FieldValue});
683       Visited.erase(FieldType.getCanonicalType());
684     }
685 
686     return &takeOwnership(
687         std::make_unique<StructValue>(std::move(FieldValues)));
688   }
689 
690   return nullptr;
691 }
692 
693 StorageLocation &Environment::skip(StorageLocation &Loc, SkipPast SP) const {
694   switch (SP) {
695   case SkipPast::None:
696     return Loc;
697   case SkipPast::Reference:
698     // References cannot be chained so we only need to skip past one level of
699     // indirection.
700     if (auto *Val = dyn_cast_or_null<ReferenceValue>(getValue(Loc)))
701       return Val->getReferentLoc();
702     return Loc;
703   case SkipPast::ReferenceThenPointer:
704     StorageLocation &LocPastRef = skip(Loc, SkipPast::Reference);
705     if (auto *Val = dyn_cast_or_null<PointerValue>(getValue(LocPastRef)))
706       return Val->getPointeeLoc();
707     return LocPastRef;
708   }
709   llvm_unreachable("bad SkipPast kind");
710 }
711 
712 const StorageLocation &Environment::skip(const StorageLocation &Loc,
713                                          SkipPast SP) const {
714   return skip(*const_cast<StorageLocation *>(&Loc), SP);
715 }
716 
717 void Environment::addToFlowCondition(BoolValue &Val) {
718   DACtx->addFlowConditionConstraint(*FlowConditionToken, Val);
719 }
720 
721 bool Environment::flowConditionImplies(BoolValue &Val) const {
722   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
723 }
724 
725 void Environment::dump() const {
726   DACtx->dumpFlowCondition(*FlowConditionToken);
727 }
728 
729 } // namespace dataflow
730 } // namespace clang
731