xref: /llvm-project/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (revision 9b0651f5ae6510577302ea527b2cc79e80ec9ccc)
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/RecursiveASTVisitor.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Analysis/FlowSensitive/ASTOps.h"
21 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
22 #include "clang/Analysis/FlowSensitive/Value.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/ScopeExit.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include <cassert>
30 #include <utility>
31 
32 #define DEBUG_TYPE "dataflow"
33 
34 namespace clang {
35 namespace dataflow {
36 
37 // FIXME: convert these to parameters of the analysis or environment. Current
38 // settings have been experimentaly validated, but only for a particular
39 // analysis.
40 static constexpr int MaxCompositeValueDepth = 3;
41 static constexpr int MaxCompositeValueSize = 1000;
42 
43 /// Returns a map consisting of key-value entries that are present in both maps.
44 static llvm::DenseMap<const ValueDecl *, StorageLocation *> intersectDeclToLoc(
45     const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc1,
46     const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc2) {
47   llvm::DenseMap<const ValueDecl *, StorageLocation *> Result;
48   for (auto &Entry : DeclToLoc1) {
49     auto It = DeclToLoc2.find(Entry.first);
50     if (It != DeclToLoc2.end() && Entry.second == It->second)
51       Result.insert({Entry.first, Entry.second});
52   }
53   return Result;
54 }
55 
56 // Performs a join on either `ExprToLoc` or `ExprToVal`.
57 // The maps must be consistent in the sense that any entries for the same
58 // expression must map to the same location / value. This is the case if we are
59 // performing a join for control flow within a full-expression (which is the
60 // only case when this function should be used).
61 template <typename MapT> MapT joinExprMaps(const MapT &Map1, const MapT &Map2) {
62   MapT Result = Map1;
63 
64   for (const auto &Entry : Map2) {
65     [[maybe_unused]] auto [It, Inserted] = Result.insert(Entry);
66     // If there was an existing entry, its value should be the same as for the
67     // entry we were trying to insert.
68     assert(It->second == Entry.second);
69   }
70 
71   return Result;
72 }
73 
74 // Whether to consider equivalent two values with an unknown relation.
75 //
76 // FIXME: this function is a hack enabling unsoundness to support
77 // convergence. Once we have widening support for the reference/pointer and
78 // struct built-in models, this should be unconditionally `false` (and inlined
79 // as such at its call sites).
80 static bool equateUnknownValues(Value::Kind K) {
81   switch (K) {
82   case Value::Kind::Integer:
83   case Value::Kind::Pointer:
84     return true;
85   default:
86     return false;
87   }
88 }
89 
90 static bool compareDistinctValues(QualType Type, Value &Val1,
91                                   const Environment &Env1, Value &Val2,
92                                   const Environment &Env2,
93                                   Environment::ValueModel &Model) {
94   // Note: Potentially costly, but, for booleans, we could check whether both
95   // can be proven equivalent in their respective environments.
96 
97   // FIXME: move the reference/pointers logic from `areEquivalentValues` to here
98   // and implement separate, join/widen specific handling for
99   // reference/pointers.
100   switch (Model.compare(Type, Val1, Env1, Val2, Env2)) {
101   case ComparisonResult::Same:
102     return true;
103   case ComparisonResult::Different:
104     return false;
105   case ComparisonResult::Unknown:
106     return equateUnknownValues(Val1.getKind());
107   }
108   llvm_unreachable("All cases covered in switch");
109 }
110 
111 /// Attempts to join distinct values `Val1` and `Val2` in `Env1` and `Env2`,
112 /// respectively, of the same type `Type`. Joining generally produces a single
113 /// value that (soundly) approximates the two inputs, although the actual
114 /// meaning depends on `Model`.
115 static Value *joinDistinctValues(QualType Type, Value &Val1,
116                                  const Environment &Env1, Value &Val2,
117                                  const Environment &Env2,
118                                  Environment &JoinedEnv,
119                                  Environment::ValueModel &Model) {
120   // Join distinct boolean values preserving information about the constraints
121   // in the respective path conditions.
122   if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) {
123     // FIXME: Checking both values should be unnecessary, since they should have
124     // a consistent shape.  However, right now we can end up with BoolValue's in
125     // integer-typed variables due to our incorrect handling of
126     // boolean-to-integer casts (we just propagate the BoolValue to the result
127     // of the cast). So, a join can encounter an integer in one branch but a
128     // bool in the other.
129     // For example:
130     // ```
131     // std::optional<bool> o;
132     // int x;
133     // if (o.has_value())
134     //   x = o.value();
135     // ```
136     auto &Expr1 = cast<BoolValue>(Val1).formula();
137     auto &Expr2 = cast<BoolValue>(Val2).formula();
138     auto &A = JoinedEnv.arena();
139     auto &JoinedVal = A.makeAtomRef(A.makeAtom());
140     JoinedEnv.assume(
141         A.makeOr(A.makeAnd(A.makeAtomRef(Env1.getFlowConditionToken()),
142                            A.makeEquals(JoinedVal, Expr1)),
143                  A.makeAnd(A.makeAtomRef(Env2.getFlowConditionToken()),
144                            A.makeEquals(JoinedVal, Expr2))));
145     return &A.makeBoolValue(JoinedVal);
146   }
147 
148   Value *JoinedVal = JoinedEnv.createValue(Type);
149   if (JoinedVal)
150     Model.join(Type, Val1, Env1, Val2, Env2, *JoinedVal, JoinedEnv);
151 
152   return JoinedVal;
153 }
154 
155 static WidenResult widenDistinctValues(QualType Type, Value &Prev,
156                                        const Environment &PrevEnv,
157                                        Value &Current, Environment &CurrentEnv,
158                                        Environment::ValueModel &Model) {
159   // Boolean-model widening.
160   if (auto *PrevBool = dyn_cast<BoolValue>(&Prev)) {
161     if (isa<TopBoolValue>(Prev))
162       // Safe to return `Prev` here, because Top is never dependent on the
163       // environment.
164       return {&Prev, LatticeEffect::Unchanged};
165 
166     // We may need to widen to Top, but before we do so, check whether both
167     // values are implied to be either true or false in the current environment.
168     // In that case, we can simply return a literal instead.
169     auto &CurBool = cast<BoolValue>(Current);
170     bool TruePrev = PrevEnv.proves(PrevBool->formula());
171     bool TrueCur = CurrentEnv.proves(CurBool.formula());
172     if (TruePrev && TrueCur)
173       return {&CurrentEnv.getBoolLiteralValue(true), LatticeEffect::Unchanged};
174     if (!TruePrev && !TrueCur &&
175         PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool->formula())) &&
176         CurrentEnv.proves(CurrentEnv.arena().makeNot(CurBool.formula())))
177       return {&CurrentEnv.getBoolLiteralValue(false), LatticeEffect::Unchanged};
178 
179     return {&CurrentEnv.makeTopBoolValue(), LatticeEffect::Changed};
180   }
181 
182   // FIXME: Add other built-in model widening.
183 
184   // Custom-model widening.
185   if (auto Result = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv))
186     return *Result;
187 
188   return {&Current, equateUnknownValues(Prev.getKind())
189                         ? LatticeEffect::Unchanged
190                         : LatticeEffect::Changed};
191 }
192 
193 // Returns whether the values in `Map1` and `Map2` compare equal for those
194 // keys that `Map1` and `Map2` have in common.
195 template <typename Key>
196 bool compareKeyToValueMaps(const llvm::MapVector<Key, Value *> &Map1,
197                            const llvm::MapVector<Key, Value *> &Map2,
198                            const Environment &Env1, const Environment &Env2,
199                            Environment::ValueModel &Model) {
200   for (auto &Entry : Map1) {
201     Key K = Entry.first;
202     assert(K != nullptr);
203 
204     Value *Val = Entry.second;
205     assert(Val != nullptr);
206 
207     auto It = Map2.find(K);
208     if (It == Map2.end())
209       continue;
210     assert(It->second != nullptr);
211 
212     if (!areEquivalentValues(*Val, *It->second) &&
213         !compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2,
214                                Model))
215       return false;
216   }
217 
218   return true;
219 }
220 
221 // Perform a join on two `LocToVal` maps.
222 static llvm::MapVector<const StorageLocation *, Value *>
223 joinLocToVal(const llvm::MapVector<const StorageLocation *, Value *> &LocToVal,
224              const llvm::MapVector<const StorageLocation *, Value *> &LocToVal2,
225              const Environment &Env1, const Environment &Env2,
226              Environment &JoinedEnv, Environment::ValueModel &Model) {
227   llvm::MapVector<const StorageLocation *, Value *> Result;
228   for (auto &Entry : LocToVal) {
229     const StorageLocation *Loc = Entry.first;
230     assert(Loc != nullptr);
231 
232     Value *Val = Entry.second;
233     assert(Val != nullptr);
234 
235     auto It = LocToVal2.find(Loc);
236     if (It == LocToVal2.end())
237       continue;
238     assert(It->second != nullptr);
239 
240     if (Value *JoinedVal = Environment::joinValues(
241             Loc->getType(), Val, Env1, It->second, Env2, JoinedEnv, Model)) {
242       Result.insert({Loc, JoinedVal});
243     }
244   }
245 
246   return Result;
247 }
248 
249 // Perform widening on either `LocToVal` or `ExprToVal`. `Key` must be either
250 // `const StorageLocation *` or `const Expr *`.
251 template <typename Key>
252 llvm::MapVector<Key, Value *>
253 widenKeyToValueMap(const llvm::MapVector<Key, Value *> &CurMap,
254                    const llvm::MapVector<Key, Value *> &PrevMap,
255                    Environment &CurEnv, const Environment &PrevEnv,
256                    Environment::ValueModel &Model, LatticeEffect &Effect) {
257   llvm::MapVector<Key, Value *> WidenedMap;
258   for (auto &Entry : CurMap) {
259     Key K = Entry.first;
260     assert(K != nullptr);
261 
262     Value *Val = Entry.second;
263     assert(Val != nullptr);
264 
265     auto PrevIt = PrevMap.find(K);
266     if (PrevIt == PrevMap.end())
267       continue;
268     assert(PrevIt->second != nullptr);
269 
270     if (areEquivalentValues(*Val, *PrevIt->second)) {
271       WidenedMap.insert({K, Val});
272       continue;
273     }
274 
275     auto [WidenedVal, ValEffect] = widenDistinctValues(
276         K->getType(), *PrevIt->second, PrevEnv, *Val, CurEnv, Model);
277     WidenedMap.insert({K, WidenedVal});
278     if (ValEffect == LatticeEffect::Changed)
279       Effect = LatticeEffect::Changed;
280   }
281 
282   return WidenedMap;
283 }
284 
285 namespace {
286 
287 // Visitor that builds a map from record prvalues to result objects.
288 // This traverses the body of the function to be analyzed; for each result
289 // object that it encounters, it propagates the storage location of the result
290 // object to all record prvalues that can initialize it.
291 class ResultObjectVisitor : public RecursiveASTVisitor<ResultObjectVisitor> {
292 public:
293   // `ResultObjectMap` will be filled with a map from record prvalues to result
294   // object. If the function being analyzed returns a record by value,
295   // `LocForRecordReturnVal` is the location to which this record should be
296   // written; otherwise, it is null.
297   explicit ResultObjectVisitor(
298       llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap,
299       RecordStorageLocation *LocForRecordReturnVal,
300       DataflowAnalysisContext &DACtx)
301       : ResultObjectMap(ResultObjectMap),
302         LocForRecordReturnVal(LocForRecordReturnVal), DACtx(DACtx) {}
303 
304   bool shouldVisitImplicitCode() { return true; }
305 
306   bool shouldVisitLambdaBody() const { return false; }
307 
308   // Traverse all member and base initializers of `Ctor`. This function is not
309   // called by `RecursiveASTVisitor`; it should be called manually if we are
310   // analyzing a constructor. `ThisPointeeLoc` is the storage location that
311   // `this` points to.
312   void TraverseConstructorInits(const CXXConstructorDecl *Ctor,
313                                 RecordStorageLocation *ThisPointeeLoc) {
314     assert(ThisPointeeLoc != nullptr);
315     for (const CXXCtorInitializer *Init : Ctor->inits()) {
316       Expr *InitExpr = Init->getInit();
317       if (FieldDecl *Field = Init->getMember();
318           Field != nullptr && Field->getType()->isRecordType()) {
319         PropagateResultObject(InitExpr, cast<RecordStorageLocation>(
320                                             ThisPointeeLoc->getChild(*Field)));
321       } else if (Init->getBaseClass()) {
322         PropagateResultObject(InitExpr, ThisPointeeLoc);
323       }
324 
325       // Ensure that any result objects within `InitExpr` (e.g. temporaries)
326       // are also propagated to the prvalues that initialize them.
327       TraverseStmt(InitExpr);
328 
329       // If this is a `CXXDefaultInitExpr`, also propagate any result objects
330       // within the default expression.
331       if (auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(InitExpr))
332         TraverseStmt(DefaultInit->getExpr());
333     }
334   }
335 
336   bool TraverseDecl(Decl *D) {
337     // Don't traverse nested record or function declarations.
338     // - We won't be analyzing code contained in these anyway
339     // - We don't model fields that are used only in these nested declaration,
340     //   so trying to propagate a result object to initializers of such fields
341     //   would cause an error.
342     if (isa_and_nonnull<RecordDecl>(D) || isa_and_nonnull<FunctionDecl>(D))
343       return true;
344 
345     return RecursiveASTVisitor<ResultObjectVisitor>::TraverseDecl(D);
346   }
347 
348   bool TraverseBindingDecl(BindingDecl *BD) {
349     // `RecursiveASTVisitor` doesn't traverse holding variables for
350     // `BindingDecl`s by itself, so we need to tell it to.
351     if (VarDecl *HoldingVar = BD->getHoldingVar())
352       TraverseDecl(HoldingVar);
353     return RecursiveASTVisitor<ResultObjectVisitor>::TraverseBindingDecl(BD);
354   }
355 
356   bool VisitVarDecl(VarDecl *VD) {
357     if (VD->getType()->isRecordType() && VD->hasInit())
358       PropagateResultObject(
359           VD->getInit(),
360           &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*VD)));
361     return true;
362   }
363 
364   bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE) {
365     if (MTE->getType()->isRecordType())
366       PropagateResultObject(
367           MTE->getSubExpr(),
368           &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*MTE)));
369     return true;
370   }
371 
372   bool VisitReturnStmt(ReturnStmt *Return) {
373     Expr *RetValue = Return->getRetValue();
374     if (RetValue != nullptr && RetValue->getType()->isRecordType() &&
375         RetValue->isPRValue())
376       PropagateResultObject(RetValue, LocForRecordReturnVal);
377     return true;
378   }
379 
380   bool VisitExpr(Expr *E) {
381     // Clang's AST can have record-type prvalues without a result object -- for
382     // example as full-expressions contained in a compound statement or as
383     // arguments of call expressions. We notice this if we get here and a
384     // storage location has not yet been associated with `E`. In this case,
385     // treat this as if it was a `MaterializeTemporaryExpr`.
386     if (E->isPRValue() && E->getType()->isRecordType() &&
387         !ResultObjectMap.contains(E))
388       PropagateResultObject(
389           E, &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*E)));
390     return true;
391   }
392 
393   void
394   PropagateResultObjectToRecordInitList(const RecordInitListHelper &InitList,
395                                         RecordStorageLocation *Loc) {
396     for (auto [Base, Init] : InitList.base_inits()) {
397       assert(Base->getType().getCanonicalType() ==
398              Init->getType().getCanonicalType());
399 
400       // Storage location for the base class is the same as that of the
401       // derived class because we "flatten" the object hierarchy and put all
402       // fields in `RecordStorageLocation` of the derived class.
403       PropagateResultObject(Init, Loc);
404     }
405 
406     for (auto [Field, Init] : InitList.field_inits()) {
407       // Fields of non-record type are handled in
408       // `TransferVisitor::VisitInitListExpr()`.
409       if (Field->getType()->isRecordType())
410         PropagateResultObject(
411             Init, cast<RecordStorageLocation>(Loc->getChild(*Field)));
412     }
413   }
414 
415   // Assigns `Loc` as the result object location of `E`, then propagates the
416   // location to all lower-level prvalues that initialize the same object as
417   // `E` (or one of its base classes or member variables).
418   void PropagateResultObject(Expr *E, RecordStorageLocation *Loc) {
419     if (!E->isPRValue() || !E->getType()->isRecordType()) {
420       assert(false);
421       // Ensure we don't propagate the result object if we hit this in a
422       // release build.
423       return;
424     }
425 
426     ResultObjectMap[E] = Loc;
427 
428     // The following AST node kinds are "original initializers": They are the
429     // lowest-level AST node that initializes a given object, and nothing
430     // below them can initialize the same object (or part of it).
431     if (isa<CXXConstructExpr>(E) || isa<CallExpr>(E) || isa<LambdaExpr>(E) ||
432         isa<CXXDefaultArgExpr>(E) || isa<CXXDefaultInitExpr>(E) ||
433         isa<CXXStdInitializerListExpr>(E) ||
434         // We treat `BuiltinBitCastExpr` as an "original initializer" too as
435         // it may not even be casting from a record type -- and even if it is,
436         // the two objects are in general of unrelated type.
437         isa<BuiltinBitCastExpr>(E)) {
438       return;
439     }
440     if (auto *Op = dyn_cast<BinaryOperator>(E);
441         Op && Op->getOpcode() == BO_Cmp) {
442       // Builtin `<=>` returns a `std::strong_ordering` object.
443       return;
444     }
445 
446     if (auto *InitList = dyn_cast<InitListExpr>(E)) {
447       if (!InitList->isSemanticForm())
448         return;
449       if (InitList->isTransparent()) {
450         PropagateResultObject(InitList->getInit(0), Loc);
451         return;
452       }
453 
454       PropagateResultObjectToRecordInitList(RecordInitListHelper(InitList),
455                                             Loc);
456       return;
457     }
458 
459     if (auto *ParenInitList = dyn_cast<CXXParenListInitExpr>(E)) {
460       PropagateResultObjectToRecordInitList(RecordInitListHelper(ParenInitList),
461                                             Loc);
462       return;
463     }
464 
465     if (auto *Op = dyn_cast<BinaryOperator>(E); Op && Op->isCommaOp()) {
466       PropagateResultObject(Op->getRHS(), Loc);
467       return;
468     }
469 
470     if (auto *Cond = dyn_cast<AbstractConditionalOperator>(E)) {
471       PropagateResultObject(Cond->getTrueExpr(), Loc);
472       PropagateResultObject(Cond->getFalseExpr(), Loc);
473       return;
474     }
475 
476     if (auto *SE = dyn_cast<StmtExpr>(E)) {
477       PropagateResultObject(cast<Expr>(SE->getSubStmt()->body_back()), Loc);
478       return;
479     }
480 
481     // All other expression nodes that propagate a record prvalue should have
482     // exactly one child.
483     SmallVector<Stmt *, 1> Children(E->child_begin(), E->child_end());
484     LLVM_DEBUG({
485       if (Children.size() != 1)
486         E->dump();
487     });
488     assert(Children.size() == 1);
489     for (Stmt *S : Children)
490       PropagateResultObject(cast<Expr>(S), Loc);
491   }
492 
493 private:
494   llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap;
495   RecordStorageLocation *LocForRecordReturnVal;
496   DataflowAnalysisContext &DACtx;
497 };
498 
499 } // namespace
500 
501 Environment::Environment(DataflowAnalysisContext &DACtx)
502     : DACtx(&DACtx),
503       FlowConditionToken(DACtx.arena().makeFlowConditionToken()) {}
504 
505 Environment::Environment(DataflowAnalysisContext &DACtx,
506                          const DeclContext &DeclCtx)
507     : Environment(DACtx) {
508   CallStack.push_back(&DeclCtx);
509 }
510 
511 void Environment::initialize() {
512   const DeclContext *DeclCtx = getDeclCtx();
513   if (DeclCtx == nullptr)
514     return;
515 
516   const auto *FuncDecl = dyn_cast<FunctionDecl>(DeclCtx);
517   if (FuncDecl == nullptr)
518     return;
519 
520   assert(FuncDecl->doesThisDeclarationHaveABody());
521 
522   initFieldsGlobalsAndFuncs(FuncDecl);
523 
524   for (const auto *ParamDecl : FuncDecl->parameters()) {
525     assert(ParamDecl != nullptr);
526     setStorageLocation(*ParamDecl, createObject(*ParamDecl, nullptr));
527   }
528 
529   if (FuncDecl->getReturnType()->isRecordType())
530     LocForRecordReturnVal = &cast<RecordStorageLocation>(
531         createStorageLocation(FuncDecl->getReturnType()));
532 
533   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclCtx)) {
534     auto *Parent = MethodDecl->getParent();
535     assert(Parent != nullptr);
536 
537     if (Parent->isLambda()) {
538       for (const auto &Capture : Parent->captures()) {
539         if (Capture.capturesVariable()) {
540           const auto *VarDecl = Capture.getCapturedVar();
541           assert(VarDecl != nullptr);
542           setStorageLocation(*VarDecl, createObject(*VarDecl, nullptr));
543         } else if (Capture.capturesThis()) {
544           const auto *SurroundingMethodDecl =
545               cast<CXXMethodDecl>(DeclCtx->getNonClosureAncestor());
546           QualType ThisPointeeType =
547               SurroundingMethodDecl->getFunctionObjectParameterType();
548           setThisPointeeStorageLocation(
549               cast<RecordStorageLocation>(createObject(ThisPointeeType)));
550         }
551       }
552     } else if (MethodDecl->isImplicitObjectMemberFunction()) {
553       QualType ThisPointeeType = MethodDecl->getFunctionObjectParameterType();
554       auto &ThisLoc =
555           cast<RecordStorageLocation>(createStorageLocation(ThisPointeeType));
556       setThisPointeeStorageLocation(ThisLoc);
557       // Initialize fields of `*this` with values, but only if we're not
558       // analyzing a constructor; after all, it's the constructor's job to do
559       // this (and we want to be able to test that).
560       if (!isa<CXXConstructorDecl>(MethodDecl))
561         initializeFieldsWithValues(ThisLoc);
562     }
563   }
564 
565   // We do this below the handling of `CXXMethodDecl` above so that we can
566   // be sure that the storage location for `this` has been set.
567   ResultObjectMap = std::make_shared<PrValueToResultObject>(
568       buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(),
569                            LocForRecordReturnVal));
570 }
571 
572 // FIXME: Add support for resetting globals after function calls to enable
573 // the implementation of sound analyses.
574 void Environment::initFieldsGlobalsAndFuncs(const FunctionDecl *FuncDecl) {
575   assert(FuncDecl->doesThisDeclarationHaveABody());
576 
577   ReferencedDecls Referenced = getReferencedDecls(*FuncDecl);
578 
579   // These have to be added before the lines that follow to ensure that
580   // `create*` work correctly for structs.
581   DACtx->addModeledFields(Referenced.Fields);
582 
583   for (const VarDecl *D : Referenced.Globals) {
584     if (getStorageLocation(*D) != nullptr)
585       continue;
586 
587     // We don't run transfer functions on the initializers of global variables,
588     // so they won't be associated with a value or storage location. We
589     // therefore intentionally don't pass an initializer to `createObject()`;
590     // in particular, this ensures that `createObject()` will initialize the
591     // fields of record-type variables with values.
592     setStorageLocation(*D, createObject(*D, nullptr));
593   }
594 
595   for (const FunctionDecl *FD : Referenced.Functions) {
596     if (getStorageLocation(*FD) != nullptr)
597       continue;
598     auto &Loc = createStorageLocation(*FD);
599     setStorageLocation(*FD, Loc);
600   }
601 }
602 
603 Environment Environment::fork() const {
604   Environment Copy(*this);
605   Copy.FlowConditionToken = DACtx->forkFlowCondition(FlowConditionToken);
606   return Copy;
607 }
608 
609 bool Environment::canDescend(unsigned MaxDepth,
610                              const DeclContext *Callee) const {
611   return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
612 }
613 
614 Environment Environment::pushCall(const CallExpr *Call) const {
615   Environment Env(*this);
616 
617   if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
618     if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
619       if (!isa<CXXThisExpr>(Arg))
620         Env.ThisPointeeLoc =
621             cast<RecordStorageLocation>(getStorageLocation(*Arg));
622       // Otherwise (when the argument is `this`), retain the current
623       // environment's `ThisPointeeLoc`.
624     }
625   }
626 
627   if (Call->getType()->isRecordType() && Call->isPRValue())
628     Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
629 
630   Env.pushCallInternal(Call->getDirectCallee(),
631                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
632 
633   return Env;
634 }
635 
636 Environment Environment::pushCall(const CXXConstructExpr *Call) const {
637   Environment Env(*this);
638 
639   Env.ThisPointeeLoc = &Env.getResultObjectLocation(*Call);
640   Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
641 
642   Env.pushCallInternal(Call->getConstructor(),
643                        llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
644 
645   return Env;
646 }
647 
648 void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
649                                    ArrayRef<const Expr *> Args) {
650   // Canonicalize to the definition of the function. This ensures that we're
651   // putting arguments into the same `ParamVarDecl`s` that the callee will later
652   // be retrieving them from.
653   assert(FuncDecl->getDefinition() != nullptr);
654   FuncDecl = FuncDecl->getDefinition();
655 
656   CallStack.push_back(FuncDecl);
657 
658   initFieldsGlobalsAndFuncs(FuncDecl);
659 
660   const auto *ParamIt = FuncDecl->param_begin();
661 
662   // FIXME: Parameters don't always map to arguments 1:1; examples include
663   // overloaded operators implemented as member functions, and parameter packs.
664   for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
665     assert(ParamIt != FuncDecl->param_end());
666     const VarDecl *Param = *ParamIt;
667     setStorageLocation(*Param, createObject(*Param, Args[ArgIndex]));
668   }
669 
670   ResultObjectMap = std::make_shared<PrValueToResultObject>(
671       buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(),
672                            LocForRecordReturnVal));
673 }
674 
675 void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) {
676   // We ignore some entries of `CalleeEnv`:
677   // - `DACtx` because is already the same in both
678   // - We don't want the callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or
679   //   `ThisPointeeLoc` because they don't apply to us.
680   // - `DeclToLoc`, `ExprToLoc`, and `ExprToVal` capture information from the
681   //   callee's local scope, so when popping that scope, we do not propagate
682   //   the maps.
683   this->LocToVal = std::move(CalleeEnv.LocToVal);
684   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
685 
686   if (Call->isGLValue()) {
687     if (CalleeEnv.ReturnLoc != nullptr)
688       setStorageLocation(*Call, *CalleeEnv.ReturnLoc);
689   } else if (!Call->getType()->isVoidType()) {
690     if (CalleeEnv.ReturnVal != nullptr)
691       setValue(*Call, *CalleeEnv.ReturnVal);
692   }
693 }
694 
695 void Environment::popCall(const CXXConstructExpr *Call,
696                           const Environment &CalleeEnv) {
697   // See also comment in `popCall(const CallExpr *, const Environment &)` above.
698   this->LocToVal = std::move(CalleeEnv.LocToVal);
699   this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
700 }
701 
702 bool Environment::equivalentTo(const Environment &Other,
703                                Environment::ValueModel &Model) const {
704   assert(DACtx == Other.DACtx);
705 
706   if (ReturnVal != Other.ReturnVal)
707     return false;
708 
709   if (ReturnLoc != Other.ReturnLoc)
710     return false;
711 
712   if (LocForRecordReturnVal != Other.LocForRecordReturnVal)
713     return false;
714 
715   if (ThisPointeeLoc != Other.ThisPointeeLoc)
716     return false;
717 
718   if (DeclToLoc != Other.DeclToLoc)
719     return false;
720 
721   if (ExprToLoc != Other.ExprToLoc)
722     return false;
723 
724   if (!compareKeyToValueMaps(ExprToVal, Other.ExprToVal, *this, Other, Model))
725     return false;
726 
727   if (!compareKeyToValueMaps(LocToVal, Other.LocToVal, *this, Other, Model))
728     return false;
729 
730   return true;
731 }
732 
733 LatticeEffect Environment::widen(const Environment &PrevEnv,
734                                  Environment::ValueModel &Model) {
735   assert(DACtx == PrevEnv.DACtx);
736   assert(ReturnVal == PrevEnv.ReturnVal);
737   assert(ReturnLoc == PrevEnv.ReturnLoc);
738   assert(LocForRecordReturnVal == PrevEnv.LocForRecordReturnVal);
739   assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
740   assert(CallStack == PrevEnv.CallStack);
741   assert(ResultObjectMap == PrevEnv.ResultObjectMap);
742 
743   auto Effect = LatticeEffect::Unchanged;
744 
745   // By the API, `PrevEnv` is a previous version of the environment for the same
746   // block, so we have some guarantees about its shape. In particular, it will
747   // be the result of a join or widen operation on previous values for this
748   // block. For `DeclToLoc`, `ExprToVal`, and `ExprToLoc`, join guarantees that
749   // these maps are subsets of the maps in `PrevEnv`. So, as long as we maintain
750   // this property here, we don't need change their current values to widen.
751   assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
752   assert(ExprToVal.size() <= PrevEnv.ExprToVal.size());
753   assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
754 
755   ExprToVal = widenKeyToValueMap(ExprToVal, PrevEnv.ExprToVal, *this, PrevEnv,
756                                  Model, Effect);
757 
758   LocToVal = widenKeyToValueMap(LocToVal, PrevEnv.LocToVal, *this, PrevEnv,
759                                 Model, Effect);
760   if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
761       ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
762       ExprToVal.size() != PrevEnv.ExprToVal.size() ||
763       LocToVal.size() != PrevEnv.LocToVal.size())
764     Effect = LatticeEffect::Changed;
765 
766   return Effect;
767 }
768 
769 Environment Environment::join(const Environment &EnvA, const Environment &EnvB,
770                               Environment::ValueModel &Model,
771                               ExprJoinBehavior ExprBehavior) {
772   assert(EnvA.DACtx == EnvB.DACtx);
773   assert(EnvA.LocForRecordReturnVal == EnvB.LocForRecordReturnVal);
774   assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc);
775   assert(EnvA.CallStack == EnvB.CallStack);
776   assert(EnvA.ResultObjectMap == EnvB.ResultObjectMap);
777 
778   Environment JoinedEnv(*EnvA.DACtx);
779 
780   JoinedEnv.CallStack = EnvA.CallStack;
781   JoinedEnv.ResultObjectMap = EnvA.ResultObjectMap;
782   JoinedEnv.LocForRecordReturnVal = EnvA.LocForRecordReturnVal;
783   JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc;
784 
785   if (EnvA.CallStack.empty()) {
786     JoinedEnv.ReturnVal = nullptr;
787   } else {
788     // FIXME: Make `CallStack` a vector of `FunctionDecl` so we don't need this
789     // cast.
790     auto *Func = dyn_cast<FunctionDecl>(EnvA.CallStack.back());
791     assert(Func != nullptr);
792     JoinedEnv.ReturnVal =
793         joinValues(Func->getReturnType(), EnvA.ReturnVal, EnvA, EnvB.ReturnVal,
794                    EnvB, JoinedEnv, Model);
795   }
796 
797   if (EnvA.ReturnLoc == EnvB.ReturnLoc)
798     JoinedEnv.ReturnLoc = EnvA.ReturnLoc;
799   else
800     JoinedEnv.ReturnLoc = nullptr;
801 
802   JoinedEnv.DeclToLoc = intersectDeclToLoc(EnvA.DeclToLoc, EnvB.DeclToLoc);
803 
804   // FIXME: update join to detect backedges and simplify the flow condition
805   // accordingly.
806   JoinedEnv.FlowConditionToken = EnvA.DACtx->joinFlowConditions(
807       EnvA.FlowConditionToken, EnvB.FlowConditionToken);
808 
809   JoinedEnv.LocToVal =
810       joinLocToVal(EnvA.LocToVal, EnvB.LocToVal, EnvA, EnvB, JoinedEnv, Model);
811 
812   if (ExprBehavior == KeepExprState) {
813     JoinedEnv.ExprToVal = joinExprMaps(EnvA.ExprToVal, EnvB.ExprToVal);
814     JoinedEnv.ExprToLoc = joinExprMaps(EnvA.ExprToLoc, EnvB.ExprToLoc);
815   }
816 
817   return JoinedEnv;
818 }
819 
820 Value *Environment::joinValues(QualType Ty, Value *Val1,
821                                const Environment &Env1, Value *Val2,
822                                const Environment &Env2, Environment &JoinedEnv,
823                                Environment::ValueModel &Model) {
824   if (Val1 == nullptr || Val2 == nullptr)
825     // We can't say anything about the joined value -- even if one of the values
826     // is non-null, we don't want to simply propagate it, because it would be
827     // too specific: Because the other value is null, that means we have no
828     // information at all about the value (i.e. the value is unconstrained).
829     return nullptr;
830 
831   if (areEquivalentValues(*Val1, *Val2))
832     // Arbitrarily return one of the two values.
833     return Val1;
834 
835   return joinDistinctValues(Ty, *Val1, Env1, *Val2, Env2, JoinedEnv, Model);
836 }
837 
838 StorageLocation &Environment::createStorageLocation(QualType Type) {
839   return DACtx->createStorageLocation(Type);
840 }
841 
842 StorageLocation &Environment::createStorageLocation(const ValueDecl &D) {
843   // Evaluated declarations are always assigned the same storage locations to
844   // ensure that the environment stabilizes across loop iterations. Storage
845   // locations for evaluated declarations are stored in the analysis context.
846   return DACtx->getStableStorageLocation(D);
847 }
848 
849 StorageLocation &Environment::createStorageLocation(const Expr &E) {
850   // Evaluated expressions are always assigned the same storage locations to
851   // ensure that the environment stabilizes across loop iterations. Storage
852   // locations for evaluated expressions are stored in the analysis context.
853   return DACtx->getStableStorageLocation(E);
854 }
855 
856 void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
857   assert(!DeclToLoc.contains(&D));
858   // The only kinds of declarations that may have a "variable" storage location
859   // are declarations of reference type and `BindingDecl`. For all other
860   // declaration, the storage location should be the stable storage location
861   // returned by `createStorageLocation()`.
862   assert(D.getType()->isReferenceType() || isa<BindingDecl>(D) ||
863          &Loc == &createStorageLocation(D));
864   DeclToLoc[&D] = &Loc;
865 }
866 
867 StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const {
868   auto It = DeclToLoc.find(&D);
869   if (It == DeclToLoc.end())
870     return nullptr;
871 
872   StorageLocation *Loc = It->second;
873 
874   return Loc;
875 }
876 
877 void Environment::removeDecl(const ValueDecl &D) { DeclToLoc.erase(&D); }
878 
879 void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
880   // `DeclRefExpr`s to builtin function types aren't glvalues, for some reason,
881   // but we still want to be able to associate a `StorageLocation` with them,
882   // so allow these as an exception.
883   assert(E.isGLValue() ||
884          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
885   const Expr &CanonE = ignoreCFGOmittedNodes(E);
886   assert(!ExprToLoc.contains(&CanonE));
887   ExprToLoc[&CanonE] = &Loc;
888 }
889 
890 StorageLocation *Environment::getStorageLocation(const Expr &E) const {
891   // See comment in `setStorageLocation()`.
892   assert(E.isGLValue() ||
893          E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
894   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
895   return It == ExprToLoc.end() ? nullptr : &*It->second;
896 }
897 
898 RecordStorageLocation &
899 Environment::getResultObjectLocation(const Expr &RecordPRValue) const {
900   assert(RecordPRValue.getType()->isRecordType());
901   assert(RecordPRValue.isPRValue());
902 
903   assert(ResultObjectMap != nullptr);
904   RecordStorageLocation *Loc = ResultObjectMap->lookup(&RecordPRValue);
905   assert(Loc != nullptr);
906   // In release builds, use the "stable" storage location if the map lookup
907   // failed.
908   if (Loc == nullptr)
909     return cast<RecordStorageLocation>(
910         DACtx->getStableStorageLocation(RecordPRValue));
911   return *Loc;
912 }
913 
914 PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
915   return DACtx->getOrCreateNullPointerValue(PointeeType);
916 }
917 
918 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc,
919                                              QualType Type) {
920   llvm::DenseSet<QualType> Visited;
921   int CreatedValuesCount = 0;
922   initializeFieldsWithValues(Loc, Type, Visited, 0, CreatedValuesCount);
923   if (CreatedValuesCount > MaxCompositeValueSize) {
924     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
925                  << '\n';
926   }
927 }
928 
929 void Environment::setValue(const StorageLocation &Loc, Value &Val) {
930   // Records should not be associated with values.
931   assert(!isa<RecordStorageLocation>(Loc));
932   LocToVal[&Loc] = &Val;
933 }
934 
935 void Environment::setValue(const Expr &E, Value &Val) {
936   const Expr &CanonE = ignoreCFGOmittedNodes(E);
937 
938   assert(CanonE.isPRValue());
939   // Records should not be associated with values.
940   assert(!CanonE.getType()->isRecordType());
941   ExprToVal[&CanonE] = &Val;
942 }
943 
944 Value *Environment::getValue(const StorageLocation &Loc) const {
945   // Records should not be associated with values.
946   assert(!isa<RecordStorageLocation>(Loc));
947   return LocToVal.lookup(&Loc);
948 }
949 
950 Value *Environment::getValue(const ValueDecl &D) const {
951   auto *Loc = getStorageLocation(D);
952   if (Loc == nullptr)
953     return nullptr;
954   return getValue(*Loc);
955 }
956 
957 Value *Environment::getValue(const Expr &E) const {
958   // Records should not be associated with values.
959   assert(!E.getType()->isRecordType());
960 
961   if (E.isPRValue()) {
962     auto It = ExprToVal.find(&ignoreCFGOmittedNodes(E));
963     return It == ExprToVal.end() ? nullptr : It->second;
964   }
965 
966   auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
967   if (It == ExprToLoc.end())
968     return nullptr;
969   return getValue(*It->second);
970 }
971 
972 Value *Environment::createValue(QualType Type) {
973   llvm::DenseSet<QualType> Visited;
974   int CreatedValuesCount = 0;
975   Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
976                                                 CreatedValuesCount);
977   if (CreatedValuesCount > MaxCompositeValueSize) {
978     llvm::errs() << "Attempting to initialize a huge value of type: " << Type
979                  << '\n';
980   }
981   return Val;
982 }
983 
984 Value *Environment::createValueUnlessSelfReferential(
985     QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
986     int &CreatedValuesCount) {
987   assert(!Type.isNull());
988   assert(!Type->isReferenceType());
989   assert(!Type->isRecordType());
990 
991   // Allow unlimited fields at depth 1; only cap at deeper nesting levels.
992   if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
993       Depth > MaxCompositeValueDepth)
994     return nullptr;
995 
996   if (Type->isBooleanType()) {
997     CreatedValuesCount++;
998     return &makeAtomicBoolValue();
999   }
1000 
1001   if (Type->isIntegerType()) {
1002     // FIXME: consider instead `return nullptr`, given that we do nothing useful
1003     // with integers, and so distinguishing them serves no purpose, but could
1004     // prevent convergence.
1005     CreatedValuesCount++;
1006     return &arena().create<IntegerValue>();
1007   }
1008 
1009   if (Type->isPointerType()) {
1010     CreatedValuesCount++;
1011     QualType PointeeType = Type->getPointeeType();
1012     StorageLocation &PointeeLoc =
1013         createLocAndMaybeValue(PointeeType, Visited, Depth, CreatedValuesCount);
1014 
1015     return &arena().create<PointerValue>(PointeeLoc);
1016   }
1017 
1018   return nullptr;
1019 }
1020 
1021 StorageLocation &
1022 Environment::createLocAndMaybeValue(QualType Ty,
1023                                     llvm::DenseSet<QualType> &Visited,
1024                                     int Depth, int &CreatedValuesCount) {
1025   if (!Visited.insert(Ty.getCanonicalType()).second)
1026     return createStorageLocation(Ty.getNonReferenceType());
1027   auto EraseVisited = llvm::make_scope_exit(
1028       [&Visited, Ty] { Visited.erase(Ty.getCanonicalType()); });
1029 
1030   Ty = Ty.getNonReferenceType();
1031 
1032   if (Ty->isRecordType()) {
1033     auto &Loc = cast<RecordStorageLocation>(createStorageLocation(Ty));
1034     initializeFieldsWithValues(Loc, Ty, Visited, Depth, CreatedValuesCount);
1035     return Loc;
1036   }
1037 
1038   StorageLocation &Loc = createStorageLocation(Ty);
1039 
1040   if (Value *Val = createValueUnlessSelfReferential(Ty, Visited, Depth,
1041                                                     CreatedValuesCount))
1042     setValue(Loc, *Val);
1043 
1044   return Loc;
1045 }
1046 
1047 void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc,
1048                                              QualType Type,
1049                                              llvm::DenseSet<QualType> &Visited,
1050                                              int Depth,
1051                                              int &CreatedValuesCount) {
1052   auto initField = [&](QualType FieldType, StorageLocation &FieldLoc) {
1053     if (FieldType->isRecordType()) {
1054       auto &FieldRecordLoc = cast<RecordStorageLocation>(FieldLoc);
1055       initializeFieldsWithValues(FieldRecordLoc, FieldRecordLoc.getType(),
1056                                  Visited, Depth + 1, CreatedValuesCount);
1057     } else {
1058       if (getValue(FieldLoc) != nullptr)
1059         return;
1060       if (!Visited.insert(FieldType.getCanonicalType()).second)
1061         return;
1062       if (Value *Val = createValueUnlessSelfReferential(
1063               FieldType, Visited, Depth + 1, CreatedValuesCount))
1064         setValue(FieldLoc, *Val);
1065       Visited.erase(FieldType.getCanonicalType());
1066     }
1067   };
1068 
1069   for (const FieldDecl *Field : DACtx->getModeledFields(Type)) {
1070     assert(Field != nullptr);
1071     QualType FieldType = Field->getType();
1072 
1073     if (FieldType->isReferenceType()) {
1074       Loc.setChild(*Field,
1075                    &createLocAndMaybeValue(FieldType, Visited, Depth + 1,
1076                                            CreatedValuesCount));
1077     } else {
1078       StorageLocation *FieldLoc = Loc.getChild(*Field);
1079       assert(FieldLoc != nullptr);
1080       initField(FieldType, *FieldLoc);
1081     }
1082   }
1083   for (const auto &[FieldName, FieldType] : DACtx->getSyntheticFields(Type)) {
1084     // Synthetic fields cannot have reference type, so we don't need to deal
1085     // with this case.
1086     assert(!FieldType->isReferenceType());
1087     initField(FieldType, Loc.getSyntheticField(FieldName));
1088   }
1089 }
1090 
1091 StorageLocation &Environment::createObjectInternal(const ValueDecl *D,
1092                                                    QualType Ty,
1093                                                    const Expr *InitExpr) {
1094   if (Ty->isReferenceType()) {
1095     // Although variables of reference type always need to be initialized, it
1096     // can happen that we can't see the initializer, so `InitExpr` may still
1097     // be null.
1098     if (InitExpr) {
1099       if (auto *InitExprLoc = getStorageLocation(*InitExpr))
1100         return *InitExprLoc;
1101     }
1102 
1103     // Even though we have an initializer, we might not get an
1104     // InitExprLoc, for example if the InitExpr is a CallExpr for which we
1105     // don't have a function body. In this case, we just invent a storage
1106     // location and value -- it's the best we can do.
1107     return createObjectInternal(D, Ty.getNonReferenceType(), nullptr);
1108   }
1109 
1110   StorageLocation &Loc =
1111       D ? createStorageLocation(*D) : createStorageLocation(Ty);
1112 
1113   if (Ty->isRecordType()) {
1114     auto &RecordLoc = cast<RecordStorageLocation>(Loc);
1115     if (!InitExpr)
1116       initializeFieldsWithValues(RecordLoc);
1117   } else {
1118     Value *Val = nullptr;
1119     if (InitExpr)
1120       // In the (few) cases where an expression is intentionally
1121       // "uninterpreted", `InitExpr` is not associated with a value.  There are
1122       // two ways to handle this situation: propagate the status, so that
1123       // uninterpreted initializers result in uninterpreted variables, or
1124       // provide a default value. We choose the latter so that later refinements
1125       // of the variable can be used for reasoning about the surrounding code.
1126       // For this reason, we let this case be handled by the `createValue()`
1127       // call below.
1128       //
1129       // FIXME. If and when we interpret all language cases, change this to
1130       // assert that `InitExpr` is interpreted, rather than supplying a
1131       // default value (assuming we don't update the environment API to return
1132       // references).
1133       Val = getValue(*InitExpr);
1134     if (!Val)
1135       Val = createValue(Ty);
1136     if (Val)
1137       setValue(Loc, *Val);
1138   }
1139 
1140   return Loc;
1141 }
1142 
1143 void Environment::assume(const Formula &F) {
1144   DACtx->addFlowConditionConstraint(FlowConditionToken, F);
1145 }
1146 
1147 bool Environment::proves(const Formula &F) const {
1148   return DACtx->flowConditionImplies(FlowConditionToken, F);
1149 }
1150 
1151 bool Environment::allows(const Formula &F) const {
1152   return DACtx->flowConditionAllows(FlowConditionToken, F);
1153 }
1154 
1155 void Environment::dump(raw_ostream &OS) const {
1156   llvm::DenseMap<const StorageLocation *, std::string> LocToName;
1157   if (LocForRecordReturnVal != nullptr)
1158     LocToName[LocForRecordReturnVal] = "(returned record)";
1159   if (ThisPointeeLoc != nullptr)
1160     LocToName[ThisPointeeLoc] = "this";
1161 
1162   OS << "DeclToLoc:\n";
1163   for (auto [D, L] : DeclToLoc) {
1164     auto Iter = LocToName.insert({L, D->getNameAsString()}).first;
1165     OS << "  [" << Iter->second << ", " << L << "]\n";
1166   }
1167   OS << "ExprToLoc:\n";
1168   for (auto [E, L] : ExprToLoc)
1169     OS << "  [" << E << ", " << L << "]\n";
1170 
1171   OS << "ExprToVal:\n";
1172   for (auto [E, V] : ExprToVal)
1173     OS << "  [" << E << ", " << V << ": " << *V << "]\n";
1174 
1175   OS << "LocToVal:\n";
1176   for (auto [L, V] : LocToVal) {
1177     OS << "  [" << L;
1178     if (auto Iter = LocToName.find(L); Iter != LocToName.end())
1179       OS << " (" << Iter->second << ")";
1180     OS << ", " << V << ": " << *V << "]\n";
1181   }
1182 
1183   if (const FunctionDecl *Func = getCurrentFunc()) {
1184     if (Func->getReturnType()->isReferenceType()) {
1185       OS << "ReturnLoc: " << ReturnLoc;
1186       if (auto Iter = LocToName.find(ReturnLoc); Iter != LocToName.end())
1187         OS << " (" << Iter->second << ")";
1188       OS << "\n";
1189     } else if (Func->getReturnType()->isRecordType() ||
1190                isa<CXXConstructorDecl>(Func)) {
1191       OS << "LocForRecordReturnVal: " << LocForRecordReturnVal << "\n";
1192     } else if (!Func->getReturnType()->isVoidType()) {
1193       if (ReturnVal == nullptr)
1194         OS << "ReturnVal: nullptr\n";
1195       else
1196         OS << "ReturnVal: " << *ReturnVal << "\n";
1197     }
1198 
1199     if (isa<CXXMethodDecl>(Func)) {
1200       OS << "ThisPointeeLoc: " << ThisPointeeLoc << "\n";
1201     }
1202   }
1203 
1204   OS << "\n";
1205   DACtx->dumpFlowCondition(FlowConditionToken, OS);
1206 }
1207 
1208 void Environment::dump() const { dump(llvm::dbgs()); }
1209 
1210 Environment::PrValueToResultObject Environment::buildResultObjectMap(
1211     DataflowAnalysisContext *DACtx, const FunctionDecl *FuncDecl,
1212     RecordStorageLocation *ThisPointeeLoc,
1213     RecordStorageLocation *LocForRecordReturnVal) {
1214   assert(FuncDecl->doesThisDeclarationHaveABody());
1215 
1216   PrValueToResultObject Map;
1217 
1218   ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx);
1219   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl))
1220     Visitor.TraverseConstructorInits(Ctor, ThisPointeeLoc);
1221   Visitor.TraverseStmt(FuncDecl->getBody());
1222 
1223   return Map;
1224 }
1225 
1226 RecordStorageLocation *getImplicitObjectLocation(const CXXMemberCallExpr &MCE,
1227                                                  const Environment &Env) {
1228   Expr *ImplicitObject = MCE.getImplicitObjectArgument();
1229   if (ImplicitObject == nullptr)
1230     return nullptr;
1231   if (ImplicitObject->getType()->isPointerType()) {
1232     if (auto *Val = Env.get<PointerValue>(*ImplicitObject))
1233       return &cast<RecordStorageLocation>(Val->getPointeeLoc());
1234     return nullptr;
1235   }
1236   return cast_or_null<RecordStorageLocation>(
1237       Env.getStorageLocation(*ImplicitObject));
1238 }
1239 
1240 RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME,
1241                                              const Environment &Env) {
1242   Expr *Base = ME.getBase();
1243   if (Base == nullptr)
1244     return nullptr;
1245   if (ME.isArrow()) {
1246     if (auto *Val = Env.get<PointerValue>(*Base))
1247       return &cast<RecordStorageLocation>(Val->getPointeeLoc());
1248     return nullptr;
1249   }
1250   return Env.get<RecordStorageLocation>(*Base);
1251 }
1252 
1253 } // namespace dataflow
1254 } // namespace clang
1255