1 //===-- UncheckedOptionalAccessModel.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 a dataflow analysis that detects unsafe uses of optional
10 //  values.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/Stmt.h"
20 #include "clang/ASTMatchers/ASTMatchers.h"
21 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
22 #include "clang/Analysis/FlowSensitive/MatchSwitch.h"
23 #include "clang/Analysis/FlowSensitive/SourceLocationsLattice.h"
24 #include "clang/Analysis/FlowSensitive/Value.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Casting.h"
27 #include <cassert>
28 #include <memory>
29 #include <utility>
30 
31 namespace clang {
32 namespace dataflow {
33 namespace {
34 
35 using namespace ::clang::ast_matchers;
36 using LatticeTransferState = TransferState<SourceLocationsLattice>;
37 
38 DeclarationMatcher optionalClass() {
39   return classTemplateSpecializationDecl(
40       anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
41             hasName("__optional_destruct_base"), hasName("absl::optional"),
42             hasName("base::Optional")),
43       hasTemplateArgument(0, refersToType(type().bind("T"))));
44 }
45 
46 auto optionalOrAliasType() {
47   return hasUnqualifiedDesugaredType(
48       recordType(hasDeclaration(optionalClass())));
49 }
50 
51 /// Matches any of the spellings of the optional types and sugar, aliases, etc.
52 auto hasOptionalType() { return hasType(optionalOrAliasType()); }
53 
54 auto isOptionalMemberCallWithName(
55     llvm::StringRef MemberName,
56     llvm::Optional<StatementMatcher> Ignorable = llvm::None) {
57   auto Exception = unless(Ignorable ? expr(anyOf(*Ignorable, cxxThisExpr()))
58                                     : cxxThisExpr());
59   return cxxMemberCallExpr(
60       on(expr(Exception)),
61       callee(cxxMethodDecl(hasName(MemberName), ofClass(optionalClass()))));
62 }
63 
64 auto isOptionalOperatorCallWithName(
65     llvm::StringRef operator_name,
66     llvm::Optional<StatementMatcher> Ignorable = llvm::None) {
67   return cxxOperatorCallExpr(
68       hasOverloadedOperatorName(operator_name),
69       callee(cxxMethodDecl(ofClass(optionalClass()))),
70       Ignorable ? callExpr(unless(hasArgument(0, *Ignorable))) : callExpr());
71 }
72 
73 auto isMakeOptionalCall() {
74   return callExpr(
75       callee(functionDecl(hasAnyName(
76           "std::make_optional", "base::make_optional", "absl::make_optional"))),
77       hasOptionalType());
78 }
79 
80 auto hasNulloptType() {
81   return hasType(namedDecl(
82       hasAnyName("std::nullopt_t", "absl::nullopt_t", "base::nullopt_t")));
83 }
84 
85 auto inPlaceClass() {
86   return recordDecl(
87       hasAnyName("std::in_place_t", "absl::in_place_t", "base::in_place_t"));
88 }
89 
90 auto isOptionalNulloptConstructor() {
91   return cxxConstructExpr(hasOptionalType(), argumentCountIs(1),
92                           hasArgument(0, hasNulloptType()));
93 }
94 
95 auto isOptionalInPlaceConstructor() {
96   return cxxConstructExpr(hasOptionalType(),
97                           hasArgument(0, hasType(inPlaceClass())));
98 }
99 
100 auto isOptionalValueOrConversionConstructor() {
101   return cxxConstructExpr(
102       hasOptionalType(),
103       unless(hasDeclaration(
104           cxxConstructorDecl(anyOf(isCopyConstructor(), isMoveConstructor())))),
105       argumentCountIs(1), hasArgument(0, unless(hasNulloptType())));
106 }
107 
108 auto isOptionalValueOrConversionAssignment() {
109   return cxxOperatorCallExpr(
110       hasOverloadedOperatorName("="),
111       callee(cxxMethodDecl(ofClass(optionalClass()))),
112       unless(hasDeclaration(cxxMethodDecl(
113           anyOf(isCopyAssignmentOperator(), isMoveAssignmentOperator())))),
114       argumentCountIs(2), hasArgument(1, unless(hasNulloptType())));
115 }
116 
117 auto isOptionalNulloptAssignment() {
118   return cxxOperatorCallExpr(hasOverloadedOperatorName("="),
119                              callee(cxxMethodDecl(ofClass(optionalClass()))),
120                              argumentCountIs(2),
121                              hasArgument(1, hasNulloptType()));
122 }
123 
124 auto isStdSwapCall() {
125   return callExpr(callee(functionDecl(hasName("std::swap"))),
126                   argumentCountIs(2), hasArgument(0, hasOptionalType()),
127                   hasArgument(1, hasOptionalType()));
128 }
129 
130 constexpr llvm::StringLiteral ValueOrCallID = "ValueOrCall";
131 
132 auto isValueOrStringEmptyCall() {
133   // `opt.value_or("").empty()`
134   return cxxMemberCallExpr(
135       callee(cxxMethodDecl(hasName("empty"))),
136       onImplicitObjectArgument(ignoringImplicit(
137           cxxMemberCallExpr(on(expr(unless(cxxThisExpr()))),
138                             callee(cxxMethodDecl(hasName("value_or"),
139                                                  ofClass(optionalClass()))),
140                             hasArgument(0, stringLiteral(hasSize(0))))
141               .bind(ValueOrCallID))));
142 }
143 
144 auto isValueOrNotEqX() {
145   auto ComparesToSame = [](ast_matchers::internal::Matcher<Stmt> Arg) {
146     return hasOperands(
147         ignoringImplicit(
148             cxxMemberCallExpr(on(expr(unless(cxxThisExpr()))),
149                               callee(cxxMethodDecl(hasName("value_or"),
150                                                    ofClass(optionalClass()))),
151                               hasArgument(0, Arg))
152                 .bind(ValueOrCallID)),
153         ignoringImplicit(Arg));
154   };
155 
156   // `opt.value_or(X) != X`, for X is `nullptr`, `""`, or `0`. Ideally, we'd
157   // support this pattern for any expression, but the AST does not have a
158   // generic expression comparison facility, so we specialize to common cases
159   // seen in practice.  FIXME: define a matcher that compares values across
160   // nodes, which would let us generalize this to any `X`.
161   return binaryOperation(hasOperatorName("!="),
162                          anyOf(ComparesToSame(cxxNullPtrLiteralExpr()),
163                                ComparesToSame(stringLiteral(hasSize(0))),
164                                ComparesToSame(integerLiteral(equals(0)))));
165 }
166 
167 auto isCallReturningOptional() {
168   return callExpr(hasType(qualType(anyOf(
169       optionalOrAliasType(), referenceType(pointee(optionalOrAliasType()))))));
170 }
171 
172 /// Creates a symbolic value for an `optional` value using `HasValueVal` as the
173 /// symbolic value of its "has_value" property.
174 StructValue &createOptionalValue(Environment &Env, BoolValue &HasValueVal) {
175   auto OptionalVal = std::make_unique<StructValue>();
176   OptionalVal->setProperty("has_value", HasValueVal);
177   return Env.takeOwnership(std::move(OptionalVal));
178 }
179 
180 /// Returns the symbolic value that represents the "has_value" property of the
181 /// optional value `OptionalVal`. Returns null if `OptionalVal` is null.
182 BoolValue *getHasValue(Environment &Env, Value *OptionalVal) {
183   if (OptionalVal != nullptr) {
184     auto *HasValueVal =
185         cast_or_null<BoolValue>(OptionalVal->getProperty("has_value"));
186     if (HasValueVal == nullptr) {
187       HasValueVal = &Env.makeAtomicBoolValue();
188       OptionalVal->setProperty("has_value", *HasValueVal);
189     }
190     return HasValueVal;
191   }
192   return nullptr;
193 }
194 
195 /// If `Type` is a reference type, returns the type of its pointee. Otherwise,
196 /// returns `Type` itself.
197 QualType stripReference(QualType Type) {
198   return Type->isReferenceType() ? Type->getPointeeType() : Type;
199 }
200 
201 /// Returns true if and only if `Type` is an optional type.
202 bool IsOptionalType(QualType Type) {
203   if (!Type->isRecordType())
204     return false;
205   // FIXME: Optimize this by avoiding the `getQualifiedNameAsString` call.
206   auto TypeName = Type->getAsCXXRecordDecl()->getQualifiedNameAsString();
207   return TypeName == "std::optional" || TypeName == "absl::optional" ||
208          TypeName == "base::Optional";
209 }
210 
211 /// Returns the number of optional wrappers in `Type`.
212 ///
213 /// For example, if `Type` is `optional<optional<int>>`, the result of this
214 /// function will be 2.
215 int countOptionalWrappers(const ASTContext &ASTCtx, QualType Type) {
216   if (!IsOptionalType(Type))
217     return 0;
218   return 1 + countOptionalWrappers(
219                  ASTCtx,
220                  cast<ClassTemplateSpecializationDecl>(Type->getAsRecordDecl())
221                      ->getTemplateArgs()
222                      .get(0)
223                      .getAsType()
224                      .getDesugaredType(ASTCtx));
225 }
226 
227 /// Tries to initialize the `optional`'s value (that is, contents), and return
228 /// its location. Returns nullptr if the value can't be represented.
229 StorageLocation *maybeInitializeOptionalValueMember(QualType Q,
230                                                     Value &OptionalVal,
231                                                     Environment &Env) {
232   // The "value" property represents a synthetic field. As such, it needs
233   // `StorageLocation`, like normal fields (and other variables). So, we model
234   // it with a `ReferenceValue`, since that includes a storage location.  Once
235   // the property is set, it will be shared by all environments that access the
236   // `Value` representing the optional (here, `OptionalVal`).
237   if (auto *ValueProp = OptionalVal.getProperty("value")) {
238     auto *ValueRef = clang::cast<ReferenceValue>(ValueProp);
239     auto &ValueLoc = ValueRef->getPointeeLoc();
240     if (Env.getValue(ValueLoc) == nullptr) {
241       // The property was previously set, but the value has been lost. This can
242       // happen, for example, because of an environment merge (where the two
243       // environments mapped the property to different values, which resulted in
244       // them both being discarded), or when two blocks in the CFG, with neither
245       // a dominator of the other, visit the same optional value, or even when a
246       // block is revisited during testing to collect per-statement state.
247       // FIXME: This situation means that the optional contents are not shared
248       // between branches and the like. Practically, this lack of sharing
249       // reduces the precision of the model when the contents are relevant to
250       // the check, like another optional or a boolean that influences control
251       // flow.
252       auto *ValueVal = Env.createValue(ValueLoc.getType());
253       if (ValueVal == nullptr)
254         return nullptr;
255       Env.setValue(ValueLoc, *ValueVal);
256     }
257     return &ValueLoc;
258   }
259 
260   auto Ty = stripReference(Q);
261   auto *ValueVal = Env.createValue(Ty);
262   if (ValueVal == nullptr)
263     return nullptr;
264   auto &ValueLoc = Env.createStorageLocation(Ty);
265   Env.setValue(ValueLoc, *ValueVal);
266   auto ValueRef = std::make_unique<ReferenceValue>(ValueLoc);
267   OptionalVal.setProperty("value", Env.takeOwnership(std::move(ValueRef)));
268   return &ValueLoc;
269 }
270 
271 void initializeOptionalReference(const Expr *OptionalExpr,
272                                  const MatchFinder::MatchResult &,
273                                  LatticeTransferState &State) {
274   if (auto *OptionalVal =
275           State.Env.getValue(*OptionalExpr, SkipPast::Reference)) {
276     if (OptionalVal->getProperty("has_value") == nullptr) {
277       OptionalVal->setProperty("has_value", State.Env.makeAtomicBoolValue());
278     }
279   }
280 }
281 
282 void transferUnwrapCall(const Expr *UnwrapExpr, const Expr *ObjectExpr,
283                         LatticeTransferState &State) {
284   if (auto *OptionalVal =
285           State.Env.getValue(*ObjectExpr, SkipPast::ReferenceThenPointer)) {
286     if (State.Env.getStorageLocation(*UnwrapExpr, SkipPast::None) == nullptr)
287       if (auto *Loc = maybeInitializeOptionalValueMember(
288               UnwrapExpr->getType(), *OptionalVal, State.Env))
289         State.Env.setStorageLocation(*UnwrapExpr, *Loc);
290 
291     auto *Prop = OptionalVal->getProperty("has_value");
292     if (auto *HasValueVal = cast_or_null<BoolValue>(Prop)) {
293       if (State.Env.flowConditionImplies(*HasValueVal))
294         return;
295     }
296   }
297 
298   // Record that this unwrap is *not* provably safe.
299   // FIXME: include either the name of the optional (if applicable) or a source
300   // range of the access for easier interpretation of the result.
301   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
302 }
303 
304 void transferMakeOptionalCall(const CallExpr *E,
305                               const MatchFinder::MatchResult &,
306                               LatticeTransferState &State) {
307   auto &Loc = State.Env.createStorageLocation(*E);
308   State.Env.setStorageLocation(*E, Loc);
309   State.Env.setValue(
310       Loc, createOptionalValue(State.Env, State.Env.getBoolLiteralValue(true)));
311 }
312 
313 void transferOptionalHasValueCall(const CXXMemberCallExpr *CallExpr,
314                                   const MatchFinder::MatchResult &,
315                                   LatticeTransferState &State) {
316   if (auto *HasValueVal = getHasValue(
317           State.Env, State.Env.getValue(*CallExpr->getImplicitObjectArgument(),
318                                         SkipPast::ReferenceThenPointer))) {
319     auto &CallExprLoc = State.Env.createStorageLocation(*CallExpr);
320     State.Env.setValue(CallExprLoc, *HasValueVal);
321     State.Env.setStorageLocation(*CallExpr, CallExprLoc);
322   }
323 }
324 
325 /// `ModelPred` builds a logical formula relating the predicate in
326 /// `ValueOrPredExpr` to the optional's `has_value` property.
327 void transferValueOrImpl(const clang::Expr *ValueOrPredExpr,
328                          const MatchFinder::MatchResult &Result,
329                          LatticeTransferState &State,
330                          BoolValue &(*ModelPred)(Environment &Env,
331                                                  BoolValue &ExprVal,
332                                                  BoolValue &HasValueVal)) {
333   auto &Env = State.Env;
334 
335   const auto *ObjectArgumentExpr =
336       Result.Nodes.getNodeAs<clang::CXXMemberCallExpr>(ValueOrCallID)
337           ->getImplicitObjectArgument();
338 
339   auto *HasValueVal = getHasValue(
340       State.Env,
341       State.Env.getValue(*ObjectArgumentExpr, SkipPast::ReferenceThenPointer));
342   if (HasValueVal == nullptr)
343     return;
344 
345   auto *ExprValue = cast_or_null<BoolValue>(
346       State.Env.getValue(*ValueOrPredExpr, SkipPast::None));
347   if (ExprValue == nullptr) {
348     auto &ExprLoc = State.Env.createStorageLocation(*ValueOrPredExpr);
349     ExprValue = &State.Env.makeAtomicBoolValue();
350     State.Env.setValue(ExprLoc, *ExprValue);
351     State.Env.setStorageLocation(*ValueOrPredExpr, ExprLoc);
352   }
353 
354   Env.addToFlowCondition(ModelPred(Env, *ExprValue, *HasValueVal));
355 }
356 
357 void transferValueOrStringEmptyCall(const clang::Expr *ComparisonExpr,
358                                     const MatchFinder::MatchResult &Result,
359                                     LatticeTransferState &State) {
360   return transferValueOrImpl(ComparisonExpr, Result, State,
361                              [](Environment &Env, BoolValue &ExprVal,
362                                 BoolValue &HasValueVal) -> BoolValue & {
363                                // If the result is *not* empty, then we know the
364                                // optional must have been holding a value. If
365                                // `ExprVal` is true, though, we don't learn
366                                // anything definite about `has_value`, so we
367                                // don't add any corresponding implications to
368                                // the flow condition.
369                                return Env.makeImplication(Env.makeNot(ExprVal),
370                                                           HasValueVal);
371                              });
372 }
373 
374 void transferValueOrNotEqX(const Expr *ComparisonExpr,
375                            const MatchFinder::MatchResult &Result,
376                            LatticeTransferState &State) {
377   transferValueOrImpl(ComparisonExpr, Result, State,
378                       [](Environment &Env, BoolValue &ExprVal,
379                          BoolValue &HasValueVal) -> BoolValue & {
380                         // We know that if `(opt.value_or(X) != X)` then
381                         // `opt.hasValue()`, even without knowing further
382                         // details about the contents of `opt`.
383                         return Env.makeImplication(ExprVal, HasValueVal);
384                       });
385 }
386 
387 void transferCallReturningOptional(const CallExpr *E,
388                                    const MatchFinder::MatchResult &Result,
389                                    LatticeTransferState &State) {
390   if (State.Env.getStorageLocation(*E, SkipPast::None) != nullptr)
391     return;
392 
393   auto &Loc = State.Env.createStorageLocation(*E);
394   State.Env.setStorageLocation(*E, Loc);
395   State.Env.setValue(
396       Loc, createOptionalValue(State.Env, State.Env.makeAtomicBoolValue()));
397 }
398 
399 void assignOptionalValue(const Expr &E, LatticeTransferState &State,
400                          BoolValue &HasValueVal) {
401   if (auto *OptionalLoc =
402           State.Env.getStorageLocation(E, SkipPast::ReferenceThenPointer)) {
403     State.Env.setValue(*OptionalLoc,
404                        createOptionalValue(State.Env, HasValueVal));
405   }
406 }
407 
408 /// Returns a symbolic value for the "has_value" property of an `optional<T>`
409 /// value that is constructed/assigned from a value of type `U` or `optional<U>`
410 /// where `T` is constructible from `U`.
411 BoolValue &
412 getValueOrConversionHasValue(const FunctionDecl &F, const Expr &E,
413                              const MatchFinder::MatchResult &MatchRes,
414                              LatticeTransferState &State) {
415   assert(F.getTemplateSpecializationArgs()->size() > 0);
416 
417   const int TemplateParamOptionalWrappersCount = countOptionalWrappers(
418       *MatchRes.Context,
419       stripReference(F.getTemplateSpecializationArgs()->get(0).getAsType()));
420   const int ArgTypeOptionalWrappersCount =
421       countOptionalWrappers(*MatchRes.Context, stripReference(E.getType()));
422 
423   // Check if this is a constructor/assignment call for `optional<T>` with
424   // argument of type `U` such that `T` is constructible from `U`.
425   if (TemplateParamOptionalWrappersCount == ArgTypeOptionalWrappersCount)
426     return State.Env.getBoolLiteralValue(true);
427 
428   // This is a constructor/assignment call for `optional<T>` with argument of
429   // type `optional<U>` such that `T` is constructible from `U`.
430   if (auto *HasValueVal =
431           getHasValue(State.Env, State.Env.getValue(E, SkipPast::Reference)))
432     return *HasValueVal;
433   return State.Env.makeAtomicBoolValue();
434 }
435 
436 void transferValueOrConversionConstructor(
437     const CXXConstructExpr *E, const MatchFinder::MatchResult &MatchRes,
438     LatticeTransferState &State) {
439   assert(E->getNumArgs() > 0);
440 
441   assignOptionalValue(*E, State,
442                       getValueOrConversionHasValue(*E->getConstructor(),
443                                                    *E->getArg(0), MatchRes,
444                                                    State));
445 }
446 
447 void transferAssignment(const CXXOperatorCallExpr *E, BoolValue &HasValueVal,
448                         LatticeTransferState &State) {
449   assert(E->getNumArgs() > 0);
450 
451   auto *OptionalLoc =
452       State.Env.getStorageLocation(*E->getArg(0), SkipPast::Reference);
453   if (OptionalLoc == nullptr)
454     return;
455 
456   State.Env.setValue(*OptionalLoc, createOptionalValue(State.Env, HasValueVal));
457 
458   // Assign a storage location for the whole expression.
459   State.Env.setStorageLocation(*E, *OptionalLoc);
460 }
461 
462 void transferValueOrConversionAssignment(
463     const CXXOperatorCallExpr *E, const MatchFinder::MatchResult &MatchRes,
464     LatticeTransferState &State) {
465   assert(E->getNumArgs() > 1);
466   transferAssignment(E,
467                      getValueOrConversionHasValue(
468                          *E->getDirectCallee(), *E->getArg(1), MatchRes, State),
469                      State);
470 }
471 
472 void transferNulloptAssignment(const CXXOperatorCallExpr *E,
473                                const MatchFinder::MatchResult &,
474                                LatticeTransferState &State) {
475   transferAssignment(E, State.Env.getBoolLiteralValue(false), State);
476 }
477 
478 void transferSwap(const StorageLocation &OptionalLoc1,
479                   const StorageLocation &OptionalLoc2,
480                   LatticeTransferState &State) {
481   auto *OptionalVal1 = State.Env.getValue(OptionalLoc1);
482   assert(OptionalVal1 != nullptr);
483 
484   auto *OptionalVal2 = State.Env.getValue(OptionalLoc2);
485   assert(OptionalVal2 != nullptr);
486 
487   State.Env.setValue(OptionalLoc1, *OptionalVal2);
488   State.Env.setValue(OptionalLoc2, *OptionalVal1);
489 }
490 
491 void transferSwapCall(const CXXMemberCallExpr *E,
492                       const MatchFinder::MatchResult &,
493                       LatticeTransferState &State) {
494   assert(E->getNumArgs() == 1);
495 
496   auto *OptionalLoc1 = State.Env.getStorageLocation(
497       *E->getImplicitObjectArgument(), SkipPast::ReferenceThenPointer);
498   assert(OptionalLoc1 != nullptr);
499 
500   auto *OptionalLoc2 =
501       State.Env.getStorageLocation(*E->getArg(0), SkipPast::Reference);
502   assert(OptionalLoc2 != nullptr);
503 
504   transferSwap(*OptionalLoc1, *OptionalLoc2, State);
505 }
506 
507 void transferStdSwapCall(const CallExpr *E, const MatchFinder::MatchResult &,
508                          LatticeTransferState &State) {
509   assert(E->getNumArgs() == 2);
510 
511   auto *OptionalLoc1 =
512       State.Env.getStorageLocation(*E->getArg(0), SkipPast::Reference);
513   assert(OptionalLoc1 != nullptr);
514 
515   auto *OptionalLoc2 =
516       State.Env.getStorageLocation(*E->getArg(1), SkipPast::Reference);
517   assert(OptionalLoc2 != nullptr);
518 
519   transferSwap(*OptionalLoc1, *OptionalLoc2, State);
520 }
521 
522 llvm::Optional<StatementMatcher>
523 ignorableOptional(const UncheckedOptionalAccessModelOptions &Options) {
524   if (Options.IgnoreSmartPointerDereference)
525     return memberExpr(hasObjectExpression(ignoringParenImpCasts(
526         cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName("->"),
527                                   hasOverloadedOperatorName("*")),
528                             unless(hasArgument(0, expr(hasOptionalType())))))));
529   return llvm::None;
530 }
531 
532 auto buildTransferMatchSwitch(
533     const UncheckedOptionalAccessModelOptions &Options) {
534   // FIXME: Evaluate the efficiency of matchers. If using matchers results in a
535   // lot of duplicated work (e.g. string comparisons), consider providing APIs
536   // that avoid it through memoization.
537   auto IgnorableOptional = ignorableOptional(Options);
538   return MatchSwitchBuilder<LatticeTransferState>()
539       // Attach a symbolic "has_value" state to optional values that we see for
540       // the first time.
541       .CaseOf<Expr>(
542           expr(anyOf(declRefExpr(), memberExpr()), hasOptionalType()),
543           initializeOptionalReference)
544 
545       // make_optional
546       .CaseOf<CallExpr>(isMakeOptionalCall(), transferMakeOptionalCall)
547 
548       // optional::optional
549       .CaseOf<CXXConstructExpr>(
550           isOptionalInPlaceConstructor(),
551           [](const CXXConstructExpr *E, const MatchFinder::MatchResult &,
552              LatticeTransferState &State) {
553             assignOptionalValue(*E, State, State.Env.getBoolLiteralValue(true));
554           })
555       .CaseOf<CXXConstructExpr>(
556           isOptionalNulloptConstructor(),
557           [](const CXXConstructExpr *E, const MatchFinder::MatchResult &,
558              LatticeTransferState &State) {
559             assignOptionalValue(*E, State,
560                                 State.Env.getBoolLiteralValue(false));
561           })
562       .CaseOf<CXXConstructExpr>(isOptionalValueOrConversionConstructor(),
563                                 transferValueOrConversionConstructor)
564 
565       // optional::operator=
566       .CaseOf<CXXOperatorCallExpr>(isOptionalValueOrConversionAssignment(),
567                                    transferValueOrConversionAssignment)
568       .CaseOf<CXXOperatorCallExpr>(isOptionalNulloptAssignment(),
569                                    transferNulloptAssignment)
570 
571       // optional::value
572       .CaseOf<CXXMemberCallExpr>(
573           isOptionalMemberCallWithName("value", IgnorableOptional),
574           [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &,
575              LatticeTransferState &State) {
576             transferUnwrapCall(E, E->getImplicitObjectArgument(), State);
577           })
578 
579       // optional::operator*, optional::operator->
580       .CaseOf<CallExpr>(
581           expr(anyOf(isOptionalOperatorCallWithName("*", IgnorableOptional),
582                      isOptionalOperatorCallWithName("->", IgnorableOptional))),
583           [](const CallExpr *E, const MatchFinder::MatchResult &,
584              LatticeTransferState &State) {
585             transferUnwrapCall(E, E->getArg(0), State);
586           })
587 
588       // optional::has_value
589       .CaseOf<CXXMemberCallExpr>(isOptionalMemberCallWithName("has_value"),
590                                  transferOptionalHasValueCall)
591 
592       // optional::operator bool
593       .CaseOf<CXXMemberCallExpr>(isOptionalMemberCallWithName("operator bool"),
594                                  transferOptionalHasValueCall)
595 
596       // optional::emplace
597       .CaseOf<CXXMemberCallExpr>(
598           isOptionalMemberCallWithName("emplace"),
599           [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &,
600              LatticeTransferState &State) {
601             assignOptionalValue(*E->getImplicitObjectArgument(), State,
602                                 State.Env.getBoolLiteralValue(true));
603           })
604 
605       // optional::reset
606       .CaseOf<CXXMemberCallExpr>(
607           isOptionalMemberCallWithName("reset"),
608           [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &,
609              LatticeTransferState &State) {
610             assignOptionalValue(*E->getImplicitObjectArgument(), State,
611                                 State.Env.getBoolLiteralValue(false));
612           })
613 
614       // optional::swap
615       .CaseOf<CXXMemberCallExpr>(isOptionalMemberCallWithName("swap"),
616                                  transferSwapCall)
617 
618       // std::swap
619       .CaseOf<CallExpr>(isStdSwapCall(), transferStdSwapCall)
620 
621       // opt.value_or("").empty()
622       .CaseOf<Expr>(isValueOrStringEmptyCall(), transferValueOrStringEmptyCall)
623 
624       // opt.value_or(X) != X
625       .CaseOf<Expr>(isValueOrNotEqX(), transferValueOrNotEqX)
626 
627       // returns optional
628       .CaseOf<CallExpr>(isCallReturningOptional(),
629                         transferCallReturningOptional)
630 
631       .Build();
632 }
633 
634 } // namespace
635 
636 ast_matchers::DeclarationMatcher
637 UncheckedOptionalAccessModel::optionalClassDecl() {
638   return optionalClass();
639 }
640 
641 UncheckedOptionalAccessModel::UncheckedOptionalAccessModel(
642     ASTContext &Ctx, UncheckedOptionalAccessModelOptions Options)
643     : DataflowAnalysis<UncheckedOptionalAccessModel, SourceLocationsLattice>(
644           Ctx),
645       TransferMatchSwitch(buildTransferMatchSwitch(Options)) {}
646 
647 void UncheckedOptionalAccessModel::transfer(const Stmt *S,
648                                             SourceLocationsLattice &L,
649                                             Environment &Env) {
650   LatticeTransferState State(L, Env);
651   TransferMatchSwitch(*S, getASTContext(), State);
652 }
653 
654 } // namespace dataflow
655 } // namespace clang
656