clang 23.0.0git
CheckExprLifetime.cpp
Go to the documentation of this file.
1//===--- CheckExprLifetime.cpp --------------------------------------------===//
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#include "CheckExprLifetime.h"
10#include "clang/AST/Decl.h"
11#include "clang/AST/Expr.h"
12#include "clang/AST/Type.h"
16#include "clang/Sema/Sema.h"
17#include "llvm/ADT/PointerIntPair.h"
18
19namespace clang::sema {
22
23namespace {
24enum LifetimeKind {
25 /// The lifetime of a temporary bound to this entity ends at the end of the
26 /// full-expression, and that's (probably) fine.
27 LK_FullExpression,
28
29 /// The lifetime of a temporary bound to this entity is extended to the
30 /// lifeitme of the entity itself.
31 LK_Extended,
32
33 /// The lifetime of a temporary bound to this entity probably ends too soon,
34 /// because the entity is allocated in a new-expression.
35 LK_New,
36
37 /// The lifetime of a temporary bound to this entity ends too soon, because
38 /// the entity is a return object.
39 LK_Return,
40
41 /// The lifetime of a temporary bound to this entity ends too soon, because
42 /// the entity passed to a musttail function call.
43 LK_MustTail,
44
45 /// The lifetime of a temporary bound to this entity ends too soon, because
46 /// the entity is the result of a statement expression.
47 LK_StmtExprResult,
48
49 /// This is a mem-initializer: if it would extend a temporary (other than via
50 /// a default member initializer), the program is ill-formed.
51 LK_MemInitializer,
52
53 /// The lifetime of a temporary bound to this entity may end too soon,
54 /// because the entity is a pointer and we assign the address of a temporary
55 /// object to it.
56 LK_Assignment,
57
58 /// The lifetime of a temporary bound to this entity may end too soon,
59 /// because the entity may capture the reference to a temporary object.
60 LK_LifetimeCapture,
61};
62using LifetimeResult =
63 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
64} // namespace
65
66/// Determine the declaration which an initialized entity ultimately refers to,
67/// for the purpose of lifetime-extending a temporary bound to a reference in
68/// the initialization of \p Entity.
69static LifetimeResult
71 const InitializedEntity *InitField = nullptr) {
72 // C++11 [class.temporary]p5:
73 switch (Entity->getKind()) {
75 // The temporary [...] persists for the lifetime of the reference
76 return {Entity, LK_Extended};
77
79 // For subobjects, we look at the complete object.
80 if (Entity->getParent())
81 return getEntityLifetime(Entity->getParent(), Entity);
82
83 // except:
84 // C++17 [class.base.init]p8:
85 // A temporary expression bound to a reference member in a
86 // mem-initializer is ill-formed.
87 // C++17 [class.base.init]p11:
88 // A temporary expression bound to a reference member from a
89 // default member initializer is ill-formed.
90 //
91 // The context of p11 and its example suggest that it's only the use of a
92 // default member initializer from a constructor that makes the program
93 // ill-formed, not its mere existence, and that it can even be used by
94 // aggregate initialization.
95 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
96 : LK_MemInitializer};
97
99 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
100 // type.
101 return {Entity, LK_Extended};
102
105 // -- A temporary bound to a reference parameter in a function call
106 // persists until the completion of the full-expression containing
107 // the call.
108 return {nullptr, LK_FullExpression};
109
111 // FIXME: This will always be ill-formed; should we eagerly diagnose it
112 // here?
113 return {nullptr, LK_FullExpression};
114
116 // -- The lifetime of a temporary bound to the returned value in a
117 // function return statement is not extended; the temporary is
118 // destroyed at the end of the full-expression in the return statement.
119 return {nullptr, LK_Return};
120
122 // FIXME: Should we lifetime-extend through the result of a statement
123 // expression?
124 return {nullptr, LK_StmtExprResult};
125
127 // -- A temporary bound to a reference in a new-initializer persists
128 // until the completion of the full-expression containing the
129 // new-initializer.
130 return {nullptr, LK_New};
131
135 // We don't yet know the storage duration of the surrounding temporary.
136 // Assume it's got full-expression duration for now, it will patch up our
137 // storage duration if that's not correct.
138 return {nullptr, LK_FullExpression};
139
141 // For subobjects, we look at the complete object.
142 return getEntityLifetime(Entity->getParent(), InitField);
143
145 // For subobjects, we look at the complete object.
146 if (Entity->getParent())
147 return getEntityLifetime(Entity->getParent(), InitField);
148 return {InitField, LK_MemInitializer};
149
151 // We can reach this case for aggregate initialization in a constructor:
152 // struct A { int &&r; };
153 // struct B : A { B() : A{0} {} };
154 // In this case, use the outermost field decl as the context.
155 return {InitField, LK_MemInitializer};
156
163 return {nullptr, LK_FullExpression};
164
166 // FIXME: Can we diagnose lifetime problems with exceptions?
167 return {nullptr, LK_FullExpression};
168
170 // -- A temporary object bound to a reference element of an aggregate of
171 // class type initialized from a parenthesized expression-list
172 // [dcl.init, 9.3] persists until the completion of the full-expression
173 // containing the expression-list.
174 return {nullptr, LK_FullExpression};
175 }
176
177 llvm_unreachable("unknown entity kind");
178}
179
180namespace {
181enum ReferenceKind {
182 /// Lifetime would be extended by a reference binding to a temporary.
183 RK_ReferenceBinding,
184 /// Lifetime would be extended by a std::initializer_list object binding to
185 /// its backing array.
186 RK_StdInitializerList,
187};
188
189/// A temporary or local variable. This will be one of:
190/// * A MaterializeTemporaryExpr.
191/// * A DeclRefExpr whose declaration is a local.
192/// * An AddrLabelExpr.
193/// * A BlockExpr for a block with captures.
194using Local = Expr *;
195
196/// Expressions we stepped over when looking for the local state. Any steps
197/// that would inhibit lifetime extension or take us out of subexpressions of
198/// the initializer are included.
199struct IndirectLocalPathEntry {
200 enum EntryKind {
201 DefaultInit,
202 AddressOf,
203 VarInit,
204 LValToRVal,
205 LifetimeBoundCall,
206 TemporaryCopy,
207 LambdaCaptureInit,
208 MemberExpr,
209 GslReferenceInit,
210 GslPointerInit,
211 GslPointerAssignment,
212 DefaultArg,
213 ParenAggInit,
214 } Kind;
215 Expr *E;
216 union {
217 const Decl *D = nullptr;
218 const LambdaCapture *Capture;
219 };
220 IndirectLocalPathEntry() {}
221 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
222 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
223 : Kind(K), E(E), D(D) {}
224 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
225 : Kind(K), E(E), Capture(Capture) {}
226};
227
228using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
229
230struct RevertToOldSizeRAII {
231 IndirectLocalPath &Path;
232 unsigned OldSize = Path.size();
233 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
234 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
235};
236
237using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
238 ReferenceKind RK)>;
239} // namespace
240
241static bool isVarOnPath(const IndirectLocalPath &Path, VarDecl *VD) {
242 for (auto E : Path)
243 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
244 return true;
245 return false;
246}
247
248static bool pathContainsInit(const IndirectLocalPath &Path) {
249 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
250 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
251 E.Kind == IndirectLocalPathEntry::VarInit;
252 });
253}
254
255static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
256 Expr *Init, LocalVisitor Visit,
257 bool RevisitSubinits);
258
259static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
260 Expr *Init, ReferenceKind RK,
261 LocalVisitor Visit);
262
263// Returns true if the given Record decl is a form of `GSLOwner<Pointer>`
264// type, e.g. std::vector<string_view>, std::optional<string_view>.
265static bool isContainerOfPointer(const RecordDecl *Container) {
266 if (const auto *CTSD =
267 dyn_cast_if_present<ClassTemplateSpecializationDecl>(Container)) {
268 if (!CTSD->hasAttr<OwnerAttr>()) // Container must be a GSL owner type.
269 return false;
270 const auto &TAs = CTSD->getTemplateArgs();
271 return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
272 lifetimes::isPointerLikeType(TAs[0].getAsType());
273 }
274 return false;
275}
276static bool isContainerOfOwner(const RecordDecl *Container) {
277 const auto *CTSD =
278 dyn_cast_if_present<ClassTemplateSpecializationDecl>(Container);
279 if (!CTSD)
280 return false;
281 if (!CTSD->hasAttr<OwnerAttr>()) // Container must be a GSL owner type.
282 return false;
283 const auto &TAs = CTSD->getTemplateArgs();
284 return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
285 isGslOwnerType(TAs[0].getAsType());
286}
287
288// Returns true if the given Record is `std::initializer_list<pointer>`.
290 if (const auto *CTSD =
291 dyn_cast_if_present<ClassTemplateSpecializationDecl>(RD)) {
292 const auto &TAs = CTSD->getTemplateArgs();
293 return lifetimes::isInStlNamespace(RD) && RD->getIdentifier() &&
294 RD->getName() == "initializer_list" && TAs.size() > 0 &&
295 TAs[0].getKind() == TemplateArgument::Type &&
296 lifetimes::isPointerLikeType(TAs[0].getAsType());
297 }
298 return false;
299}
300
301// Returns true if the given constructor is a copy-like constructor, such as
302// `Ctor(Owner<U>&&)` or `Ctor(const Owner<U>&)`.
304 if (!Ctor || Ctor->param_size() != 1)
305 return false;
306 const auto *ParamRefType =
307 Ctor->getParamDecl(0)->getType()->getAs<ReferenceType>();
308 if (!ParamRefType)
309 return false;
310
311 // Check if the first parameter type is "Owner<U>".
312 if (const auto *TST =
313 ParamRefType->getPointeeType()->getAs<TemplateSpecializationType>())
314 return TST->getTemplateName()
315 .getAsTemplateDecl()
316 ->getTemplatedDecl()
317 ->hasAttr<OwnerAttr>();
318 return false;
319}
320
321// Returns true if we should perform the GSL analysis on the first argument for
322// the given constructor.
323static bool
325 const auto *LHSRecordDecl = Ctor->getConstructor()->getParent();
326
327 // Case 1, construct a GSL pointer, e.g. std::string_view
328 // Always inspect when LHS is a pointer.
329 if (LHSRecordDecl->hasAttr<PointerAttr>())
330 return true;
331
332 if (Ctor->getConstructor()->param_empty() ||
333 !isContainerOfPointer(LHSRecordDecl))
334 return false;
335
336 // Now, the LHS is an Owner<Pointer> type, e.g., std::vector<string_view>.
337 //
338 // At a high level, we cannot precisely determine what the nested pointer
339 // owns. However, by analyzing the RHS owner type, we can use heuristics to
340 // infer ownership information. These heuristics are designed to be
341 // conservative, minimizing false positives while still providing meaningful
342 // diagnostics.
343 //
344 // While this inference isn't perfect, it helps catch common use-after-free
345 // patterns.
346 auto RHSArgType = Ctor->getArg(0)->getType();
347 const auto *RHSRD = RHSArgType->getAsRecordDecl();
348 // LHS is constructed from an initializer_list.
349 //
350 // std::initializer_list is a proxy object that provides access to the backing
351 // array. We perform analysis on it to determine if there are any dangling
352 // temporaries in the backing array.
353 // E.g. std::vector<string_view> abc = {string()};
355 return true;
356
357 // RHS must be an owner.
358 if (!isGslOwnerType(RHSArgType))
359 return false;
360
361 // Bail out if the RHS is Owner<Pointer>.
362 //
363 // We cannot reliably determine what the LHS nested pointer owns -- it could
364 // be the entire RHS or the nested pointer in RHS. To avoid false positives,
365 // we skip this case, such as:
366 // std::stack<std::string_view> s(std::deque<std::string_view>{});
367 //
368 // TODO: this also has a false negative, it doesn't catch the case like:
369 // std::optional<span<int*>> os = std::vector<int*>{}
370 if (isContainerOfPointer(RHSRD))
371 return false;
372
373 // Assume that the nested Pointer is constructed from the nested Owner.
374 // E.g. std::optional<string_view> sv = std::optional<string>(s);
375 if (isContainerOfOwner(RHSRD))
376 return true;
377
378 // Now, the LHS is an Owner<Pointer> and the RHS is an Owner<X>, where X is
379 // neither an `Owner` nor a `Pointer`.
380 //
381 // Use the constructor's signature as a hint. If it is a copy-like constructor
382 // `Owner1<Pointer>(Owner2<X>&&)`, we assume that the nested pointer is
383 // constructed from X. In such cases, we do not diagnose, as `X` is not an
384 // owner, e.g.
385 // std::optional<string_view> sv = std::optional<Foo>();
386 if (const auto *PrimaryCtorTemplate =
388 PrimaryCtorTemplate &&
389 isCopyLikeConstructor(dyn_cast_if_present<CXXConstructorDecl>(
390 PrimaryCtorTemplate->getTemplatedDecl()))) {
391 return false;
392 }
393 // Assume that the nested pointer is constructed from the whole RHS.
394 // E.g. optional<string_view> s = std::string();
395 return true;
396}
397
398// Visit lifetimebound or gsl-pointer arguments.
399static void visitFunctionCallArguments(IndirectLocalPath &Path, Expr *Call,
400 LocalVisitor Visit) {
401 const FunctionDecl *Callee;
402 ArrayRef<Expr *> Args;
403
404 if (auto *CE = dyn_cast<CallExpr>(Call)) {
405 Callee = CE->getDirectCallee();
406 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
407 } else {
408 auto *CCE = cast<CXXConstructExpr>(Call);
409 Callee = CCE->getConstructor();
410 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
411 }
412 if (!Callee)
413 return;
414
415 bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
416 diag::warn_dangling_lifetime_pointer, SourceLocation());
417 Expr *ObjectArg = nullptr;
418 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
419 ObjectArg = Args[0];
420 Args = Args.slice(1);
421 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
422 ObjectArg = MCE->getImplicitObjectArgument();
423 }
424
425 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
426 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
427 if (Arg->isGLValue())
428 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
429 Visit);
430 else
431 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
432 Path.pop_back();
433 };
434 auto VisitGSLPointerArg = [&](const FunctionDecl *Callee, Expr *Arg) {
435 auto ReturnType = Callee->getReturnType();
436
437 // Once we initialized a value with a non gsl-owner reference, it can no
438 // longer dangle.
439 if (ReturnType->isReferenceType() &&
440 !isGslOwnerType(ReturnType->getPointeeType())) {
441 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
442 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit ||
443 PE.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
444 continue;
445 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit ||
446 PE.Kind == IndirectLocalPathEntry::GslPointerAssignment)
447 return;
448 break;
449 }
450 }
451 Path.push_back({ReturnType->isReferenceType()
452 ? IndirectLocalPathEntry::GslReferenceInit
453 : IndirectLocalPathEntry::GslPointerInit,
454 Arg, Callee});
455 if (Arg->isGLValue())
456 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
457 Visit);
458 else
459 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
460 Path.pop_back();
461 };
462
463 bool CheckCoroCall = false;
464 if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
465 CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
466 RD->hasAttr<CoroReturnTypeAttr>() &&
467 !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
468 }
469
470 if (ObjectArg) {
471 bool CheckCoroObjArg = CheckCoroCall;
472 // Coroutine lambda objects with empty capture list are not lifetimebound.
473 if (auto *LE = dyn_cast<LambdaExpr>(ObjectArg->IgnoreImplicit());
474 LE && LE->captures().empty())
475 CheckCoroObjArg = false;
476 // Allow `get_return_object()` as the object param (__promise) is not
477 // lifetimebound.
478 if (Sema::CanBeGetReturnObject(Callee))
479 CheckCoroObjArg = false;
481 CheckCoroObjArg)
482 VisitLifetimeBoundArg(Callee, ObjectArg);
483 else if (EnableGSLAnalysis) {
484 if (auto *CME = dyn_cast<CXXMethodDecl>(Callee);
486 CME, /*RunningUnderLifetimeSafety=*/false))
487 VisitGSLPointerArg(Callee, ObjectArg);
488 }
489 }
490
491 const FunctionDecl *CanonCallee =
493 unsigned NP = std::min(Callee->getNumParams(), CanonCallee->getNumParams());
494 for (unsigned I = 0, N = std::min<unsigned>(NP, Args.size()); I != N; ++I) {
495 Expr *Arg = Args[I];
496 RevertToOldSizeRAII RAII(Path);
497 if (auto *DAE = dyn_cast<CXXDefaultArgExpr>(Arg)) {
498 Path.push_back(
499 {IndirectLocalPathEntry::DefaultArg, DAE, DAE->getParam()});
500 Arg = DAE->getExpr();
501 }
502 if (CheckCoroCall ||
503 CanonCallee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
504 VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
505 else if (const auto *CaptureAttr =
506 CanonCallee->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>();
507 CaptureAttr && isa<CXXConstructorDecl>(CanonCallee) &&
508 llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
509 return ArgIdx == LifetimeCaptureByAttr::This;
510 }))
511 // `lifetime_capture_by(this)` in a class constructor has the same
512 // semantics as `lifetimebound`:
513 //
514 // struct Foo {
515 // const int& a;
516 // // Equivalent to Foo(const int& t [[clang::lifetimebound]])
517 // Foo(const int& t [[clang::lifetime_capture_by(this)]]) : a(t) {}
518 // };
519 //
520 // In the implementation, `lifetime_capture_by` is treated as an alias for
521 // `lifetimebound` and shares the same code path. This implies the emitted
522 // diagnostics will be emitted under `-Wdangling`, not
523 // `-Wdangling-capture`.
524 VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
525 else if (EnableGSLAnalysis && I == 0) {
526 // Perform GSL analysis for the first argument
527 if (lifetimes::shouldTrackFirstArgument(CanonCallee)) {
528 VisitGSLPointerArg(CanonCallee, Arg);
529 } else if (auto *Ctor = dyn_cast<CXXConstructExpr>(Call);
531 VisitGSLPointerArg(Ctor->getConstructor(), Arg);
532 }
533 }
534 }
535}
536
537/// Visit the locals that would be reachable through a reference bound to the
538/// glvalue expression \c Init.
539static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
540 Expr *Init, ReferenceKind RK,
541 LocalVisitor Visit) {
542 RevertToOldSizeRAII RAII(Path);
543
544 // Walk past any constructs which we can lifetime-extend across.
545 Expr *Old;
546 do {
547 Old = Init;
548
549 if (auto *FE = dyn_cast<FullExpr>(Init))
550 Init = FE->getSubExpr();
551
552 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
553 // If this is just redundant braces around an initializer, step over it.
554 if (ILE->isTransparent())
555 Init = ILE->getInit(0);
556 }
557
558 if (MemberExpr *ME = dyn_cast<MemberExpr>(Init->IgnoreImpCasts()))
559 Path.push_back(
560 {IndirectLocalPathEntry::MemberExpr, ME, ME->getMemberDecl()});
561 // Step over any subobject adjustments; we may have a materialized
562 // temporary inside them.
563 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
564
565 // Per current approach for DR1376, look through casts to reference type
566 // when performing lifetime extension.
567 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
568 if (CE->getSubExpr()->isGLValue())
569 Init = CE->getSubExpr();
570
571 // Per the current approach for DR1299, look through array element access
572 // on array glvalues when performing lifetime extension.
573 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
574 Init = ASE->getBase();
575 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
576 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
577 Init = ICE->getSubExpr();
578 else
579 // We can't lifetime extend through this but we might still find some
580 // retained temporaries.
581 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
582 }
583
584 // Step into CXXDefaultInitExprs so we can diagnose cases where a
585 // constructor inherits one as an implicit mem-initializer.
586 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
587 Path.push_back(
588 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
589 Init = DIE->getExpr();
590 }
591 } while (Init != Old);
592
593 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
594 if (Visit(Path, Local(MTE), RK))
595 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true);
596 }
597
598 if (auto *M = dyn_cast<MemberExpr>(Init)) {
599 // Lifetime of a non-reference type field is same as base object.
600 if (auto *F = dyn_cast<FieldDecl>(M->getMemberDecl());
601 F && !F->getType()->isReferenceType())
602 visitLocalsRetainedByInitializer(Path, M->getBase(), Visit, true);
603 }
604
605 if (isa<CallExpr>(Init))
606 return visitFunctionCallArguments(Path, Init, Visit);
607
608 switch (Init->getStmtClass()) {
609 case Stmt::DeclRefExprClass: {
610 // If we find the name of a local non-reference parameter, we could have a
611 // lifetime problem.
612 auto *DRE = cast<DeclRefExpr>(Init);
613 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
614 if (VD && VD->hasLocalStorage() &&
615 !DRE->refersToEnclosingVariableOrCapture()) {
616 if (!VD->getType()->isReferenceType()) {
617 Visit(Path, Local(DRE), RK);
618 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
619 // The lifetime of a reference parameter is unknown; assume it's OK
620 // for now.
621 break;
622 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
623 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
624 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
625 RK_ReferenceBinding, Visit);
626 }
627 }
628 break;
629 }
630
631 case Stmt::UnaryOperatorClass: {
632 // The only unary operator that make sense to handle here
633 // is Deref. All others don't resolve to a "name." This includes
634 // handling all sorts of rvalues passed to a unary operator.
636 if (U->getOpcode() == UO_Deref)
637 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
638 break;
639 }
640
641 case Stmt::ArraySectionExprClass: {
643 Path, cast<ArraySectionExpr>(Init)->getBase(), Visit, true);
644 break;
645 }
646
647 case Stmt::ConditionalOperatorClass:
648 case Stmt::BinaryConditionalOperatorClass: {
650 if (!C->getTrueExpr()->getType()->isVoidType())
651 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
652 if (!C->getFalseExpr()->getType()->isVoidType())
653 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
654 break;
655 }
656
657 case Stmt::CompoundLiteralExprClass: {
658 if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Init)) {
659 if (!CLE->isFileScope())
660 Visit(Path, Local(CLE), RK);
661 }
662 break;
663 }
664
665 // FIXME: Visit the left-hand side of an -> or ->*.
666
667 default:
668 break;
669 }
670}
671
672/// Visit the locals that would be reachable through an object initialized by
673/// the prvalue expression \c Init.
674static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
675 Expr *Init, LocalVisitor Visit,
676 bool RevisitSubinits) {
677 RevertToOldSizeRAII RAII(Path);
678
679 Expr *Old;
680 do {
681 Old = Init;
682
683 // Step into CXXDefaultInitExprs so we can diagnose cases where a
684 // constructor inherits one as an implicit mem-initializer.
685 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
686 Path.push_back(
687 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
688 Init = DIE->getExpr();
689 }
690
691 if (auto *FE = dyn_cast<FullExpr>(Init))
692 Init = FE->getSubExpr();
693
694 // Dig out the expression which constructs the extended temporary.
695 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
696
697 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
698 Init = BTE->getSubExpr();
699
700 Init = Init->IgnoreParens();
701
702 // Step over value-preserving rvalue casts.
703 if (auto *CE = dyn_cast<CastExpr>(Init)) {
704 switch (CE->getCastKind()) {
705 case CK_LValueToRValue:
706 // If we can match the lvalue to a const object, we can look at its
707 // initializer.
708 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
710 Path, Init, RK_ReferenceBinding,
711 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
712 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
713 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
714 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
715 !isVarOnPath(Path, VD)) {
716 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
717 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit,
718 true);
719 }
720 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
721 if (MTE->getType().isConstQualified())
722 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(),
723 Visit, true);
724 }
725 return false;
726 });
727
728 // We assume that objects can be retained by pointers cast to integers,
729 // but not if the integer is cast to floating-point type or to _Complex.
730 // We assume that casts to 'bool' do not preserve enough information to
731 // retain a local object.
732 case CK_NoOp:
733 case CK_BitCast:
734 case CK_BaseToDerived:
735 case CK_DerivedToBase:
736 case CK_UncheckedDerivedToBase:
737 case CK_Dynamic:
738 case CK_ToUnion:
739 case CK_UserDefinedConversion:
740 case CK_ConstructorConversion:
741 case CK_IntegralToPointer:
742 case CK_PointerToIntegral:
743 case CK_VectorSplat:
744 case CK_IntegralCast:
745 case CK_CPointerToObjCPointerCast:
746 case CK_BlockPointerToObjCPointerCast:
747 case CK_AnyPointerToBlockPointerCast:
748 case CK_AddressSpaceConversion:
749 break;
750
751 case CK_ArrayToPointerDecay:
752 // Model array-to-pointer decay as taking the address of the array
753 // lvalue.
754 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
756 Path, CE->getSubExpr(), RK_ReferenceBinding, Visit);
757
758 default:
759 return;
760 }
761
762 Init = CE->getSubExpr();
763 }
764 } while (Old != Init);
765
766 // C++17 [dcl.init.list]p6:
767 // initializing an initializer_list object from the array extends the
768 // lifetime of the array exactly like binding a reference to a temporary.
769 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
770 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
771 RK_StdInitializerList, Visit);
772
773 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
774 // We already visited the elements of this initializer list while
775 // performing the initialization. Don't visit them again unless we've
776 // changed the lifetime of the initialized entity.
777 if (!RevisitSubinits)
778 return;
779
780 if (ILE->isTransparent())
781 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
782 RevisitSubinits);
783
784 if (ILE->getType()->isArrayType()) {
785 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
786 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
787 RevisitSubinits);
788 return;
789 }
790
791 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
792 assert(RD->isAggregate() && "aggregate init on non-aggregate");
793
794 // If we lifetime-extend a braced initializer which is initializing an
795 // aggregate, and that aggregate contains reference members which are
796 // bound to temporaries, those temporaries are also lifetime-extended.
797 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
798 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
799 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
800 RK_ReferenceBinding, Visit);
801 else {
802 unsigned Index = 0;
803 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
804 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
805 RevisitSubinits);
806 for (const auto *I : RD->fields()) {
807 if (Index >= ILE->getNumInits())
808 break;
809 if (I->isUnnamedBitField())
810 continue;
811 Expr *SubInit = ILE->getInit(Index);
812 if (I->getType()->isReferenceType())
814 RK_ReferenceBinding, Visit);
815 else
816 // This might be either aggregate-initialization of a member or
817 // initialization of a std::initializer_list object. Regardless,
818 // we should recursively lifetime-extend that initializer.
819 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
820 RevisitSubinits);
821 ++Index;
822 }
823 }
824 }
825 return;
826 }
827
828 // The lifetime of an init-capture is that of the closure object constructed
829 // by a lambda-expression.
830 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
831 LambdaExpr::capture_iterator CapI = LE->capture_begin();
832 for (Expr *E : LE->capture_inits()) {
833 assert(CapI != LE->capture_end());
834 const LambdaCapture &Cap = *CapI++;
835 if (!E)
836 continue;
837 if (Cap.capturesVariable())
838 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
839 if (E->isGLValue())
840 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
841 Visit);
842 else
843 visitLocalsRetainedByInitializer(Path, E, Visit, true);
844 if (Cap.capturesVariable())
845 Path.pop_back();
846 }
847 }
848
849 // Assume that a copy or move from a temporary references the same objects
850 // that the temporary does.
851 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
852 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
853 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
854 Expr *Arg = MTE->getSubExpr();
855 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
856 CCE->getConstructor()});
857 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
858 Path.pop_back();
859 }
860 }
861 }
862
864 return visitFunctionCallArguments(Path, Init, Visit);
865
866 if (auto *CPE = dyn_cast<CXXParenListInitExpr>(Init)) {
867 RevertToOldSizeRAII RAII(Path);
868 Path.push_back({IndirectLocalPathEntry::ParenAggInit, CPE});
869 for (auto *I : CPE->getInitExprs()) {
870 if (I->isGLValue())
871 visitLocalsRetainedByReferenceBinding(Path, I, RK_ReferenceBinding,
872 Visit);
873 else
874 visitLocalsRetainedByInitializer(Path, I, Visit, true);
875 }
876 }
877 switch (Init->getStmtClass()) {
878 case Stmt::UnaryOperatorClass: {
879 auto *UO = cast<UnaryOperator>(Init);
880 // If the initializer is the address of a local, we could have a lifetime
881 // problem.
882 if (UO->getOpcode() == UO_AddrOf) {
883 // If this is &rvalue, then it's ill-formed and we have already diagnosed
884 // it. Don't produce a redundant warning about the lifetime of the
885 // temporary.
886 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
887 return;
888
889 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
890 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
891 RK_ReferenceBinding, Visit);
892 }
893 break;
894 }
895
896 case Stmt::BinaryOperatorClass: {
897 // Handle pointer arithmetic.
898 auto *BO = cast<BinaryOperator>(Init);
899 BinaryOperatorKind BOK = BO->getOpcode();
900 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
901 break;
902
903 if (BO->getLHS()->getType()->isPointerType())
904 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
905 else if (BO->getRHS()->getType()->isPointerType())
906 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
907 break;
908 }
909
910 case Stmt::ConditionalOperatorClass:
911 case Stmt::BinaryConditionalOperatorClass: {
913 // In C++, we can have a throw-expression operand, which has 'void' type
914 // and isn't interesting from a lifetime perspective.
915 if (!C->getTrueExpr()->getType()->isVoidType())
916 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
917 if (!C->getFalseExpr()->getType()->isVoidType())
918 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
919 break;
920 }
921
922 case Stmt::BlockExprClass:
923 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
924 // This is a local block, whose lifetime is that of the function.
925 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
926 }
927 break;
928
929 case Stmt::AddrLabelExprClass:
930 // We want to warn if the address of a label would escape the function.
931 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
932 break;
933
934 default:
935 break;
936 }
937}
938
939/// Whether a path to an object supports lifetime extension.
941 /// Lifetime-extend along this path.
943 /// Do not lifetime extend along this path.
945};
946
947/// Determine whether this is an indirect path to a temporary that we are
948/// supposed to lifetime-extend along.
949static PathLifetimeKind
950shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
951 for (auto Elem : Path) {
952 if (Elem.Kind == IndirectLocalPathEntry::MemberExpr ||
953 Elem.Kind == IndirectLocalPathEntry::LambdaCaptureInit)
954 continue;
955 return Elem.Kind == IndirectLocalPathEntry::DefaultInit
958 }
960}
961
962/// Find the range for the first interesting entry in the path at or after I.
963static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
964 Expr *E) {
965 for (unsigned N = Path.size(); I != N; ++I) {
966 switch (Path[I].Kind) {
967 case IndirectLocalPathEntry::AddressOf:
968 case IndirectLocalPathEntry::LValToRVal:
969 case IndirectLocalPathEntry::LifetimeBoundCall:
970 case IndirectLocalPathEntry::TemporaryCopy:
971 case IndirectLocalPathEntry::GslReferenceInit:
972 case IndirectLocalPathEntry::GslPointerInit:
973 case IndirectLocalPathEntry::GslPointerAssignment:
974 case IndirectLocalPathEntry::ParenAggInit:
975 case IndirectLocalPathEntry::MemberExpr:
976 // These exist primarily to mark the path as not permitting or
977 // supporting lifetime extension.
978 break;
979
980 case IndirectLocalPathEntry::VarInit:
981 if (cast<VarDecl>(Path[I].D)->isImplicit())
982 return SourceRange();
983 [[fallthrough]];
984 case IndirectLocalPathEntry::DefaultInit:
985 return Path[I].E->getSourceRange();
986
987 case IndirectLocalPathEntry::LambdaCaptureInit:
988 if (!Path[I].Capture->capturesVariable())
989 continue;
990 return Path[I].E->getSourceRange();
991
992 case IndirectLocalPathEntry::DefaultArg:
993 return cast<CXXDefaultArgExpr>(Path[I].E)->getUsedLocation();
994 }
995 }
996 return E->getSourceRange();
997}
998
999static bool pathOnlyHandlesGslPointer(const IndirectLocalPath &Path) {
1000 for (const auto &It : llvm::reverse(Path)) {
1001 switch (It.Kind) {
1002 case IndirectLocalPathEntry::VarInit:
1003 case IndirectLocalPathEntry::AddressOf:
1004 case IndirectLocalPathEntry::LifetimeBoundCall:
1005 case IndirectLocalPathEntry::MemberExpr:
1006 continue;
1007 case IndirectLocalPathEntry::GslPointerInit:
1008 case IndirectLocalPathEntry::GslReferenceInit:
1009 case IndirectLocalPathEntry::GslPointerAssignment:
1010 return true;
1011 default:
1012 return false;
1013 }
1014 }
1015 return false;
1016}
1017// Result of analyzing the Path for GSLPointer.
1019 // Path does not correspond to a GSLPointer.
1021
1022 // A relevant case was identified.
1024 // Stop the entire traversal.
1026 // Skip this step and continue traversing inner AST nodes.
1028};
1029// Analyze cases where a GSLPointer is initialized or assigned from a
1030// temporary owner object.
1031static AnalysisResult analyzePathForGSLPointer(const IndirectLocalPath &Path,
1032 Local L, LifetimeKind LK) {
1033 if (!pathOnlyHandlesGslPointer(Path))
1034 return NotGSLPointer;
1035
1036 // At this point, Path represents a series of operations involving a
1037 // GSLPointer, either in the process of initialization or assignment.
1038
1039 // Process temporary base objects for MemberExpr cases, e.g. Temp().field.
1040 for (const auto &E : Path) {
1041 if (E.Kind == IndirectLocalPathEntry::MemberExpr) {
1042 // Avoid interfering with the local base object.
1043 if (pathContainsInit(Path))
1044 return Abandon;
1045
1046 // We are not interested in the temporary base objects of gsl Pointers:
1047 // auto p1 = Temp().ptr; // Here p1 might not dangle.
1048 // However, we want to diagnose for gsl owner fields:
1049 // auto p2 = Temp().owner; // Here p2 is dangling.
1050 if (const auto *FD = llvm::dyn_cast_or_null<FieldDecl>(E.D);
1051 FD && !FD->getType()->isReferenceType() &&
1052 isGslOwnerType(FD->getType()) && LK != LK_MemInitializer) {
1053 return Report;
1054 }
1055 return Abandon;
1056 }
1057 }
1058
1059 // Note: A LifetimeBoundCall can appear interleaved in this sequence.
1060 // For example:
1061 // const std::string& Ref(const std::string& a [[clang::lifetimebound]]);
1062 // string_view abc = Ref(std::string());
1063 // The "Path" is [GSLPointerInit, LifetimeboundCall], where "L" is the
1064 // temporary "std::string()" object. We need to check the return type of the
1065 // function with the lifetimebound attribute.
1066 if (Path.back().Kind == IndirectLocalPathEntry::LifetimeBoundCall) {
1067 // The lifetimebound applies to the implicit object parameter of a method.
1068 const FunctionDecl *FD =
1069 llvm::dyn_cast_or_null<FunctionDecl>(Path.back().D);
1070 // The lifetimebound applies to a function parameter.
1071 if (const auto *PD = llvm::dyn_cast<ParmVarDecl>(Path.back().D))
1072 FD = llvm::dyn_cast<FunctionDecl>(PD->getDeclContext());
1073
1074 if (isa_and_present<CXXConstructorDecl>(FD)) {
1075 // Constructor case: the parameter is annotated with lifetimebound
1076 // e.g., GSLPointer(const S& s [[clang::lifetimebound]])
1077 // We still respect this case even the type S is not an owner.
1078 return Report;
1079 }
1080 // Check the return type, e.g.
1081 // const GSLOwner& func(const Foo& foo [[clang::lifetimebound]])
1082 // GSLOwner* func(cosnt Foo& foo [[clang::lifetimebound]])
1083 // GSLPointer func(const Foo& foo [[clang::lifetimebound]])
1084 if (FD && ((FD->getReturnType()->isPointerOrReferenceType() &&
1087 return Report;
1088
1089 return Abandon;
1090 }
1091
1092 if (isa<DeclRefExpr>(L)) {
1093 // We do not want to follow the references when returning a pointer
1094 // originating from a local owner to avoid the following false positive:
1095 // int &p = *localUniquePtr;
1096 // someContainer.add(std::move(localUniquePtr));
1097 // return p;
1098 if (!pathContainsInit(Path) && isGslOwnerType(L->getType()))
1099 return Report;
1100 return Abandon;
1101 }
1102
1103 // The GSLPointer is from a temporary object.
1104 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
1105
1106 bool IsGslPtrValueFromGslTempOwner =
1107 MTE && !MTE->getExtendingDecl() && isGslOwnerType(MTE->getType());
1108 // Skipping a chain of initializing gsl::Pointer annotated objects.
1109 // We are looking only for the final source to find out if it was
1110 // a local or temporary owner or the address of a local
1111 // variable/param.
1112 if (!IsGslPtrValueFromGslTempOwner)
1113 return Skip;
1114 return Report;
1115}
1116
1117static bool shouldRunGSLAssignmentAnalysis(const Sema &SemaRef,
1118 const AssignedEntity &Entity) {
1119 bool EnableGSLAssignmentWarnings = !SemaRef.getDiagnostics().isIgnored(
1120 diag::warn_dangling_lifetime_pointer_assignment, SourceLocation());
1121 return (EnableGSLAssignmentWarnings &&
1122 (isGslPointerType(Entity.LHS->getType()) ||
1124 Entity.AssignmentOperator)));
1125}
1126
1127static void
1129 const InitializedEntity *ExtendingEntity, LifetimeKind LK,
1130 const AssignedEntity *AEntity,
1131 const CapturingEntity *CapEntity, Expr *Init) {
1132 assert(!AEntity || LK == LK_Assignment);
1133 assert(!CapEntity || LK == LK_LifetimeCapture);
1134 assert(!InitEntity || (LK != LK_Assignment && LK != LK_LifetimeCapture));
1135 // If this entity doesn't have an interesting lifetime, don't bother looking
1136 // for temporaries within its initializer.
1137 if (LK == LK_FullExpression)
1138 return;
1139
1140 // FIXME: consider moving the TemporaryVisitor and visitLocalsRetained*
1141 // functions to a dedicated class.
1142 auto TemporaryVisitor = [&](const IndirectLocalPath &Path, Local L,
1143 ReferenceKind RK) -> bool {
1144 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
1145 SourceLocation DiagLoc = DiagRange.getBegin();
1146
1147 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
1148
1149 bool IsGslPtrValueFromGslTempOwner = true;
1150 switch (analyzePathForGSLPointer(Path, L, LK)) {
1151 case Abandon:
1152 return false;
1153 case Skip:
1154 return true;
1155 case NotGSLPointer:
1156 IsGslPtrValueFromGslTempOwner = false;
1157 [[fallthrough]];
1158 case Report:
1159 break;
1160 }
1161
1162 switch (LK) {
1163 case LK_FullExpression:
1164 llvm_unreachable("already handled this");
1165
1166 case LK_Extended: {
1167 if (!MTE) {
1168 // The initialized entity has lifetime beyond the full-expression,
1169 // and the local entity does too, so don't warn.
1170 //
1171 // FIXME: We should consider warning if a static / thread storage
1172 // duration variable retains an automatic storage duration local.
1173 return false;
1174 }
1175
1176 switch (shouldLifetimeExtendThroughPath(Path)) {
1178 // Update the storage duration of the materialized temporary.
1179 // FIXME: Rebuild the expression instead of mutating it.
1180 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
1181 ExtendingEntity->allocateManglingNumber());
1182 // Also visit the temporaries lifetime-extended by this initializer.
1183 return true;
1184
1186 if (SemaRef.getLangOpts().CPlusPlus23 && InitEntity) {
1187 if (const VarDecl *VD =
1188 dyn_cast_if_present<VarDecl>(InitEntity->getDecl());
1189 VD && VD->isCXXForRangeImplicitVar()) {
1190 return false;
1191 }
1192 }
1193
1194 if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) {
1195 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
1196 << DiagRange;
1197 return false;
1198 }
1199
1200 // If the path goes through the initialization of a variable or field,
1201 // it can't possibly reach a temporary created in this full-expression.
1202 // We will have already diagnosed any problems with the initializer.
1203 if (pathContainsInit(Path))
1204 return false;
1205
1206 SemaRef.Diag(DiagLoc, diag::warn_dangling_variable)
1207 << RK << !InitEntity->getParent()
1208 << ExtendingEntity->getDecl()->isImplicit()
1209 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
1210 break;
1211 }
1212 break;
1213 }
1214
1215 case LK_LifetimeCapture: {
1216 // The captured entity has lifetime beyond the full-expression,
1217 // and the capturing entity does too, so don't warn.
1218 if (!MTE)
1219 return false;
1220 if (CapEntity->Entity)
1221 SemaRef.Diag(DiagLoc, diag::warn_dangling_reference_captured)
1222 << CapEntity->Entity << DiagRange;
1223 else
1224 SemaRef.Diag(DiagLoc, diag::warn_dangling_reference_captured_by_unknown)
1225 << DiagRange;
1226 return false;
1227 }
1228
1229 case LK_Assignment: {
1230 if (!MTE || pathContainsInit(Path))
1231 return false;
1232 if (IsGslPtrValueFromGslTempOwner)
1233 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_assignment)
1234 << AEntity->LHS << DiagRange;
1235 else
1236 SemaRef.Diag(DiagLoc, diag::warn_dangling_pointer_assignment)
1237 << AEntity->LHS->getType()->isPointerType() << AEntity->LHS
1238 << DiagRange;
1239 return false;
1240 }
1241 case LK_MemInitializer: {
1242 if (MTE) {
1243 // Under C++ DR1696, if a mem-initializer (or a default member
1244 // initializer used by the absence of one) would lifetime-extend a
1245 // temporary, the program is ill-formed.
1246 if (auto *ExtendingDecl =
1247 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
1248 if (IsGslPtrValueFromGslTempOwner) {
1249 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
1250 << ExtendingDecl << DiagRange;
1251 SemaRef.Diag(ExtendingDecl->getLocation(),
1252 diag::note_ref_or_ptr_member_declared_here)
1253 << true;
1254 return false;
1255 }
1256 bool IsSubobjectMember = ExtendingEntity != InitEntity;
1257 SemaRef.Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
1259 ? diag::err_dangling_member
1260 : diag::warn_dangling_member)
1261 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
1262 // Don't bother adding a note pointing to the field if we're inside
1263 // its default member initializer; our primary diagnostic points to
1264 // the same place in that case.
1265 if (Path.empty() ||
1266 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
1267 SemaRef.Diag(ExtendingDecl->getLocation(),
1268 diag::note_lifetime_extending_member_declared_here)
1269 << RK << IsSubobjectMember;
1270 }
1271 } else {
1272 // We have a mem-initializer but no particular field within it; this
1273 // is either a base class or a delegating initializer directly
1274 // initializing the base-class from something that doesn't live long
1275 // enough.
1276 //
1277 // FIXME: Warn on this.
1278 return false;
1279 }
1280 } else {
1281 // Paths via a default initializer can only occur during error recovery
1282 // (there's no other way that a default initializer can refer to a
1283 // local). Don't produce a bogus warning on those cases.
1284 if (pathContainsInit(Path))
1285 return false;
1286
1287 auto *DRE = dyn_cast<DeclRefExpr>(L);
1288 // Suppress false positives for code like the one below:
1289 // Ctor(unique_ptr<T> up) : pointer(up.get()), owner(move(up)) {}
1290 // FIXME: move this logic to analyzePathForGSLPointer.
1291 if (DRE && isGslOwnerType(DRE->getType()))
1292 return false;
1293
1294 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
1295 if (!VD) {
1296 // A member was initialized to a local block.
1297 // FIXME: Warn on this.
1298 return false;
1299 }
1300
1301 if (auto *Member =
1302 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
1303 bool IsPointer = !Member->getType()->isReferenceType();
1304 SemaRef.Diag(DiagLoc,
1305 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1306 : diag::warn_bind_ref_member_to_parameter)
1307 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
1308 SemaRef.Diag(Member->getLocation(),
1309 diag::note_ref_or_ptr_member_declared_here)
1310 << (unsigned)IsPointer;
1311 }
1312 }
1313 break;
1314 }
1315
1316 case LK_New:
1318 if (IsGslPtrValueFromGslTempOwner)
1319 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
1320 << DiagRange;
1321 else
1322 SemaRef.Diag(DiagLoc, RK == RK_ReferenceBinding
1323 ? diag::warn_new_dangling_reference
1324 : diag::warn_new_dangling_initializer_list)
1325 << !InitEntity->getParent() << DiagRange;
1326 } else {
1327 // We can't determine if the allocation outlives the local declaration.
1328 return false;
1329 }
1330 break;
1331
1332 case LK_Return:
1333 case LK_MustTail:
1334 case LK_StmtExprResult:
1335 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
1336 // We can't determine if the local variable outlives the statement
1337 // expression.
1338 if (LK == LK_StmtExprResult)
1339 return false;
1340 SemaRef.Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
1341 << InitEntity->getType()->isReferenceType() << DRE->getDecl()
1342 << isa<ParmVarDecl>(DRE->getDecl()) << (LK == LK_MustTail)
1343 << DiagRange;
1344 } else if (isa<BlockExpr>(L)) {
1345 SemaRef.Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
1346 } else if (isa<AddrLabelExpr>(L)) {
1347 // Don't warn when returning a label from a statement expression.
1348 // Leaving the scope doesn't end its lifetime.
1349 if (LK == LK_StmtExprResult)
1350 return false;
1351 SemaRef.Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
1352 } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(L)) {
1353 SemaRef.Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
1354 << InitEntity->getType()->isReferenceType() << CLE->getInitializer()
1355 << 2 << (LK == LK_MustTail) << DiagRange;
1356 } else {
1357 // P2748R5: Disallow Binding a Returned Glvalue to a Temporary.
1358 // [stmt.return]/p6: In a function whose return type is a reference,
1359 // other than an invented function for std::is_convertible ([meta.rel]),
1360 // a return statement that binds the returned reference to a temporary
1361 // expression ([class.temporary]) is ill-formed.
1362 if (SemaRef.getLangOpts().CPlusPlus26 &&
1363 InitEntity->getType()->isReferenceType())
1364 SemaRef.Diag(DiagLoc, diag::err_ret_local_temp_ref)
1365 << InitEntity->getType()->isReferenceType() << DiagRange;
1366 else if (LK == LK_MustTail)
1367 SemaRef.Diag(DiagLoc, diag::warn_musttail_local_temp_addr_ref)
1368 << InitEntity->getType()->isReferenceType() << DiagRange;
1369 else
1370 SemaRef.Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
1371 << InitEntity->getType()->isReferenceType() << DiagRange;
1372 }
1373 break;
1374 }
1375
1376 for (unsigned I = 0; I != Path.size(); ++I) {
1377 auto Elem = Path[I];
1378
1379 switch (Elem.Kind) {
1380 case IndirectLocalPathEntry::AddressOf:
1381 case IndirectLocalPathEntry::LValToRVal:
1382 case IndirectLocalPathEntry::ParenAggInit:
1383 // These exist primarily to mark the path as not permitting or
1384 // supporting lifetime extension.
1385 break;
1386
1387 case IndirectLocalPathEntry::LifetimeBoundCall:
1388 case IndirectLocalPathEntry::TemporaryCopy:
1389 case IndirectLocalPathEntry::MemberExpr:
1390 case IndirectLocalPathEntry::GslPointerInit:
1391 case IndirectLocalPathEntry::GslReferenceInit:
1392 case IndirectLocalPathEntry::GslPointerAssignment:
1393 // FIXME: Consider adding a note for these.
1394 break;
1395
1396 case IndirectLocalPathEntry::DefaultInit: {
1397 auto *FD = cast<FieldDecl>(Elem.D);
1398 SemaRef.Diag(FD->getLocation(),
1399 diag::note_init_with_default_member_initializer)
1400 << FD << nextPathEntryRange(Path, I + 1, L);
1401 break;
1402 }
1403
1404 case IndirectLocalPathEntry::VarInit: {
1405 const VarDecl *VD = cast<VarDecl>(Elem.D);
1406 SemaRef.Diag(VD->getLocation(), diag::note_local_var_initializer)
1407 << VD->getType()->isReferenceType() << VD->isImplicit()
1408 << VD->getDeclName() << nextPathEntryRange(Path, I + 1, L);
1409 break;
1410 }
1411
1412 case IndirectLocalPathEntry::LambdaCaptureInit: {
1413 if (!Elem.Capture->capturesVariable())
1414 break;
1415 // FIXME: We can't easily tell apart an init-capture from a nested
1416 // capture of an init-capture.
1417 const ValueDecl *VD = Elem.Capture->getCapturedVar();
1418 SemaRef.Diag(Elem.Capture->getLocation(),
1419 diag::note_lambda_capture_initializer)
1420 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
1421 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
1422 << nextPathEntryRange(Path, I + 1, L);
1423 break;
1424 }
1425
1426 case IndirectLocalPathEntry::DefaultArg: {
1427 const auto *DAE = cast<CXXDefaultArgExpr>(Elem.E);
1428 const ParmVarDecl *Param = DAE->getParam();
1429 SemaRef.Diag(Param->getDefaultArgRange().getBegin(),
1430 diag::note_init_with_default_argument)
1431 << Param << nextPathEntryRange(Path, I + 1, L);
1432 break;
1433 }
1434 }
1435 }
1436
1437 // We didn't lifetime-extend, so don't go any further; we don't need more
1438 // warnings or errors on inner temporaries within this one's initializer.
1439 return false;
1440 };
1441
1443 switch (LK) {
1444 case LK_Assignment: {
1445 if (shouldRunGSLAssignmentAnalysis(SemaRef, *AEntity))
1447 AEntity->AssignmentOperator)
1448 ? IndirectLocalPathEntry::LifetimeBoundCall
1449 : IndirectLocalPathEntry::GslPointerAssignment,
1450 Init});
1451 break;
1452 }
1453 case LK_LifetimeCapture: {
1454 if (lifetimes::isPointerLikeType(Init->getType()))
1455 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Init});
1456 break;
1457 }
1458 default:
1459 break;
1460 }
1461
1462 if (Init->isGLValue())
1463 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
1464 TemporaryVisitor);
1465 else
1467 Path, Init, TemporaryVisitor,
1468 // Don't revisit the sub inits for the initialization case.
1469 /*RevisitSubinits=*/!InitEntity);
1470}
1471
1472void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity,
1473 Expr *Init) {
1474 auto LTResult = getEntityLifetime(&Entity);
1475 LifetimeKind LK = LTResult.getInt();
1476 const InitializedEntity *ExtendingEntity = LTResult.getPointer();
1477 checkExprLifetimeImpl(SemaRef, &Entity, ExtendingEntity, LK,
1478 /*AEntity=*/nullptr, /*CapEntity=*/nullptr, Init);
1479}
1480
1482 const InitializedEntity &Entity, Expr *Init) {
1483 checkExprLifetimeImpl(SemaRef, &Entity, nullptr, LK_MustTail,
1484 /*AEntity=*/nullptr, /*CapEntity=*/nullptr, Init);
1485}
1486
1487void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity,
1488 Expr *Init) {
1489 bool EnableDanglingPointerAssignment = !SemaRef.getDiagnostics().isIgnored(
1490 diag::warn_dangling_pointer_assignment, SourceLocation());
1491 bool RunAnalysis = (EnableDanglingPointerAssignment &&
1492 Entity.LHS->getType()->isPointerType()) ||
1493 shouldRunGSLAssignmentAnalysis(SemaRef, Entity);
1494
1495 if (!RunAnalysis)
1496 return;
1497
1498 checkExprLifetimeImpl(SemaRef, /*InitEntity=*/nullptr,
1499 /*ExtendingEntity=*/nullptr, LK_Assignment, &Entity,
1500 /*CapEntity=*/nullptr, Init);
1501}
1502
1503void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity,
1504 Expr *Init) {
1505 if (SemaRef.getDiagnostics().isIgnored(diag::warn_dangling_reference_captured,
1506 SourceLocation()) &&
1507 SemaRef.getDiagnostics().isIgnored(
1508 diag::warn_dangling_reference_captured_by_unknown, SourceLocation()))
1509 return;
1510 return checkExprLifetimeImpl(SemaRef, /*InitEntity=*/nullptr,
1511 /*ExtendingEntity=*/nullptr, LK_LifetimeCapture,
1512 /*AEntity=*/nullptr,
1513 /*CapEntity=*/&Entity, Init);
1514}
1515
1516} // namespace clang::sema
C Language Family Type Representation.
Represents binding an expression to a temporary.
Definition ExprCXX.h:1493
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1691
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3676
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:573
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
SourceLocation getLocation() const
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:577
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
This represents one expression.
Definition Expr.h:112
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
QualType getType() const
Definition Expr.h:144
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
QualType getReturnType() const
Definition Decl.h:2845
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4313
bool param_empty() const
Definition Decl.h:2785
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3826
size_t param_size() const
Definition Decl.h:2790
Describes an C or C++ initializer list.
Definition Expr.h:5299
Describes an entity that is being initialized.
EntityKind getKind() const
Determine the kind of initialization.
unsigned allocateManglingNumber() const
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
@ EK_Variable
The entity being initialized is a variable.
@ EK_Temporary
The entity being initialized is a temporary object.
@ EK_Binding
The entity being initialized is a structured binding of a decomposition declaration.
@ EK_BlockElement
The entity being initialized is a field of block descriptor for the copied-in c++ object.
@ EK_MatrixElement
The entity being initialized is an element of a matrix.
@ EK_Parameter_CF_Audited
The entity being initialized is a function parameter; function is member of group of audited CF APIs.
@ EK_LambdaToBlockConversionBlockElement
The entity being initialized is a field of block descriptor for the copied-in lambda object that's us...
@ EK_Member
The entity being initialized is a non-static data member subobject.
@ EK_Base
The entity being initialized is a base member subobject.
@ EK_Result
The entity being initialized is the result of a function call.
@ EK_TemplateParameter
The entity being initialized is a non-type template parameter.
@ EK_StmtExprResult
The entity being initialized is the result of a statement expression.
@ EK_ParenAggInitMember
The entity being initialized is a non-static data member subobject of an object initialized via paren...
@ EK_VectorElement
The entity being initialized is an element of a vector.
@ EK_New
The entity being initialized is an object (or array of objects) allocated via new.
@ EK_CompoundLiteralInit
The entity being initialized is the initializer for a compound literal.
@ EK_Parameter
The entity being initialized is a function parameter.
@ EK_Delegating
The initialization is being done by a delegating constructor.
@ EK_ComplexElement
The entity being initialized is the real or imaginary part of a complex number.
@ EK_ArrayElement
The entity being initialized is an element of an array.
@ EK_LambdaCapture
The entity being initialized is the field that captures a variable in a lambda.
@ EK_Exception
The entity being initialized is an exception object that is being thrown.
@ EK_RelatedResult
The entity being implicitly initialized back to the formal result type.
bool isDefaultMemberInitializer() const
Is this the default member initializer of a member (specified inside the class definition)?
Describes the capture of a variable or of this, or of a C++1y init-capture.
bool capturesVariable() const
Determine whether this capture handles a variable.
const LambdaCapture * capture_iterator
An iterator that walks over the captures of the lambda, both implicit and explicit.
Definition ExprCXX.h:2033
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3364
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represents a parameter to a function.
Definition Decl.h:1790
Represents a struct/union/class.
Definition Decl.h:4324
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3574
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:856
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:924
const LangOptions & getLangOpts() const
Definition Sema.h:920
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
@ Type
The template argument is a type.
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:1952
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isPointerType() const
Definition TypeBase.h:8529
bool isReferenceType() const
Definition TypeBase.h:8553
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isPointerOrReferenceType() const
Definition TypeBase.h:8533
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5582
Represents a variable declaration or definition.
Definition Decl.h:926
bool isCXXForRangeImplicitVar() const
Whether this variable is the implicit '__range' variable in C++ range-based for loops.
Definition Decl.h:1622
#define bool
Definition gpuintrin.h:32
bool isGslPointerType(QualType QT)
bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee, bool RunningUnderLifetimeSafety)
bool shouldTrackFirstArgument(const FunctionDecl *FD)
bool isAssignmentOperatorLifetimeBound(const CXXMethodDecl *CMD)
bool isPointerLikeType(QualType QT)
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
const FunctionDecl * getDeclWithMergedLifetimeBoundAttrs(const FunctionDecl *FD)
bool isGslOwnerType(QualType QT)
bool isInStlNamespace(const Decl *D)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
static bool isStdInitializerListOfPointer(const RecordDecl *RD)
bool isGslPointerType(QualType QT)
static void checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity, const InitializedEntity *ExtendingEntity, LifetimeKind LK, const AssignedEntity *AEntity, const CapturingEntity *CapEntity, Expr *Init)
static bool shouldRunGSLAssignmentAnalysis(const Sema &SemaRef, const AssignedEntity &Entity)
static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, Expr *Init, ReferenceKind RK, LocalVisitor Visit)
Visit the locals that would be reachable through a reference bound to the glvalue expression Init.
void checkExprLifetimeMustTailArg(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient, assuming that it is pas...
static bool pathOnlyHandlesGslPointer(const IndirectLocalPath &Path)
static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, Expr *Init, LocalVisitor Visit, bool RevisitSubinits)
Visit the locals that would be reachable through an object initialized by the prvalue expression Init...
static AnalysisResult analyzePathForGSLPointer(const IndirectLocalPath &Path, Local L, LifetimeKind LK)
static bool isContainerOfOwner(const RecordDecl *Container)
static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, Expr *E)
Find the range for the first interesting entry in the path at or after I.
static LifetimeResult getEntityLifetime(const InitializedEntity *Entity, const InitializedEntity *InitField=nullptr)
Determine the declaration which an initialized entity ultimately refers to, for the purpose of lifeti...
static bool isContainerOfPointer(const RecordDecl *Container)
void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
static bool isCopyLikeConstructor(const CXXConstructorDecl *Ctor)
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
static bool shouldTrackFirstArgumentForConstructor(const CXXConstructExpr *Ctor)
bool isGslOwnerType(QualType QT)
PathLifetimeKind
Whether a path to an object supports lifetime extension.
@ NoExtend
Do not lifetime extend along this path.
@ Extend
Lifetime-extend along this path.
static bool isVarOnPath(const IndirectLocalPath &Path, VarDecl *VD)
static bool pathContainsInit(const IndirectLocalPath &Path)
static void visitFunctionCallArguments(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
static PathLifetimeKind shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path)
Determine whether this is an indirect path to a temporary that we are supposed to lifetime-extend alo...
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
U cast(CodeGen::Address addr)
Definition Address.h:327
Describes an entity that is being assigned.