Debian Codegraph @

clang/lib/Sema/CheckExprLifetime.cpp

raw
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"
13 #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
14 #include "clang/Basic/DiagnosticSema.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Sema.h"
17 #include "llvm/ADT/PointerIntPair.h"
18
19 namespace clang::sema {
20 using lifetimes::isGslOwnerType;
21 using lifetimes::isGslPointerType;
22
23 namespace {
24 enum 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 };
62 using 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.
69 static LifetimeResult
70 getEntityLifetime(const InitializedEntity *Entity,
71 const InitializedEntity *InitField = nullptr) {
72 // C++11 [class.temporary]p5:
73 switch (Entity->getKind()) {
74 case InitializedEntity::EK_Variable:
75 // The temporary [...] persists for the lifetime of the reference
76 return {Entity, LK_Extended};
77
78 case InitializedEntity::EK_Member:
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
98 case InitializedEntity::EK_Binding:
99 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
100 // type.
101 return {Entity, LK_Extended};
102
103 case InitializedEntity::EK_Parameter:
104 case InitializedEntity::EK_Parameter_CF_Audited:
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
110 case InitializedEntity::EK_TemplateParameter:
111 // FIXME: This will always be ill-formed; should we eagerly diagnose it
112 // here?
113 return {nullptr, LK_FullExpression};
114
115 case InitializedEntity::EK_Result:
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
121 case InitializedEntity::EK_StmtExprResult:
122 // FIXME: Should we lifetime-extend through the result of a statement
123 // expression?
124 return {nullptr, LK_StmtExprResult};
125
126 case InitializedEntity::EK_New:
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
132 case InitializedEntity::EK_Temporary:
133 case InitializedEntity::EK_CompoundLiteralInit:
134 case InitializedEntity::EK_RelatedResult:
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
140 case InitializedEntity::EK_ArrayElement:
141 // For subobjects, we look at the complete object.
142 return getEntityLifetime(Entity->getParent(), InitField);
143
144 case InitializedEntity::EK_Base:
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
150 case InitializedEntity::EK_Delegating:
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
157 case InitializedEntity::EK_BlockElement:
158 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
159 case InitializedEntity::EK_LambdaCapture:
160 case InitializedEntity::EK_VectorElement:
161 case InitializedEntity::EK_MatrixElement:
162 case InitializedEntity::EK_ComplexElement:
163 return {nullptr, LK_FullExpression};
164
165 case InitializedEntity::EK_Exception:
166 // FIXME: Can we diagnose lifetime problems with exceptions?
167 return {nullptr, LK_FullExpression};
168
169 case InitializedEntity::EK_ParenAggInitMember:
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
180 namespace {
181 enum 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.
194 using 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.
199 struct 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
228 using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
229
230 struct RevertToOldSizeRAII {
231 IndirectLocalPath &Path;
232 unsigned OldSize = Path.size();
233 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
234 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
235 };
236
237 using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
238 ReferenceKind RK)>;
239 } // namespace
240
241 static 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
248 static 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
255 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
256 Expr *Init, LocalVisitor Visit,
257 bool RevisitSubinits);
258
259 static 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>.
265 static 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 }
276 static 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>`.
289 static bool isStdInitializerListOfPointer(const RecordDecl *RD) {
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>&)`.
303 static bool isCopyLikeConstructor(const CXXConstructorDecl *Ctor) {
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.
323 static bool
324 shouldTrackFirstArgumentForConstructor(const CXXConstructExpr *Ctor) {
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 intializer_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()};
354 if (isStdInitializerListOfPointer(RHSRD))
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 =
387 Ctor->getConstructor()->getPrimaryTemplate();
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.
399 static 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;
480 if (lifetimes::implicitObjectParamIsLifetimeBound(Callee) ||
481 CheckCoroObjArg)
482 VisitLifetimeBoundArg(Callee, ObjectArg);
483 else if (EnableGSLAnalysis) {
484 if (auto *CME = dyn_cast<CXXMethodDecl>(Callee);
485 CME && lifetimes::shouldTrackImplicitObjectArg(CME))
486 VisitGSLPointerArg(Callee, ObjectArg);
487 }
488 }
489
490 const FunctionDecl *CanonCallee =
491 lifetimes::getDeclWithMergedLifetimeBoundAttrs(Callee);
492 unsigned NP = std::min(Callee->getNumParams(), CanonCallee->getNumParams());
493 for (unsigned I = 0, N = std::min<unsigned>(NP, Args.size()); I != N; ++I) {
494 Expr *Arg = Args[I];
495 RevertToOldSizeRAII RAII(Path);
496 if (auto *DAE = dyn_cast<CXXDefaultArgExpr>(Arg)) {
497 Path.push_back(
498 {IndirectLocalPathEntry::DefaultArg, DAE, DAE->getParam()});
499 Arg = DAE->getExpr();
500 }
501 if (CheckCoroCall ||
502 CanonCallee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
503 VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
504 else if (const auto *CaptureAttr =
505 CanonCallee->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>();
506 CaptureAttr && isa<CXXConstructorDecl>(CanonCallee) &&
507 llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
508 return ArgIdx == LifetimeCaptureByAttr::This;
509 }))
510 // `lifetime_capture_by(this)` in a class constructor has the same
511 // semantics as `lifetimebound`:
512 //
513 // struct Foo {
514 // const int& a;
515 // // Equivalent to Foo(const int& t [[clang::lifetimebound]])
516 // Foo(const int& t [[clang::lifetime_capture_by(this)]]) : a(t) {}
517 // };
518 //
519 // In the implementation, `lifetime_capture_by` is treated as an alias for
520 // `lifetimebound` and shares the same code path. This implies the emitted
521 // diagnostics will be emitted under `-Wdangling`, not
522 // `-Wdangling-capture`.
523 VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
524 else if (EnableGSLAnalysis && I == 0) {
525 // Perform GSL analysis for the first argument
526 if (lifetimes::shouldTrackFirstArgument(CanonCallee)) {
527 VisitGSLPointerArg(CanonCallee, Arg);
528 } else if (auto *Ctor = dyn_cast<CXXConstructExpr>(Call);
529 Ctor && shouldTrackFirstArgumentForConstructor(Ctor)) {
530 VisitGSLPointerArg(Ctor->getConstructor(), Arg);
531 }
532 }
533 }
534 }
535
536 /// Visit the locals that would be reachable through a reference bound to the
537 /// glvalue expression \c Init.
538 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
539 Expr *Init, ReferenceKind RK,
540 LocalVisitor Visit) {
541 RevertToOldSizeRAII RAII(Path);
542
543 // Walk past any constructs which we can lifetime-extend across.
544 Expr *Old;
545 do {
546 Old = Init;
547
548 if (auto *FE = dyn_cast<FullExpr>(Init))
549 Init = FE->getSubExpr();
550
551 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
552 // If this is just redundant braces around an initializer, step over it.
553 if (ILE->isTransparent())
554 Init = ILE->getInit(0);
555 }
556
557 if (MemberExpr *ME = dyn_cast<MemberExpr>(Init->IgnoreImpCasts()))
558 Path.push_back(
559 {IndirectLocalPathEntry::MemberExpr, ME, ME->getMemberDecl()});
560 // Step over any subobject adjustments; we may have a materialized
561 // temporary inside them.
562 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
563
564 // Per current approach for DR1376, look through casts to reference type
565 // when performing lifetime extension.
566 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
567 if (CE->getSubExpr()->isGLValue())
568 Init = CE->getSubExpr();
569
570 // Per the current approach for DR1299, look through array element access
571 // on array glvalues when performing lifetime extension.
572 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
573 Init = ASE->getBase();
574 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
575 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
576 Init = ICE->getSubExpr();
577 else
578 // We can't lifetime extend through this but we might still find some
579 // retained temporaries.
580 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
581 }
582
583 // Step into CXXDefaultInitExprs so we can diagnose cases where a
584 // constructor inherits one as an implicit mem-initializer.
585 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
586 Path.push_back(
587 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
588 Init = DIE->getExpr();
589 }
590 } while (Init != Old);
591
592 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
593 if (Visit(Path, Local(MTE), RK))
594 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true);
595 }
596
597 if (auto *M = dyn_cast<MemberExpr>(Init)) {
598 // Lifetime of a non-reference type field is same as base object.
599 if (auto *F = dyn_cast<FieldDecl>(M->getMemberDecl());
600 F && !F->getType()->isReferenceType())
601 visitLocalsRetainedByInitializer(Path, M->getBase(), Visit, true);
602 }
603
604 if (isa<CallExpr>(Init))
605 return visitFunctionCallArguments(Path, Init, Visit);
606
607 switch (Init->getStmtClass()) {
608 case Stmt::DeclRefExprClass: {
609 // If we find the name of a local non-reference parameter, we could have a
610 // lifetime problem.
611 auto *DRE = cast<DeclRefExpr>(Init);
612 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
613 if (VD && VD->hasLocalStorage() &&
614 !DRE->refersToEnclosingVariableOrCapture()) {
615 if (!VD->getType()->isReferenceType()) {
616 Visit(Path, Local(DRE), RK);
617 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
618 // The lifetime of a reference parameter is unknown; assume it's OK
619 // for now.
620 break;
621 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
622 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
623 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
624 RK_ReferenceBinding, Visit);
625 }
626 }
627 break;
628 }
629
630 case Stmt::UnaryOperatorClass: {
631 // The only unary operator that make sense to handle here
632 // is Deref. All others don't resolve to a "name." This includes
633 // handling all sorts of rvalues passed to a unary operator.
634 const UnaryOperator *U = cast<UnaryOperator>(Init);
635 if (U->getOpcode() == UO_Deref)
636 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
637 break;
638 }
639
640 case Stmt::ArraySectionExprClass: {
641 visitLocalsRetainedByInitializer(
642 Path, cast<ArraySectionExpr>(Init)->getBase(), Visit, true);
643 break;
644 }
645
646 case Stmt::ConditionalOperatorClass:
647 case Stmt::BinaryConditionalOperatorClass: {
648 auto *C = cast<AbstractConditionalOperator>(Init);
649 if (!C->getTrueExpr()->getType()->isVoidType())
650 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
651 if (!C->getFalseExpr()->getType()->isVoidType())
652 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
653 break;
654 }
655
656 case Stmt::CompoundLiteralExprClass: {
657 if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Init)) {
658 if (!CLE->isFileScope())
659 Visit(Path, Local(CLE), RK);
660 }
661 break;
662 }
663
664 // FIXME: Visit the left-hand side of an -> or ->*.
665
666 default:
667 break;
668 }
669 }
670
671 /// Visit the locals that would be reachable through an object initialized by
672 /// the prvalue expression \c Init.
673 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
674 Expr *Init, LocalVisitor Visit,
675 bool RevisitSubinits) {
676 RevertToOldSizeRAII RAII(Path);
677
678 Expr *Old;
679 do {
680 Old = Init;
681
682 // Step into CXXDefaultInitExprs so we can diagnose cases where a
683 // constructor inherits one as an implicit mem-initializer.
684 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
685 Path.push_back(
686 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
687 Init = DIE->getExpr();
688 }
689
690 if (auto *FE = dyn_cast<FullExpr>(Init))
691 Init = FE->getSubExpr();
692
693 // Dig out the expression which constructs the extended temporary.
694 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
695
696 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
697 Init = BTE->getSubExpr();
698
699 Init = Init->IgnoreParens();
700
701 // Step over value-preserving rvalue casts.
702 if (auto *CE = dyn_cast<CastExpr>(Init)) {
703 switch (CE->getCastKind()) {
704 case CK_LValueToRValue:
705 // If we can match the lvalue to a const object, we can look at its
706 // initializer.
707 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
708 return visitLocalsRetainedByReferenceBinding(
709 Path, Init, RK_ReferenceBinding,
710 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
711 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
712 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
713 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
714 !isVarOnPath(Path, VD)) {
715 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
716 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit,
717 true);
718 }
719 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
720 if (MTE->getType().isConstQualified())
721 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(),
722 Visit, true);
723 }
724 return false;
725 });
726
727 // We assume that objects can be retained by pointers cast to integers,
728 // but not if the integer is cast to floating-point type or to _Complex.
729 // We assume that casts to 'bool' do not preserve enough information to
730 // retain a local object.
731 case CK_NoOp:
732 case CK_BitCast:
733 case CK_BaseToDerived:
734 case CK_DerivedToBase:
735 case CK_UncheckedDerivedToBase:
736 case CK_Dynamic:
737 case CK_ToUnion:
738 case CK_UserDefinedConversion:
739 case CK_ConstructorConversion:
740 case CK_IntegralToPointer:
741 case CK_PointerToIntegral:
742 case CK_VectorSplat:
743 case CK_IntegralCast:
744 case CK_CPointerToObjCPointerCast:
745 case CK_BlockPointerToObjCPointerCast:
746 case CK_AnyPointerToBlockPointerCast:
747 case CK_AddressSpaceConversion:
748 break;
749
750 case CK_ArrayToPointerDecay:
751 // Model array-to-pointer decay as taking the address of the array
752 // lvalue.
753 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
754 return visitLocalsRetainedByReferenceBinding(
755 Path, CE->getSubExpr(), RK_ReferenceBinding, Visit);
756
757 default:
758 return;
759 }
760
761 Init = CE->getSubExpr();
762 }
763 } while (Old != Init);
764
765 // C++17 [dcl.init.list]p6:
766 // initializing an initializer_list object from the array extends the
767 // lifetime of the array exactly like binding a reference to a temporary.
768 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
769 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
770 RK_StdInitializerList, Visit);
771
772 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
773 // We already visited the elements of this initializer list while
774 // performing the initialization. Don't visit them again unless we've
775 // changed the lifetime of the initialized entity.
776 if (!RevisitSubinits)
777 return;
778
779 if (ILE->isTransparent())
780 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
781 RevisitSubinits);
782
783 if (ILE->getType()->isArrayType()) {
784 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
785 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
786 RevisitSubinits);
787 return;
788 }
789
790 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
791 assert(RD->isAggregate() && "aggregate init on non-aggregate");
792
793 // If we lifetime-extend a braced initializer which is initializing an
794 // aggregate, and that aggregate contains reference members which are
795 // bound to temporaries, those temporaries are also lifetime-extended.
796 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
797 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
798 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
799 RK_ReferenceBinding, Visit);
800 else {
801 unsigned Index = 0;
802 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
803 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
804 RevisitSubinits);
805 for (const auto *I : RD->fields()) {
806 if (Index >= ILE->getNumInits())
807 break;
808 if (I->isUnnamedBitField())
809 continue;
810 Expr *SubInit = ILE->getInit(Index);
811 if (I->getType()->isReferenceType())
812 visitLocalsRetainedByReferenceBinding(Path, SubInit,
813 RK_ReferenceBinding, Visit);
814 else
815 // This might be either aggregate-initialization of a member or
816 // initialization of a std::initializer_list object. Regardless,
817 // we should recursively lifetime-extend that initializer.
818 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
819 RevisitSubinits);
820 ++Index;
821 }
822 }
823 }
824 return;
825 }
826
827 // The lifetime of an init-capture is that of the closure object constructed
828 // by a lambda-expression.
829 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
830 LambdaExpr::capture_iterator CapI = LE->capture_begin();
831 for (Expr *E : LE->capture_inits()) {
832 assert(CapI != LE->capture_end());
833 const LambdaCapture &Cap = *CapI++;
834 if (!E)
835 continue;
836 if (Cap.capturesVariable())
837 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
838 if (E->isGLValue())
839 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
840 Visit);
841 else
842 visitLocalsRetainedByInitializer(Path, E, Visit, true);
843 if (Cap.capturesVariable())
844 Path.pop_back();
845 }
846 }
847
848 // Assume that a copy or move from a temporary references the same objects
849 // that the temporary does.
850 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
851 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
852 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
853 Expr *Arg = MTE->getSubExpr();
854 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
855 CCE->getConstructor()});
856 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
857 Path.pop_back();
858 }
859 }
860 }
861
862 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init))
863 return visitFunctionCallArguments(Path, Init, Visit);
864
865 if (auto *CPE = dyn_cast<CXXParenListInitExpr>(Init)) {
866 RevertToOldSizeRAII RAII(Path);
867 Path.push_back({IndirectLocalPathEntry::ParenAggInit, CPE});
868 for (auto *I : CPE->getInitExprs()) {
869 if (I->isGLValue())
870 visitLocalsRetainedByReferenceBinding(Path, I, RK_ReferenceBinding,
871 Visit);
872 else
873 visitLocalsRetainedByInitializer(Path, I, Visit, true);
874 }
875 }
876 switch (Init->getStmtClass()) {
877 case Stmt::UnaryOperatorClass: {
878 auto *UO = cast<UnaryOperator>(Init);
879 // If the initializer is the address of a local, we could have a lifetime
880 // problem.
881 if (UO->getOpcode() == UO_AddrOf) {
882 // If this is &rvalue, then it's ill-formed and we have already diagnosed
883 // it. Don't produce a redundant warning about the lifetime of the
884 // temporary.
885 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
886 return;
887
888 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
889 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
890 RK_ReferenceBinding, Visit);
891 }
892 break;
893 }
894
895 case Stmt::BinaryOperatorClass: {
896 // Handle pointer arithmetic.
897 auto *BO = cast<BinaryOperator>(Init);
898 BinaryOperatorKind BOK = BO->getOpcode();
899 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
900 break;
901
902 if (BO->getLHS()->getType()->isPointerType())
903 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
904 else if (BO->getRHS()->getType()->isPointerType())
905 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
906 break;
907 }
908
909 case Stmt::ConditionalOperatorClass:
910 case Stmt::BinaryConditionalOperatorClass: {
911 auto *C = cast<AbstractConditionalOperator>(Init);
912 // In C++, we can have a throw-expression operand, which has 'void' type
913 // and isn't interesting from a lifetime perspective.
914 if (!C->getTrueExpr()->getType()->isVoidType())
915 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
916 if (!C->getFalseExpr()->getType()->isVoidType())
917 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
918 break;
919 }
920
921 case Stmt::BlockExprClass:
922 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
923 // This is a local block, whose lifetime is that of the function.
924 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
925 }
926 break;
927
928 case Stmt::AddrLabelExprClass:
929 // We want to warn if the address of a label would escape the function.
930 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
931 break;
932
933 default:
934 break;
935 }
936 }
937
938 /// Whether a path to an object supports lifetime extension.
939 enum PathLifetimeKind {
940 /// Lifetime-extend along this path.
941 Extend,
942 /// Do not lifetime extend along this path.
943 NoExtend
944 };
945
946 /// Determine whether this is an indirect path to a temporary that we are
947 /// supposed to lifetime-extend along.
948 static PathLifetimeKind
949 shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
950 for (auto Elem : Path) {
951 if (Elem.Kind == IndirectLocalPathEntry::MemberExpr ||
952 Elem.Kind == IndirectLocalPathEntry::LambdaCaptureInit)
953 continue;
954 return Elem.Kind == IndirectLocalPathEntry::DefaultInit
955 ? PathLifetimeKind::Extend
956 : PathLifetimeKind::NoExtend;
957 }
958 return PathLifetimeKind::Extend;
959 }
960
961 /// Find the range for the first interesting entry in the path at or after I.
962 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
963 Expr *E) {
964 for (unsigned N = Path.size(); I != N; ++I) {
965 switch (Path[I].Kind) {
966 case IndirectLocalPathEntry::AddressOf:
967 case IndirectLocalPathEntry::LValToRVal:
968 case IndirectLocalPathEntry::LifetimeBoundCall:
969 case IndirectLocalPathEntry::TemporaryCopy:
970 case IndirectLocalPathEntry::GslReferenceInit:
971 case IndirectLocalPathEntry::GslPointerInit:
972 case IndirectLocalPathEntry::GslPointerAssignment:
973 case IndirectLocalPathEntry::ParenAggInit:
974 case IndirectLocalPathEntry::MemberExpr:
975 // These exist primarily to mark the path as not permitting or
976 // supporting lifetime extension.
977 break;
978
979 case IndirectLocalPathEntry::VarInit:
980 if (cast<VarDecl>(Path[I].D)->isImplicit())
981 return SourceRange();
982 [[fallthrough]];
983 case IndirectLocalPathEntry::DefaultInit:
984 return Path[I].E->getSourceRange();
985
986 case IndirectLocalPathEntry::LambdaCaptureInit:
987 if (!Path[I].Capture->capturesVariable())
988 continue;
989 return Path[I].E->getSourceRange();
990
991 case IndirectLocalPathEntry::DefaultArg:
992 return cast<CXXDefaultArgExpr>(Path[I].E)->getUsedLocation();
993 }
994 }
995 return E->getSourceRange();
996 }
997
998 static bool pathOnlyHandlesGslPointer(const IndirectLocalPath &Path) {
999 for (const auto &It : llvm::reverse(Path)) {
1000 switch (It.Kind) {
1001 case IndirectLocalPathEntry::VarInit:
1002 case IndirectLocalPathEntry::AddressOf:
1003 case IndirectLocalPathEntry::LifetimeBoundCall:
1004 case IndirectLocalPathEntry::MemberExpr:
1005 continue;
1006 case IndirectLocalPathEntry::GslPointerInit:
1007 case IndirectLocalPathEntry::GslReferenceInit:
1008 case IndirectLocalPathEntry::GslPointerAssignment:
1009 return true;
1010 default:
1011 return false;
1012 }
1013 }
1014 return false;
1015 }
1016 // Result of analyzing the Path for GSLPointer.
1017 enum AnalysisResult {
1018 // Path does not correspond to a GSLPointer.
1019 NotGSLPointer,
1020
1021 // A relevant case was identified.
1022 Report,
1023 // Stop the entire traversal.
1024 Abandon,
1025 // Skip this step and continue traversing inner AST nodes.
1026 Skip,
1027 };
1028 // Analyze cases where a GSLPointer is initialized or assigned from a
1029 // temporary owner object.
1030 static AnalysisResult analyzePathForGSLPointer(const IndirectLocalPath &Path,
1031 Local L, LifetimeKind LK) {
1032 if (!pathOnlyHandlesGslPointer(Path))
1033 return NotGSLPointer;
1034
1035 // At this point, Path represents a series of operations involving a
1036 // GSLPointer, either in the process of initialization or assignment.
1037
1038 // Process temporary base objects for MemberExpr cases, e.g. Temp().field.
1039 for (const auto &E : Path) {
1040 if (E.Kind == IndirectLocalPathEntry::MemberExpr) {
1041 // Avoid interfering with the local base object.
1042 if (pathContainsInit(Path))
1043 return Abandon;
1044
1045 // We are not interested in the temporary base objects of gsl Pointers:
1046 // auto p1 = Temp().ptr; // Here p1 might not dangle.
1047 // However, we want to diagnose for gsl owner fields:
1048 // auto p2 = Temp().owner; // Here p2 is dangling.
1049 if (const auto *FD = llvm::dyn_cast_or_null<FieldDecl>(E.D);
1050 FD && !FD->getType()->isReferenceType() &&
1051 isGslOwnerType(FD->getType()) && LK != LK_MemInitializer) {
1052 return Report;
1053 }
1054 return Abandon;
1055 }
1056 }
1057
1058 // Note: A LifetimeBoundCall can appear interleaved in this sequence.
1059 // For example:
1060 // const std::string& Ref(const std::string& a [[clang::lifetimebound]]);
1061 // string_view abc = Ref(std::string());
1062 // The "Path" is [GSLPointerInit, LifetimeboundCall], where "L" is the
1063 // temporary "std::string()" object. We need to check the return type of the
1064 // function with the lifetimebound attribute.
1065 if (Path.back().Kind == IndirectLocalPathEntry::LifetimeBoundCall) {
1066 // The lifetimebound applies to the implicit object parameter of a method.
1067 const FunctionDecl *FD =
1068 llvm::dyn_cast_or_null<FunctionDecl>(Path.back().D);
1069 // The lifetimebound applies to a function parameter.
1070 if (const auto *PD = llvm::dyn_cast<ParmVarDecl>(Path.back().D))
1071 FD = llvm::dyn_cast<FunctionDecl>(PD->getDeclContext());
1072
1073 if (isa_and_present<CXXConstructorDecl>(FD)) {
1074 // Constructor case: the parameter is annotated with lifetimebound
1075 // e.g., GSLPointer(const S& s [[clang::lifetimebound]])
1076 // We still respect this case even the type S is not an owner.
1077 return Report;
1078 }
1079 // Check the return type, e.g.
1080 // const GSLOwner& func(const Foo& foo [[clang::lifetimebound]])
1081 // GSLOwner* func(cosnt Foo& foo [[clang::lifetimebound]])
1082 // GSLPointer func(const Foo& foo [[clang::lifetimebound]])
1083 if (FD && ((FD->getReturnType()->isPointerOrReferenceType() &&
1084 isGslOwnerType(FD->getReturnType()->getPointeeType())) ||
1085 isGslPointerType(FD->getReturnType())))
1086 return Report;
1087
1088 return Abandon;
1089 }
1090
1091 if (isa<DeclRefExpr>(L)) {
1092 // We do not want to follow the references when returning a pointer
1093 // originating from a local owner to avoid the following false positive:
1094 // int &p = *localUniquePtr;
1095 // someContainer.add(std::move(localUniquePtr));
1096 // return p;
1097 if (!pathContainsInit(Path) && isGslOwnerType(L->getType()))
1098 return Report;
1099 return Abandon;
1100 }
1101
1102 // The GSLPointer is from a temporary object.
1103 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
1104
1105 bool IsGslPtrValueFromGslTempOwner =
1106 MTE && !MTE->getExtendingDecl() && isGslOwnerType(MTE->getType());
1107 // Skipping a chain of initializing gsl::Pointer annotated objects.
1108 // We are looking only for the final source to find out if it was
1109 // a local or temporary owner or the address of a local
1110 // variable/param.
1111 if (!IsGslPtrValueFromGslTempOwner)
1112 return Skip;
1113 return Report;
1114 }
1115
1116 static bool shouldRunGSLAssignmentAnalysis(const Sema &SemaRef,
1117 const AssignedEntity &Entity) {
1118 bool EnableGSLAssignmentWarnings = !SemaRef.getDiagnostics().isIgnored(
1119 diag::warn_dangling_lifetime_pointer_assignment, SourceLocation());
1120 return (EnableGSLAssignmentWarnings &&
1121 (isGslPointerType(Entity.LHS->getType()) ||
1122 lifetimes::isAssignmentOperatorLifetimeBound(
1123 Entity.AssignmentOperator)));
1124 }
1125
1126 static void
1127 checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity,
1128 const InitializedEntity *ExtendingEntity, LifetimeKind LK,
1129 const AssignedEntity *AEntity,
1130 const CapturingEntity *CapEntity, Expr *Init) {
1131 assert(!AEntity || LK == LK_Assignment);
1132 assert(!CapEntity || LK == LK_LifetimeCapture);
1133 assert(!InitEntity || (LK != LK_Assignment && LK != LK_LifetimeCapture));
1134 // If this entity doesn't have an interesting lifetime, don't bother looking
1135 // for temporaries within its initializer.
1136 if (LK == LK_FullExpression)
1137 return;
1138
1139 // FIXME: consider moving the TemporaryVisitor and visitLocalsRetained*
1140 // functions to a dedicated class.
1141 auto TemporaryVisitor = [&](const IndirectLocalPath &Path, Local L,
1142 ReferenceKind RK) -> bool {
1143 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
1144 SourceLocation DiagLoc = DiagRange.getBegin();
1145
1146 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
1147
1148 bool IsGslPtrValueFromGslTempOwner = true;
1149 switch (analyzePathForGSLPointer(Path, L, LK)) {
1150 case Abandon:
1151 return false;
1152 case Skip:
1153 return true;
1154 case NotGSLPointer:
1155 IsGslPtrValueFromGslTempOwner = false;
1156 [[fallthrough]];
1157 case Report:
1158 break;
1159 }
1160
1161 switch (LK) {
1162 case LK_FullExpression:
1163 llvm_unreachable("already handled this");
1164
1165 case LK_Extended: {
1166 if (!MTE) {
1167 // The initialized entity has lifetime beyond the full-expression,
1168 // and the local entity does too, so don't warn.
1169 //
1170 // FIXME: We should consider warning if a static / thread storage
1171 // duration variable retains an automatic storage duration local.
1172 return false;
1173 }
1174
1175 switch (shouldLifetimeExtendThroughPath(Path)) {
1176 case PathLifetimeKind::Extend:
1177 // Update the storage duration of the materialized temporary.
1178 // FIXME: Rebuild the expression instead of mutating it.
1179 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
1180 ExtendingEntity->allocateManglingNumber());
1181 // Also visit the temporaries lifetime-extended by this initializer.
1182 return true;
1183
1184 case PathLifetimeKind::NoExtend:
1185 if (SemaRef.getLangOpts().CPlusPlus23 && InitEntity) {
1186 if (const VarDecl *VD =
1187 dyn_cast_if_present<VarDecl>(InitEntity->getDecl());
1188 VD && VD->isCXXForRangeImplicitVar()) {
1189 return false;
1190 }
1191 }
1192
1193 if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) {
1194 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
1195 << DiagRange;
1196 return false;
1197 }
1198
1199 // If the path goes through the initialization of a variable or field,
1200 // it can't possibly reach a temporary created in this full-expression.
1201 // We will have already diagnosed any problems with the initializer.
1202 if (pathContainsInit(Path))
1203 return false;
1204
1205 SemaRef.Diag(DiagLoc, diag::warn_dangling_variable)
1206 << RK << !InitEntity->getParent()
1207 << ExtendingEntity->getDecl()->isImplicit()
1208 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
1209 break;
1210 }
1211 break;
1212 }
1213
1214 case LK_LifetimeCapture: {
1215 // The captured entity has lifetime beyond the full-expression,
1216 // and the capturing entity does too, so don't warn.
1217 if (!MTE)
1218 return false;
1219 if (CapEntity->Entity)
1220 SemaRef.Diag(DiagLoc, diag::warn_dangling_reference_captured)
1221 << CapEntity->Entity << DiagRange;
1222 else
1223 SemaRef.Diag(DiagLoc, diag::warn_dangling_reference_captured_by_unknown)
1224 << DiagRange;
1225 return false;
1226 }
1227
1228 case LK_Assignment: {
1229 if (!MTE || pathContainsInit(Path))
1230 return false;
1231 if (IsGslPtrValueFromGslTempOwner)
1232 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_assignment)
1233 << AEntity->LHS << DiagRange;
1234 else
1235 SemaRef.Diag(DiagLoc, diag::warn_dangling_pointer_assignment)
1236 << AEntity->LHS->getType()->isPointerType() << AEntity->LHS
1237 << DiagRange;
1238 return false;
1239 }
1240 case LK_MemInitializer: {
1241 if (MTE) {
1242 // Under C++ DR1696, if a mem-initializer (or a default member
1243 // initializer used by the absence of one) would lifetime-extend a
1244 // temporary, the program is ill-formed.
1245 if (auto *ExtendingDecl =
1246 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
1247 if (IsGslPtrValueFromGslTempOwner) {
1248 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
1249 << ExtendingDecl << DiagRange;
1250 SemaRef.Diag(ExtendingDecl->getLocation(),
1251 diag::note_ref_or_ptr_member_declared_here)
1252 << true;
1253 return false;
1254 }
1255 bool IsSubobjectMember = ExtendingEntity != InitEntity;
1256 SemaRef.Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
1257 PathLifetimeKind::NoExtend
1258 ? diag::err_dangling_member
1259 : diag::warn_dangling_member)
1260 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
1261 // Don't bother adding a note pointing to the field if we're inside
1262 // its default member initializer; our primary diagnostic points to
1263 // the same place in that case.
1264 if (Path.empty() ||
1265 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
1266 SemaRef.Diag(ExtendingDecl->getLocation(),
1267 diag::note_lifetime_extending_member_declared_here)
1268 << RK << IsSubobjectMember;
1269 }
1270 } else {
1271 // We have a mem-initializer but no particular field within it; this
1272 // is either a base class or a delegating initializer directly
1273 // initializing the base-class from something that doesn't live long
1274 // enough.
1275 //
1276 // FIXME: Warn on this.
1277 return false;
1278 }
1279 } else {
1280 // Paths via a default initializer can only occur during error recovery
1281 // (there's no other way that a default initializer can refer to a
1282 // local). Don't produce a bogus warning on those cases.
1283 if (pathContainsInit(Path))
1284 return false;
1285
1286 auto *DRE = dyn_cast<DeclRefExpr>(L);
1287 // Suppress false positives for code like the one below:
1288 // Ctor(unique_ptr<T> up) : pointer(up.get()), owner(move(up)) {}
1289 // FIXME: move this logic to analyzePathForGSLPointer.
1290 if (DRE && isGslOwnerType(DRE->getType()))
1291 return false;
1292
1293 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
1294 if (!VD) {
1295 // A member was initialized to a local block.
1296 // FIXME: Warn on this.
1297 return false;
1298 }
1299
1300 if (auto *Member =
1301 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
1302 bool IsPointer = !Member->getType()->isReferenceType();
1303 SemaRef.Diag(DiagLoc,
1304 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1305 : diag::warn_bind_ref_member_to_parameter)
1306 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
1307 SemaRef.Diag(Member->getLocation(),
1308 diag::note_ref_or_ptr_member_declared_here)
1309 << (unsigned)IsPointer;
1310 }
1311 }
1312 break;
1313 }
1314
1315 case LK_New:
1316 if (isa<MaterializeTemporaryExpr>(L)) {
1317 if (IsGslPtrValueFromGslTempOwner)
1318 SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
1319 << DiagRange;
1320 else
1321 SemaRef.Diag(DiagLoc, RK == RK_ReferenceBinding
1322 ? diag::warn_new_dangling_reference
1323 : diag::warn_new_dangling_initializer_list)
1324 << !InitEntity->getParent() << DiagRange;
1325 } else {
1326 // We can't determine if the allocation outlives the local declaration.
1327 return false;
1328 }
1329 break;
1330
1331 case LK_Return:
1332 case LK_MustTail:
1333 case LK_StmtExprResult:
1334 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
1335 // We can't determine if the local variable outlives the statement
1336 // expression.
1337 if (LK == LK_StmtExprResult)
1338 return false;
1339 SemaRef.Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
1340 << InitEntity->getType()->isReferenceType() << DRE->getDecl()
1341 << isa<ParmVarDecl>(DRE->getDecl()) << (LK == LK_MustTail)
1342 << DiagRange;
1343 } else if (isa<BlockExpr>(L)) {
1344 SemaRef.Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
1345 } else if (isa<AddrLabelExpr>(L)) {
1346 // Don't warn when returning a label from a statement expression.
1347 // Leaving the scope doesn't end its lifetime.
1348 if (LK == LK_StmtExprResult)
1349 return false;
1350 SemaRef.Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
1351 } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(L)) {
1352 SemaRef.Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
1353 << InitEntity->getType()->isReferenceType() << CLE->getInitializer()
1354 << 2 << (LK == LK_MustTail) << DiagRange;
1355 } else {
1356 // P2748R5: Disallow Binding a Returned Glvalue to a Temporary.
1357 // [stmt.return]/p6: In a function whose return type is a reference,
1358 // other than an invented function for std::is_convertible ([meta.rel]),
1359 // a return statement that binds the returned reference to a temporary
1360 // expression ([class.temporary]) is ill-formed.
1361 if (SemaRef.getLangOpts().CPlusPlus26 &&
1362 InitEntity->getType()->isReferenceType())
1363 SemaRef.Diag(DiagLoc, diag::err_ret_local_temp_ref)
1364 << InitEntity->getType()->isReferenceType() << DiagRange;
1365 else if (LK == LK_MustTail)
1366 SemaRef.Diag(DiagLoc, diag::warn_musttail_local_temp_addr_ref)
1367 << InitEntity->getType()->isReferenceType() << DiagRange;
1368 else
1369 SemaRef.Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
1370 << InitEntity->getType()->isReferenceType() << DiagRange;
1371 }
1372 break;
1373 }
1374
1375 for (unsigned I = 0; I != Path.size(); ++I) {
1376 auto Elem = Path[I];
1377
1378 switch (Elem.Kind) {
1379 case IndirectLocalPathEntry::AddressOf:
1380 case IndirectLocalPathEntry::LValToRVal:
1381 case IndirectLocalPathEntry::ParenAggInit:
1382 // These exist primarily to mark the path as not permitting or
1383 // supporting lifetime extension.
1384 break;
1385
1386 case IndirectLocalPathEntry::LifetimeBoundCall:
1387 case IndirectLocalPathEntry::TemporaryCopy:
1388 case IndirectLocalPathEntry::MemberExpr:
1389 case IndirectLocalPathEntry::GslPointerInit:
1390 case IndirectLocalPathEntry::GslReferenceInit:
1391 case IndirectLocalPathEntry::GslPointerAssignment:
1392 // FIXME: Consider adding a note for these.
1393 break;
1394
1395 case IndirectLocalPathEntry::DefaultInit: {
1396 auto *FD = cast<FieldDecl>(Elem.D);
1397 SemaRef.Diag(FD->getLocation(),
1398 diag::note_init_with_default_member_initializer)
1399 << FD << nextPathEntryRange(Path, I + 1, L);
1400 break;
1401 }
1402
1403 case IndirectLocalPathEntry::VarInit: {
1404 const VarDecl *VD = cast<VarDecl>(Elem.D);
1405 SemaRef.Diag(VD->getLocation(), diag::note_local_var_initializer)
1406 << VD->getType()->isReferenceType() << VD->isImplicit()
1407 << VD->getDeclName() << nextPathEntryRange(Path, I + 1, L);
1408 break;
1409 }
1410
1411 case IndirectLocalPathEntry::LambdaCaptureInit: {
1412 if (!Elem.Capture->capturesVariable())
1413 break;
1414 // FIXME: We can't easily tell apart an init-capture from a nested
1415 // capture of an init-capture.
1416 const ValueDecl *VD = Elem.Capture->getCapturedVar();
1417 SemaRef.Diag(Elem.Capture->getLocation(),
1418 diag::note_lambda_capture_initializer)
1419 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
1420 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
1421 << nextPathEntryRange(Path, I + 1, L);
1422 break;
1423 }
1424
1425 case IndirectLocalPathEntry::DefaultArg: {
1426 const auto *DAE = cast<CXXDefaultArgExpr>(Elem.E);
1427 const ParmVarDecl *Param = DAE->getParam();
1428 SemaRef.Diag(Param->getDefaultArgRange().getBegin(),
1429 diag::note_init_with_default_argument)
1430 << Param << nextPathEntryRange(Path, I + 1, L);
1431 break;
1432 }
1433 }
1434 }
1435
1436 // We didn't lifetime-extend, so don't go any further; we don't need more
1437 // warnings or errors on inner temporaries within this one's initializer.
1438 return false;
1439 };
1440
1441 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
1442 switch (LK) {
1443 case LK_Assignment: {
1444 if (shouldRunGSLAssignmentAnalysis(SemaRef, *AEntity))
1445 Path.push_back({lifetimes::isAssignmentOperatorLifetimeBound(
1446 AEntity->AssignmentOperator)
1447 ? IndirectLocalPathEntry::LifetimeBoundCall
1448 : IndirectLocalPathEntry::GslPointerAssignment,
1449 Init});
1450 break;
1451 }
1452 case LK_LifetimeCapture: {
1453 if (lifetimes::isPointerLikeType(Init->getType()))
1454 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Init});
1455 break;
1456 }
1457 default:
1458 break;
1459 }
1460
1461 if (Init->isGLValue())
1462 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
1463 TemporaryVisitor);
1464 else
1465 visitLocalsRetainedByInitializer(
1466 Path, Init, TemporaryVisitor,
1467 // Don't revisit the sub inits for the intialization case.
1468 /*RevisitSubinits=*/!InitEntity);
1469 }
1470
1471 void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity,
1472 Expr *Init) {
1473 auto LTResult = getEntityLifetime(&Entity);
1474 LifetimeKind LK = LTResult.getInt();
1475 const InitializedEntity *ExtendingEntity = LTResult.getPointer();
1476 checkExprLifetimeImpl(SemaRef, &Entity, ExtendingEntity, LK,
1477 /*AEntity=*/nullptr, /*CapEntity=*/nullptr, Init);
1478 }
1479
1480 void checkExprLifetimeMustTailArg(Sema &SemaRef,
1481 const InitializedEntity &Entity, Expr *Init) {
1482 checkExprLifetimeImpl(SemaRef, &Entity, nullptr, LK_MustTail,
1483 /*AEntity=*/nullptr, /*CapEntity=*/nullptr, Init);
1484 }
1485
1486 void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity,
1487 Expr *Init) {
1488 bool EnableDanglingPointerAssignment = !SemaRef.getDiagnostics().isIgnored(
1489 diag::warn_dangling_pointer_assignment, SourceLocation());
1490 bool RunAnalysis = (EnableDanglingPointerAssignment &&
1491 Entity.LHS->getType()->isPointerType()) ||
1492 shouldRunGSLAssignmentAnalysis(SemaRef, Entity);
1493
1494 if (!RunAnalysis)
1495 return;
1496
1497 checkExprLifetimeImpl(SemaRef, /*InitEntity=*/nullptr,
1498 /*ExtendingEntity=*/nullptr, LK_Assignment, &Entity,
1499 /*CapEntity=*/nullptr, Init);
1500 }
1501
1502 void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity,
1503 Expr *Init) {
1504 if (SemaRef.getDiagnostics().isIgnored(diag::warn_dangling_reference_captured,
1505 SourceLocation()) &&
1506 SemaRef.getDiagnostics().isIgnored(
1507 diag::warn_dangling_reference_captured_by_unknown, SourceLocation()))
1508 return;
1509 return checkExprLifetimeImpl(SemaRef, /*InitEntity=*/nullptr,
1510 /*ExtendingEntity=*/nullptr, LK_LifetimeCapture,
1511 /*AEntity=*/nullptr,
1512 /*CapEntity=*/&Entity, Init);
1513 }
1514
1515 } // namespace clang::sema