1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for statements.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DynamicRecursiveASTVisitor.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/IgnoreExpr.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Ownership.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaHLSL.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/SemaOpenMP.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseMap.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/SmallVector.h"
44#include "llvm/ADT/StringExtras.h"
45
46using namespace clang;
47using namespace sema;
48
49StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
50 if (FE.isInvalid())
51 return StmtError();
52
53 FE = ActOnFinishFullExpr(Expr: FE.get(), CC: FE.get()->getExprLoc(), DiscardedValue);
54 if (FE.isInvalid())
55 return StmtError();
56
57 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
58 // void expression for its side effects. Conversion to void allows any
59 // operand, even incomplete types.
60
61 // Same thing in for stmt first clause (when expr) and third clause.
62 return StmtResult(FE.getAs<Stmt>());
63}
64
65
66StmtResult Sema::ActOnExprStmtError() {
67 DiscardCleanupsInEvaluationContext();
68 return StmtError();
69}
70
71StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
72 bool HasLeadingEmptyMacro) {
73 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
74}
75
76StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
77 SourceLocation EndLoc) {
78 DeclGroupRef DG = dg.get();
79
80 // If we have an invalid decl, just return an error.
81 if (DG.isNull()) return StmtError();
82
83 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
84}
85
86void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
87 DeclGroupRef DG = dg.get();
88
89 // If we don't have a declaration, or we have an invalid declaration,
90 // just return.
91 if (DG.isNull() || !DG.isSingleDecl())
92 return;
93
94 Decl *decl = DG.getSingleDecl();
95 if (!decl || decl->isInvalidDecl())
96 return;
97
98 // Only variable declarations are permitted.
99 VarDecl *var = dyn_cast<VarDecl>(Val: decl);
100 if (!var) {
101 Diag(Loc: decl->getLocation(), DiagID: diag::err_non_variable_decl_in_for);
102 decl->setInvalidDecl();
103 return;
104 }
105
106 // foreach variables are never actually initialized in the way that
107 // the parser came up with.
108 var->setInit(nullptr);
109
110 // In ARC, we don't need to retain the iteration variable of a fast
111 // enumeration loop. Rather than actually trying to catch that
112 // during declaration processing, we remove the consequences here.
113 if (getLangOpts().ObjCAutoRefCount) {
114 QualType type = var->getType();
115
116 // Only do this if we inferred the lifetime. Inferred lifetime
117 // will show up as a local qualifier because explicit lifetime
118 // should have shown up as an AttributedType instead.
119 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
120 // Add 'const' and mark the variable as pseudo-strong.
121 var->setType(type.withConst());
122 var->setARCPseudoStrong(true);
123 }
124 }
125}
126
127/// Diagnose unused comparisons, both builtin and overloaded operators.
128/// For '==' and '!=', suggest fixits for '=' or '|='.
129///
130/// Adding a cast to void (or other expression wrappers) will prevent the
131/// warning from firing.
132static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
133 SourceLocation Loc;
134 bool CanAssign;
135 enum { Equality, Inequality, Relational, ThreeWay } Kind;
136
137 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
138 if (!Op->isComparisonOp())
139 return false;
140
141 if (Op->getOpcode() == BO_EQ)
142 Kind = Equality;
143 else if (Op->getOpcode() == BO_NE)
144 Kind = Inequality;
145 else if (Op->getOpcode() == BO_Cmp)
146 Kind = ThreeWay;
147 else {
148 assert(Op->isRelationalOp());
149 Kind = Relational;
150 }
151 Loc = Op->getOperatorLoc();
152 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
153 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
154 switch (Op->getOperator()) {
155 case OO_EqualEqual:
156 Kind = Equality;
157 break;
158 case OO_ExclaimEqual:
159 Kind = Inequality;
160 break;
161 case OO_Less:
162 case OO_Greater:
163 case OO_GreaterEqual:
164 case OO_LessEqual:
165 Kind = Relational;
166 break;
167 case OO_Spaceship:
168 Kind = ThreeWay;
169 break;
170 default:
171 return false;
172 }
173
174 Loc = Op->getOperatorLoc();
175 CanAssign = Op->getArg(Arg: 0)->IgnoreParenImpCasts()->isLValue();
176 } else {
177 // Not a typo-prone comparison.
178 return false;
179 }
180
181 // Suppress warnings when the operator, suspicious as it may be, comes from
182 // a macro expansion.
183 if (S.SourceMgr.isMacroBodyExpansion(Loc))
184 return false;
185
186 S.Diag(Loc, DiagID: diag::warn_unused_comparison)
187 << (unsigned)Kind << E->getSourceRange();
188
189 // If the LHS is a plausible entity to assign to, provide a fixit hint to
190 // correct common typos.
191 if (CanAssign) {
192 if (Kind == Inequality)
193 S.Diag(Loc, DiagID: diag::note_inequality_comparison_to_or_assign)
194 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "|=");
195 else if (Kind == Equality)
196 S.Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
197 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
198 }
199
200 return true;
201}
202
203static bool DiagnoseNoDiscard(Sema &S, const NamedDecl *OffendingDecl,
204 const WarnUnusedResultAttr *A, SourceLocation Loc,
205 SourceRange R1, SourceRange R2, bool IsCtor) {
206 if (!A)
207 return false;
208 StringRef Msg = A->getMessage();
209
210 if (Msg.empty()) {
211 if (OffendingDecl)
212 return S.Diag(Loc, DiagID: diag::warn_unused_return_type)
213 << IsCtor << A << OffendingDecl << false << R1 << R2;
214 if (IsCtor)
215 return S.Diag(Loc, DiagID: diag::warn_unused_constructor)
216 << A << false << R1 << R2;
217 return S.Diag(Loc, DiagID: diag::warn_unused_result) << A << false << R1 << R2;
218 }
219
220 if (OffendingDecl)
221 return S.Diag(Loc, DiagID: diag::warn_unused_return_type)
222 << IsCtor << A << OffendingDecl << true << Msg << R1 << R2;
223 if (IsCtor)
224 return S.Diag(Loc, DiagID: diag::warn_unused_constructor)
225 << A << true << Msg << R1 << R2;
226 return S.Diag(Loc, DiagID: diag::warn_unused_result) << A << true << Msg << R1 << R2;
227}
228
229namespace {
230
231// Diagnoses unused expressions that call functions marked [[nodiscard]],
232// [[gnu::warn_unused_result]] and similar.
233// Additionally, a DiagID can be provided to emit a warning in additional
234// contexts (such as for an unused LHS of a comma expression)
235void DiagnoseUnused(Sema &S, const Expr *E, std::optional<unsigned> DiagID) {
236 bool NoDiscardOnly = !DiagID.has_value();
237
238 // If we are in an unevaluated expression context, then there can be no unused
239 // results because the results aren't expected to be used in the first place.
240 if (S.isUnevaluatedContext())
241 return;
242
243 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
244 // In most cases, we don't want to warn if the expression is written in a
245 // macro body, or if the macro comes from a system header. If the offending
246 // expression is a call to a function with the warn_unused_result attribute,
247 // we warn no matter the location. Because of the order in which the various
248 // checks need to happen, we factor out the macro-related test here.
249 bool ShouldSuppress = S.SourceMgr.isMacroBodyExpansion(Loc: ExprLoc) ||
250 S.SourceMgr.isInSystemMacro(loc: ExprLoc);
251
252 const Expr *WarnExpr;
253 SourceLocation Loc;
254 SourceRange R1, R2;
255 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Ctx&: S.Context))
256 return;
257
258 if (!NoDiscardOnly) {
259 // If this is a GNU statement expression expanded from a macro, it is
260 // probably unused because it is a function-like macro that can be used as
261 // either an expression or statement. Don't warn, because it is almost
262 // certainly a false positive.
263 if (isa<StmtExpr>(Val: E) && Loc.isMacroID())
264 return;
265
266 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
267 // That macro is frequently used to suppress "unused parameter" warnings,
268 // but its implementation makes clang's -Wunused-value fire. Prevent this.
269 if (isa<ParenExpr>(Val: E->IgnoreImpCasts()) && Loc.isMacroID()) {
270 SourceLocation SpellLoc = Loc;
271 if (S.findMacroSpelling(loc&: SpellLoc, name: "UNREFERENCED_PARAMETER"))
272 return;
273 }
274 }
275
276 // Okay, we have an unused result. Depending on what the base expression is,
277 // we might want to make a more specific diagnostic. Check for one of these
278 // cases now.
279 if (const FullExpr *Temps = dyn_cast<FullExpr>(Val: E))
280 E = Temps->getSubExpr();
281 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(Val: E))
282 E = TempExpr->getSubExpr();
283
284 if (DiagnoseUnusedComparison(S, E))
285 return;
286
287 E = WarnExpr;
288 if (const auto *Cast = dyn_cast<CastExpr>(Val: E))
289 if (Cast->getCastKind() == CK_NoOp ||
290 Cast->getCastKind() == CK_ConstructorConversion ||
291 Cast->getCastKind() == CK_IntegralCast)
292 E = Cast->getSubExpr()->IgnoreImpCasts();
293
294 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
295 if (E->getType()->isVoidType())
296 return;
297
298 auto [OffendingDecl, A] = CE->getUnusedResultAttr(Ctx: S.Context);
299 if (DiagnoseNoDiscard(S, OffendingDecl, A, Loc, R1, R2,
300 /*isCtor=*/IsCtor: false))
301 return;
302
303 // If the callee has attribute pure, const, or warn_unused_result, warn with
304 // a more specific message to make it clear what is happening. If the call
305 // is written in a macro body, only warn if it has the warn_unused_result
306 // attribute.
307 if (const Decl *FD = CE->getCalleeDecl()) {
308 if (ShouldSuppress)
309 return;
310 if (FD->hasAttr<PureAttr>()) {
311 S.Diag(Loc, DiagID: diag::warn_unused_call) << R1 << R2 << "pure";
312 return;
313 }
314 if (FD->hasAttr<ConstAttr>()) {
315 S.Diag(Loc, DiagID: diag::warn_unused_call) << R1 << R2 << "const";
316 return;
317 }
318 }
319 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(Val: E)) {
320 auto [OffendingDecl, A] = CE->getUnusedResultAttr(Ctx: S.Context);
321 if (DiagnoseNoDiscard(S, OffendingDecl, A, Loc, R1, R2,
322 /*isCtor=*/IsCtor: true))
323 return;
324 } else if (const auto *ILE = dyn_cast<InitListExpr>(Val: E)) {
325 if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
326
327 if (DiagnoseNoDiscard(S, OffendingDecl: TD, A: TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
328 R2, /*isCtor=*/IsCtor: false))
329 return;
330 }
331 } else if (ShouldSuppress)
332 return;
333
334 E = WarnExpr;
335 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: E)) {
336 if (S.getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
337 S.Diag(Loc, DiagID: diag::err_arc_unused_init_message) << R1;
338 return;
339 }
340
341 auto [OffendingDecl, A] = ME->getUnusedResultAttr(Ctx&: S.Context);
342 if (DiagnoseNoDiscard(S, OffendingDecl, A, Loc, R1, R2,
343 /*isCtor=*/IsCtor: false))
344 return;
345 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
346 const Expr *Source = POE->getSyntacticForm();
347 // Handle the actually selected call of an OpenMP specialized call.
348 if (S.LangOpts.OpenMP && isa<CallExpr>(Val: Source) &&
349 POE->getNumSemanticExprs() == 1 &&
350 isa<CallExpr>(Val: POE->getSemanticExpr(index: 0)))
351 return DiagnoseUnused(S, E: POE->getSemanticExpr(index: 0), DiagID);
352 if (isa<ObjCSubscriptRefExpr>(Val: Source))
353 DiagID = diag::warn_unused_container_subscript_expr;
354 else if (isa<ObjCPropertyRefExpr>(Val: Source))
355 DiagID = diag::warn_unused_property_expr;
356 } else if (const CXXFunctionalCastExpr *FC
357 = dyn_cast<CXXFunctionalCastExpr>(Val: E)) {
358 const Expr *E = FC->getSubExpr();
359 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(Val: E))
360 E = TE->getSubExpr();
361 if (isa<CXXTemporaryObjectExpr>(Val: E))
362 return;
363 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Val: E))
364 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
365 if (!RD->getAttr<WarnUnusedAttr>())
366 return;
367 }
368
369 if (NoDiscardOnly)
370 return;
371
372 // Diagnose "(void*) blah" as a typo for "(void) blah".
373 if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(Val: E)) {
374 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
375 QualType T = TI->getType();
376
377 // We really do want to use the non-canonical type here.
378 if (T == S.Context.VoidPtrTy) {
379 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
380
381 S.Diag(Loc, DiagID: diag::warn_unused_voidptr)
382 << FixItHint::CreateRemoval(RemoveRange: TL.getStarLoc());
383 return;
384 }
385 }
386
387 // Tell the user to assign it into a variable to force a volatile load if this
388 // isn't an array.
389 if (E->isGLValue() && E->getType().isVolatileQualified() &&
390 !E->getType()->isArrayType()) {
391 S.Diag(Loc, DiagID: diag::warn_unused_volatile) << R1 << R2;
392 return;
393 }
394
395 // Do not diagnose use of a comma operator in a SFINAE context because the
396 // type of the left operand could be used for SFINAE, so technically it is
397 // *used*.
398 if (DiagID == diag::warn_unused_comma_left_operand && S.isSFINAEContext())
399 return;
400
401 S.DiagIfReachable(Loc, Stmts: llvm::ArrayRef<const Stmt *>(E),
402 PD: S.PDiag(DiagID: *DiagID) << R1 << R2);
403}
404} // namespace
405
406void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
407 if (const LabelStmt *Label = dyn_cast_if_present<LabelStmt>(Val: S))
408 S = Label->getSubStmt();
409
410 const Expr *E = dyn_cast_if_present<Expr>(Val: S);
411 if (!E)
412 return;
413
414 DiagnoseUnused(S&: *this, E, DiagID);
415}
416
417void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
418 PushCompoundScope(IsStmtExpr);
419}
420
421void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
422 if (getCurFPFeatures().isFPConstrained()) {
423 FunctionScopeInfo *FSI = getCurFunction();
424 assert(FSI);
425 FSI->setUsesFPIntrin();
426 }
427}
428
429void Sema::ActOnFinishOfCompoundStmt() {
430 PopCompoundScope();
431}
432
433static StringRef GetDeferKeywordSpelling(Sema &S, SourceLocation DeferLoc) {
434 StringRef DeferSpelling =
435 S.PP.getLastMacroWithSpelling(Loc: DeferLoc, Tokens: {tok::kw__Defer});
436 if (DeferSpelling.empty())
437 DeferSpelling = "_Defer";
438 return DeferSpelling;
439}
440
441// Diagnose if the given statement is a redundant _Defer statement.
442static bool CheckRedundantDeferStmt(Sema &S, Stmt *Body) {
443 Stmt *Inner = Body->stripLabelLikeStatements();
444 if (isa<DeferStmt>(Val: Inner)) {
445 SourceLocation DeferLoc = Inner->getBeginLoc();
446 S.Diag(Loc: DeferLoc, DiagID: diag::warn_redundant_defer)
447 << Inner->getSourceRange() << GetDeferKeywordSpelling(S, DeferLoc);
448 return true;
449 }
450 return false;
451}
452
453sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
454 return getCurFunction()->CompoundScopes.back();
455}
456
457StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
458 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
459 const unsigned NumElts = Elts.size();
460
461 // If we're in C mode, check that we don't have any decls after stmts. If
462 // so, emit an extension diagnostic in C89 and potentially a warning in later
463 // versions.
464 const unsigned MixedDeclsCodeID = getLangOpts().C99
465 ? diag::warn_mixed_decls_code
466 : diag::ext_mixed_decls_code;
467 if (!getLangOpts().CPlusPlus && !Diags.isIgnored(DiagID: MixedDeclsCodeID, Loc: L)) {
468 // Note that __extension__ can be around a decl.
469 unsigned i = 0;
470 // Skip over all declarations.
471 for (; i != NumElts && isa<DeclStmt>(Val: Elts[i]); ++i)
472 /*empty*/;
473
474 // We found the end of the list or a statement. Scan for another declstmt.
475 for (; i != NumElts && !isa<DeclStmt>(Val: Elts[i]); ++i)
476 /*empty*/;
477
478 if (i != NumElts) {
479 Decl *D = *cast<DeclStmt>(Val: Elts[i])->decl_begin();
480 Diag(Loc: D->getLocation(), DiagID: MixedDeclsCodeID);
481 }
482 }
483
484 // Check for suspicious empty body (null statement) in `for' and `while'
485 // statements, for example:
486 //
487 // for (;;); <- warning: for loop has empty body
488 // foo();
489 //
490 // Don't do anything for template instantiations, this just adds
491 // noise.
492 if (NumElts != 0 && !CurrentInstantiationScope &&
493 getCurCompoundScope().HasEmptyLoopBodies) {
494 for (unsigned i = 0; i != NumElts - 1; ++i)
495 DiagnoseEmptyLoopBody(S: Elts[i], PossibleBody: Elts[i + 1]);
496 }
497
498 // Find defer statements that immediately precede a `break`/`continue`
499 // or a plain `return` statement.
500 if (NumElts > 1) {
501 for (unsigned i = 0; i != NumElts - 1; ++i) {
502 Stmt *Inner = Elts[i + 1]->stripLabelLikeStatements();
503 if (isa<BreakStmt, ContinueStmt>(Val: Inner) ||
504 (isa<ReturnStmt>(Val: Inner) && !cast<ReturnStmt>(Val: Inner)->getRetValue()))
505 CheckRedundantDeferStmt(S&: *this, Body: Elts[i]);
506 }
507 }
508
509 // Check for defer as last statement.
510 if (NumElts > 0)
511 CheckRedundantDeferStmt(S&: *this, Body: Elts[NumElts - 1]);
512
513 // Calculate difference between FP options in this compound statement and in
514 // the enclosing one. If this is a function body, take the difference against
515 // default options. In this case the difference will indicate options that are
516 // changed upon entry to the statement.
517 FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1)
518 ? FPOptions(getLangOpts())
519 : getCurCompoundScope().InitialFPFeatures;
520 FPOptionsOverride FPDiff = getCurFPFeatures().getChangesFrom(Base: FPO);
521
522 return CompoundStmt::Create(C: Context, Stmts: Elts, FPFeatures: FPDiff, LB: L, RB: R);
523}
524
525ExprResult
526Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
527 if (!Val.get())
528 return Val;
529
530 if (DiagnoseUnexpandedParameterPack(E: Val.get()))
531 return ExprError();
532
533 // If we're not inside a switch, let the 'case' statement handling diagnose
534 // this. Just clean up after the expression as best we can.
535 if (getCurFunction()->SwitchStack.empty())
536 return ActOnFinishFullExpr(Expr: Val.get(), CC: Val.get()->getExprLoc(), DiscardedValue: false,
537 IsConstexpr: getLangOpts().CPlusPlus11);
538
539 Expr *CondExpr =
540 getCurFunction()->SwitchStack.back().getPointer()->getCond();
541 if (!CondExpr)
542 return ExprError();
543 QualType CondType = CondExpr->getType();
544
545 auto CheckAndFinish = [&](Expr *E) {
546 if (CondType->isDependentType() || E->isTypeDependent())
547 return ExprResult(E);
548
549 if (getLangOpts().CPlusPlus11) {
550 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
551 // constant expression of the promoted type of the switch condition.
552 llvm::APSInt TempVal;
553 return CheckConvertedConstantExpression(From: E, T: CondType, Value&: TempVal,
554 CCE: CCEKind::CaseValue);
555 }
556
557 ExprResult ER = E;
558 if (!E->isValueDependent())
559 ER = VerifyIntegerConstantExpression(E, CanFold: AllowFoldKind::Allow);
560 if (!ER.isInvalid())
561 ER = DefaultLvalueConversion(E: ER.get());
562 if (!ER.isInvalid())
563 ER = ImpCastExprToType(E: ER.get(), Type: CondType, CK: CK_IntegralCast);
564 if (!ER.isInvalid())
565 ER = ActOnFinishFullExpr(Expr: ER.get(), CC: ER.get()->getExprLoc(), DiscardedValue: false);
566 return ER;
567 };
568
569 return CheckAndFinish(Val.get());
570}
571
572static bool DiagnoseSwitchCaseInExpansionStmt(Sema &S, SourceLocation KwLoc,
573 bool IsDefault) {
574 // C++26 [stmt.expand] The compound-statement of an expansion-statement is a
575 // control-flow-limited statement.
576 //
577 // We diagnose this here rather than in JumpDiagnostics because those run
578 // after the expansion statement is instantiated, at which point we will have
579 // have already complained about duplicate case labels, which is not exactly
580 // great QOI.
581 if (S.CurContext->isExpansionStmt() &&
582 S.getCurFunction()->SwitchStack.back().EnclosingDC != S.CurContext) {
583 S.Diag(Loc: KwLoc, DiagID: diag::err_expansion_stmt_case) << IsDefault;
584 S.Diag(Loc: S.getCurFunction()->SwitchStack.back().getPointer()->getSwitchLoc(),
585 DiagID: diag::note_enclosing_switch_statement_here);
586 return true;
587 }
588 return false;
589}
590
591StmtResult
592Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
593 SourceLocation DotDotDotLoc, ExprResult RHSVal,
594 SourceLocation ColonLoc) {
595 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
596 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
597 : RHSVal.isInvalid() || RHSVal.get()) &&
598 "missing RHS value");
599
600 if (getCurFunction()->SwitchStack.empty()) {
601 Diag(Loc: CaseLoc, DiagID: diag::err_case_not_in_switch);
602 return StmtError();
603 }
604
605 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
606 getCurFunction()->SwitchStack.back().setInt(true);
607 return StmtError();
608 }
609
610 if (DiagnoseSwitchCaseInExpansionStmt(S&: *this, KwLoc: CaseLoc, IsDefault: false))
611 return StmtError();
612
613 if (LangOpts.OpenACC &&
614 getCurScope()->isInOpenACCComputeConstructScope(Flags: Scope::SwitchScope)) {
615 Diag(Loc: CaseLoc, DiagID: diag::err_acc_branch_in_out_compute_construct)
616 << /*branch*/ 0 << /*into*/ 1;
617 return StmtError();
618 }
619
620 auto *CS = CaseStmt::Create(Ctx: Context, lhs: LHSVal.get(), rhs: RHSVal.get(),
621 caseLoc: CaseLoc, ellipsisLoc: DotDotDotLoc, colonLoc: ColonLoc);
622 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(SC: CS);
623 return CS;
624}
625
626void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
627 cast<CaseStmt>(Val: S)->setSubStmt(SubStmt);
628}
629
630StmtResult
631Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
632 Stmt *SubStmt, Scope *CurScope) {
633 if (getCurFunction()->SwitchStack.empty()) {
634 Diag(Loc: DefaultLoc, DiagID: diag::err_default_not_in_switch);
635 return SubStmt;
636 }
637
638 if (DiagnoseSwitchCaseInExpansionStmt(S&: *this, KwLoc: DefaultLoc, IsDefault: true))
639 return StmtError();
640
641 if (LangOpts.OpenACC &&
642 getCurScope()->isInOpenACCComputeConstructScope(Flags: Scope::SwitchScope)) {
643 Diag(Loc: DefaultLoc, DiagID: diag::err_acc_branch_in_out_compute_construct)
644 << /*branch*/ 0 << /*into*/ 1;
645 return StmtError();
646 }
647
648 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
649 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(SC: DS);
650 return DS;
651}
652
653StmtResult
654Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
655 SourceLocation ColonLoc, Stmt *SubStmt) {
656 // If the label was multiply defined, reject it now.
657 if (TheDecl->getStmt()) {
658 Diag(Loc: IdentLoc, DiagID: diag::err_redefinition_of_label) << TheDecl->getDeclName();
659 Diag(Loc: TheDecl->getLocation(), DiagID: diag::note_previous_definition);
660 return SubStmt;
661 }
662
663 ReservedIdentifierStatus Status = TheDecl->isReserved(LangOpts: getLangOpts());
664 if (isReservedInAllContexts(Status) &&
665 !Context.getSourceManager().isInSystemHeader(Loc: IdentLoc))
666 Diag(Loc: IdentLoc, DiagID: diag::warn_reserved_extern_symbol)
667 << TheDecl << static_cast<int>(Status);
668
669 // If this label is in a compute construct scope, we need to make sure we
670 // check gotos in/out.
671 if (getCurScope()->isInOpenACCComputeConstructScope())
672 setFunctionHasBranchProtectedScope();
673
674 // OpenACC3.3 2.14.4:
675 // The update directive is executable. It must not appear in place of the
676 // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
677 // C++.
678 if (isa<OpenACCUpdateConstruct>(Val: SubStmt)) {
679 Diag(Loc: SubStmt->getBeginLoc(), DiagID: diag::err_acc_update_as_body) << /*Label*/ 4;
680 SubStmt = new (Context) NullStmt(SubStmt->getBeginLoc());
681 }
682
683 // Otherwise, things are good. Fill in the declaration and return it.
684 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
685 TheDecl->setStmt(LS);
686 if (!TheDecl->isGnuLocal()) {
687 TheDecl->setLocStart(IdentLoc);
688 if (!TheDecl->isMSAsmLabel()) {
689 // Don't update the location of MS ASM labels. These will result in
690 // a diagnostic, and changing the location here will mess that up.
691 TheDecl->setLocation(IdentLoc);
692 }
693 }
694 return LS;
695}
696
697StmtResult Sema::BuildAttributedStmt(SourceLocation AttrsLoc,
698 ArrayRef<const Attr *> Attrs,
699 Stmt *SubStmt) {
700 // FIXME: this code should move when a planned refactoring around statement
701 // attributes lands.
702 for (const auto *A : Attrs) {
703 if (A->getKind() == attr::MustTail) {
704 if (!checkAndRewriteMustTailAttr(St: SubStmt, MTA: *A)) {
705 return SubStmt;
706 }
707 setFunctionHasMustTail();
708 }
709 }
710
711 return AttributedStmt::Create(C: Context, Loc: AttrsLoc, Attrs, SubStmt);
712}
713
714StmtResult Sema::ActOnAttributedStmt(const ParsedAttributes &Attrs,
715 Stmt *SubStmt) {
716 SmallVector<const Attr *, 1> SemanticAttrs;
717 ProcessStmtAttributes(Stmt: SubStmt, InAttrs: Attrs, OutAttrs&: SemanticAttrs);
718 if (!SemanticAttrs.empty())
719 return BuildAttributedStmt(AttrsLoc: Attrs.Range.getBegin(), Attrs: SemanticAttrs, SubStmt);
720 // If none of the attributes applied, that's fine, we can recover by
721 // returning the substatement directly instead of making an AttributedStmt
722 // with no attributes on it.
723 return SubStmt;
724}
725
726bool Sema::checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA) {
727 ReturnStmt *R = cast<ReturnStmt>(Val: St);
728 Expr *E = R->getRetValue();
729
730 if (CurContext->isDependentContext() || (E && E->isInstantiationDependent()))
731 // We have to suspend our check until template instantiation time.
732 return true;
733
734 if (!checkMustTailAttr(St, MTA))
735 return false;
736
737 // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function.
738 // Currently it does not skip implicit constructors in an initialization
739 // context.
740 auto IgnoreImplicitAsWritten = [](Expr *E) -> Expr * {
741 return IgnoreExprNodes(E, Fns&: IgnoreImplicitAsWrittenSingleStep,
742 Fns&: IgnoreElidableImplicitConstructorSingleStep);
743 };
744
745 // Now that we have verified that 'musttail' is valid here, rewrite the
746 // return value to remove all implicit nodes, but retain parentheses.
747 R->setRetValue(IgnoreImplicitAsWritten(E));
748 return true;
749}
750
751bool Sema::checkMustTailAttr(const Stmt *St, const Attr &MTA) {
752 assert(!CurContext->isDependentContext() &&
753 "musttail cannot be checked from a dependent context");
754
755 // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition.
756 auto IgnoreParenImplicitAsWritten = [](const Expr *E) -> const Expr * {
757 return IgnoreExprNodes(E: const_cast<Expr *>(E), Fns&: IgnoreParensSingleStep,
758 Fns&: IgnoreImplicitAsWrittenSingleStep,
759 Fns&: IgnoreElidableImplicitConstructorSingleStep);
760 };
761
762 const Expr *E = cast<ReturnStmt>(Val: St)->getRetValue();
763 const auto *CE = dyn_cast_or_null<CallExpr>(Val: IgnoreParenImplicitAsWritten(E));
764
765 if (!CE) {
766 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_needs_call) << &MTA;
767 return false;
768 }
769
770 if (const FunctionDecl *CalleeDecl = CE->getDirectCallee();
771 CalleeDecl && CalleeDecl->hasAttr<NotTailCalledAttr>()) {
772 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_mismatch) << /*show-function-callee=*/true << CalleeDecl;
773 Diag(Loc: CalleeDecl->getLocation(), DiagID: diag::note_musttail_disabled_by_not_tail_called);
774 return false;
775 }
776
777 if (const auto *EWC = dyn_cast<ExprWithCleanups>(Val: E)) {
778 if (EWC->cleanupsHaveSideEffects()) {
779 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_needs_trivial_args) << &MTA;
780 return false;
781 }
782 }
783
784 // We need to determine the full function type (including "this" type, if any)
785 // for both caller and callee.
786 struct FuncType {
787 enum {
788 ft_non_member,
789 ft_static_member,
790 ft_non_static_member,
791 ft_pointer_to_member,
792 } MemberType = ft_non_member;
793
794 QualType This;
795 const FunctionProtoType *Func;
796 const CXXMethodDecl *Method = nullptr;
797 } CallerType, CalleeType;
798
799 auto GetMethodType = [this, St, MTA](const CXXMethodDecl *CMD, FuncType &Type,
800 bool IsCallee) -> bool {
801 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CMD)) {
802 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_structors_forbidden)
803 << IsCallee << isa<CXXDestructorDecl>(Val: CMD);
804 if (IsCallee)
805 Diag(Loc: CMD->getBeginLoc(), DiagID: diag::note_musttail_structors_forbidden)
806 << isa<CXXDestructorDecl>(Val: CMD);
807 Diag(Loc: MTA.getLocation(), DiagID: diag::note_tail_call_required) << &MTA;
808 return false;
809 }
810 if (CMD->isStatic())
811 Type.MemberType = FuncType::ft_static_member;
812 else {
813 Type.This = CMD->getFunctionObjectParameterType();
814 Type.MemberType = FuncType::ft_non_static_member;
815 }
816 Type.Func = CMD->getType()->castAs<FunctionProtoType>();
817 return true;
818 };
819
820 const auto *CallerDecl = dyn_cast<FunctionDecl>(Val: CurContext);
821
822 // Find caller function signature.
823 if (!CallerDecl) {
824 int ContextType;
825 if (isa<BlockDecl>(Val: CurContext))
826 ContextType = 0;
827 else if (isa<ObjCMethodDecl>(Val: CurContext))
828 ContextType = 1;
829 else
830 ContextType = 2;
831 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_forbidden_from_this_context)
832 << &MTA << ContextType;
833 return false;
834 } else if (const auto *CMD = dyn_cast<CXXMethodDecl>(Val: CurContext)) {
835 // Caller is a class/struct method.
836 if (!GetMethodType(CMD, CallerType, false))
837 return false;
838 } else {
839 // Caller is a non-method function.
840 CallerType.Func = CallerDecl->getType()->getAs<FunctionProtoType>();
841 }
842
843 const Expr *CalleeExpr = CE->getCallee()->IgnoreParens();
844 const auto *CalleeBinOp = dyn_cast<BinaryOperator>(Val: CalleeExpr);
845 SourceLocation CalleeLoc = CE->getCalleeDecl()
846 ? CE->getCalleeDecl()->getBeginLoc()
847 : St->getBeginLoc();
848
849 // Find callee function signature.
850 if (const CXXMethodDecl *CMD =
851 dyn_cast_or_null<CXXMethodDecl>(Val: CE->getCalleeDecl())) {
852 // Call is: obj.method(), obj->method(), functor(), etc.
853 if (!GetMethodType(CMD, CalleeType, true))
854 return false;
855 } else if (CalleeBinOp && CalleeBinOp->isPtrMemOp()) {
856 // Call is: obj->*method_ptr or obj.*method_ptr
857 const auto *MPT =
858 CalleeBinOp->getRHS()->getType()->castAs<MemberPointerType>();
859 CalleeType.This =
860 Context.getCanonicalTagType(TD: MPT->getMostRecentCXXRecordDecl());
861 CalleeType.Func = MPT->getPointeeType()->castAs<FunctionProtoType>();
862 CalleeType.MemberType = FuncType::ft_pointer_to_member;
863 } else if (isa<CXXPseudoDestructorExpr>(Val: CalleeExpr)) {
864 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_structors_forbidden)
865 << /* IsCallee = */ 1 << /* IsDestructor = */ 1;
866 Diag(Loc: MTA.getLocation(), DiagID: diag::note_tail_call_required) << &MTA;
867 return false;
868 } else {
869 // Non-method function.
870 CalleeType.Func =
871 CalleeExpr->getType()->getPointeeType()->getAs<FunctionProtoType>();
872 }
873
874 // Both caller and callee must have a prototype (no K&R declarations).
875 if (!CalleeType.Func || !CallerType.Func) {
876 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_needs_prototype) << &MTA;
877 if (!CalleeType.Func && CE->getDirectCallee()) {
878 Diag(Loc: CE->getDirectCallee()->getBeginLoc(),
879 DiagID: diag::note_musttail_fix_non_prototype);
880 }
881 if (!CallerType.Func)
882 Diag(Loc: CallerDecl->getBeginLoc(), DiagID: diag::note_musttail_fix_non_prototype);
883 return false;
884 }
885
886 // Caller and callee must have matching calling conventions.
887 //
888 // Some calling conventions are physically capable of supporting tail calls
889 // even if the function types don't perfectly match. LLVM is currently too
890 // strict to allow this, but if LLVM added support for this in the future, we
891 // could exit early here and skip the remaining checks if the functions are
892 // using such a calling convention.
893 if (CallerType.Func->getCallConv() != CalleeType.Func->getCallConv()) {
894 if (const auto *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl()))
895 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_callconv_mismatch)
896 << true << ND->getDeclName();
897 else
898 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_callconv_mismatch) << false;
899 Diag(Loc: CalleeLoc, DiagID: diag::note_musttail_callconv_mismatch)
900 << FunctionType::getNameForCallConv(CC: CallerType.Func->getCallConv())
901 << FunctionType::getNameForCallConv(CC: CalleeType.Func->getCallConv());
902 Diag(Loc: MTA.getLocation(), DiagID: diag::note_tail_call_required) << &MTA;
903 return false;
904 }
905
906 if (CalleeType.Func->isVariadic() || CallerType.Func->isVariadic()) {
907 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_no_variadic) << &MTA;
908 return false;
909 }
910
911 const auto *CalleeDecl = CE->getCalleeDecl();
912 if (CalleeDecl && CalleeDecl->hasAttr<CXX11NoReturnAttr>()) {
913 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_no_return) << &MTA;
914 return false;
915 }
916
917 // Caller and callee must match in whether they have a "this" parameter.
918 if (CallerType.This.isNull() != CalleeType.This.isNull()) {
919 if (const auto *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
920 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_member_mismatch)
921 << CallerType.MemberType << CalleeType.MemberType << true
922 << ND->getDeclName();
923 Diag(Loc: CalleeLoc, DiagID: diag::note_musttail_callee_defined_here)
924 << ND->getDeclName();
925 } else
926 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_member_mismatch)
927 << CallerType.MemberType << CalleeType.MemberType << false;
928 Diag(Loc: MTA.getLocation(), DiagID: diag::note_tail_call_required) << &MTA;
929 return false;
930 }
931
932 auto CheckTypesMatch = [this](FuncType CallerType, FuncType CalleeType,
933 PartialDiagnostic &PD) -> bool {
934 enum {
935 ft_different_class,
936 ft_parameter_arity,
937 ft_parameter_mismatch,
938 ft_return_type,
939 };
940
941 auto DoTypesMatch = [this, &PD](QualType A, QualType B,
942 unsigned Select) -> bool {
943 if (!Context.hasSimilarType(T1: A, T2: B)) {
944 PD << Select << A.getUnqualifiedType() << B.getUnqualifiedType();
945 return false;
946 }
947 return true;
948 };
949
950 if (!CallerType.This.isNull() &&
951 !DoTypesMatch(CallerType.This, CalleeType.This, ft_different_class))
952 return false;
953
954 if (!DoTypesMatch(CallerType.Func->getReturnType(),
955 CalleeType.Func->getReturnType(), ft_return_type))
956 return false;
957
958 if (CallerType.Func->getNumParams() != CalleeType.Func->getNumParams()) {
959 PD << ft_parameter_arity << CallerType.Func->getNumParams()
960 << CalleeType.Func->getNumParams();
961 return false;
962 }
963
964 ArrayRef<QualType> CalleeParams = CalleeType.Func->getParamTypes();
965 ArrayRef<QualType> CallerParams = CallerType.Func->getParamTypes();
966 size_t N = CallerType.Func->getNumParams();
967 for (size_t I = 0; I < N; I++) {
968 if (!DoTypesMatch(CalleeParams[I], CallerParams[I],
969 ft_parameter_mismatch)) {
970 PD << static_cast<int>(I) + 1;
971 return false;
972 }
973 }
974
975 return true;
976 };
977
978 PartialDiagnostic PD = PDiag(DiagID: diag::note_musttail_mismatch);
979 if (!CheckTypesMatch(CallerType, CalleeType, PD)) {
980 if (const auto *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl()))
981 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_mismatch)
982 << true << ND->getDeclName();
983 else
984 Diag(Loc: St->getBeginLoc(), DiagID: diag::err_musttail_mismatch) << false;
985 Diag(Loc: CalleeLoc, PD);
986 Diag(Loc: MTA.getLocation(), DiagID: diag::note_tail_call_required) << &MTA;
987 return false;
988 }
989
990 // The lifetimes of locals and incoming function parameters must end before
991 // the call, because we can't have a stack frame to store them, so diagnose
992 // any pointers or references to them passed into the musttail call.
993 for (auto ArgExpr : CE->arguments()) {
994 InitializedEntity Entity = InitializedEntity::InitializeParameter(
995 Context, Type: ArgExpr->getType(), Consumed: false);
996 checkExprLifetimeMustTailArg(SemaRef&: *this, Entity, Init: const_cast<Expr *>(ArgExpr));
997 }
998
999 return true;
1000}
1001
1002namespace {
1003class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
1004 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
1005 Sema &SemaRef;
1006public:
1007 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
1008 void VisitBinaryOperator(BinaryOperator *E) {
1009 if (E->getOpcode() == BO_Comma)
1010 SemaRef.DiagnoseCommaOperator(LHS: E->getLHS(), Loc: E->getExprLoc());
1011 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(S: E);
1012 }
1013};
1014}
1015
1016StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc,
1017 IfStatementKind StatementKind,
1018 SourceLocation LParenLoc, Stmt *InitStmt,
1019 ConditionResult Cond, SourceLocation RParenLoc,
1020 Stmt *thenStmt, SourceLocation ElseLoc,
1021 Stmt *elseStmt) {
1022 if (Cond.isInvalid())
1023 return StmtError();
1024
1025 bool ConstevalOrNegatedConsteval =
1026 StatementKind == IfStatementKind::ConstevalNonNegated ||
1027 StatementKind == IfStatementKind::ConstevalNegated;
1028
1029 Expr *CondExpr = Cond.get().second;
1030 assert((CondExpr || ConstevalOrNegatedConsteval) &&
1031 "If statement: missing condition");
1032 // Only call the CommaVisitor when not C89 due to differences in scope flags.
1033 if (CondExpr && (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
1034 !Diags.isIgnored(DiagID: diag::warn_comma_operator, Loc: CondExpr->getExprLoc()))
1035 CommaVisitor(*this).Visit(S: CondExpr);
1036
1037 if (!ConstevalOrNegatedConsteval && !elseStmt)
1038 DiagnoseEmptyStmtBody(StmtLoc: RParenLoc, Body: thenStmt, DiagID: diag::warn_empty_if_body);
1039
1040 if (CheckRedundantDeferStmt(S&: *this, Body: thenStmt))
1041 Diag(Loc: thenStmt->getBeginLoc(), DiagID: diag::note_redundant_defer_if)
1042 << GetDeferKeywordSpelling(S&: *this, DeferLoc: thenStmt->getBeginLoc());
1043 if (elseStmt)
1044 CheckRedundantDeferStmt(S&: *this, Body: elseStmt);
1045
1046 if (ConstevalOrNegatedConsteval ||
1047 StatementKind == IfStatementKind::Constexpr) {
1048 auto DiagnoseLikelihood = [&](const Stmt *S) {
1049 if (const Attr *A = Stmt::getLikelihoodAttr(S)) {
1050 Diags.Report(Loc: A->getLocation(),
1051 DiagID: diag::warn_attribute_has_no_effect_on_compile_time_if)
1052 << A << ConstevalOrNegatedConsteval << A->getRange();
1053 Diags.Report(Loc: IfLoc,
1054 DiagID: diag::note_attribute_has_no_effect_on_compile_time_if_here)
1055 << ConstevalOrNegatedConsteval
1056 << SourceRange(IfLoc, (ConstevalOrNegatedConsteval
1057 ? thenStmt->getBeginLoc()
1058 : LParenLoc)
1059 .getLocWithOffset(Offset: -1));
1060 }
1061 };
1062 DiagnoseLikelihood(thenStmt);
1063 DiagnoseLikelihood(elseStmt);
1064 } else {
1065 std::tuple<bool, const Attr *, const Attr *> LHC =
1066 Stmt::determineLikelihoodConflict(Then: thenStmt, Else: elseStmt);
1067 if (std::get<0>(t&: LHC)) {
1068 const Attr *ThenAttr = std::get<1>(t&: LHC);
1069 const Attr *ElseAttr = std::get<2>(t&: LHC);
1070 Diags.Report(Loc: ThenAttr->getLocation(),
1071 DiagID: diag::warn_attributes_likelihood_ifstmt_conflict)
1072 << ThenAttr << ThenAttr->getRange();
1073 Diags.Report(Loc: ElseAttr->getLocation(), DiagID: diag::note_conflicting_attribute)
1074 << ElseAttr << ElseAttr->getRange();
1075 }
1076 }
1077
1078 if (ConstevalOrNegatedConsteval) {
1079 bool Immediate = ExprEvalContexts.back().Context ==
1080 ExpressionEvaluationContext::ImmediateFunctionContext;
1081 if (CurContext->isFunctionOrMethod()) {
1082 const auto *FD =
1083 dyn_cast<FunctionDecl>(Val: Decl::castFromDeclContext(CurContext));
1084 if (FD && FD->isImmediateFunction())
1085 Immediate = true;
1086 }
1087 if (isUnevaluatedContext() || Immediate)
1088 Diags.Report(Loc: IfLoc, DiagID: diag::warn_consteval_if_always_true) << Immediate;
1089 }
1090
1091 // OpenACC3.3 2.14.4:
1092 // The update directive is executable. It must not appear in place of the
1093 // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1094 // C++.
1095 if (isa<OpenACCUpdateConstruct>(Val: thenStmt)) {
1096 Diag(Loc: thenStmt->getBeginLoc(), DiagID: diag::err_acc_update_as_body) << /*if*/ 0;
1097 thenStmt = new (Context) NullStmt(thenStmt->getBeginLoc());
1098 }
1099
1100 return BuildIfStmt(IfLoc, StatementKind, LParenLoc, InitStmt, Cond, RParenLoc,
1101 ThenVal: thenStmt, ElseLoc, ElseVal: elseStmt);
1102}
1103
1104StmtResult Sema::BuildIfStmt(SourceLocation IfLoc,
1105 IfStatementKind StatementKind,
1106 SourceLocation LParenLoc, Stmt *InitStmt,
1107 ConditionResult Cond, SourceLocation RParenLoc,
1108 Stmt *thenStmt, SourceLocation ElseLoc,
1109 Stmt *elseStmt) {
1110 if (Cond.isInvalid())
1111 return StmtError();
1112
1113 if (StatementKind != IfStatementKind::Ordinary ||
1114 isa<ObjCAvailabilityCheckExpr>(Val: Cond.get().second))
1115 setFunctionHasBranchProtectedScope();
1116
1117 return IfStmt::Create(Ctx: Context, IL: IfLoc, Kind: StatementKind, Init: InitStmt,
1118 Var: Cond.get().first, Cond: Cond.get().second, LPL: LParenLoc,
1119 RPL: RParenLoc, Then: thenStmt, EL: ElseLoc, Else: elseStmt);
1120}
1121
1122namespace {
1123 struct CaseCompareFunctor {
1124 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
1125 const llvm::APSInt &RHS) {
1126 return LHS.first < RHS;
1127 }
1128 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
1129 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
1130 return LHS.first < RHS.first;
1131 }
1132 bool operator()(const llvm::APSInt &LHS,
1133 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
1134 return LHS < RHS.first;
1135 }
1136 };
1137}
1138
1139/// CmpCaseVals - Comparison predicate for sorting case values.
1140///
1141static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
1142 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
1143 if (lhs.first < rhs.first)
1144 return true;
1145
1146 if (lhs.first == rhs.first &&
1147 lhs.second->getCaseLoc() < rhs.second->getCaseLoc())
1148 return true;
1149 return false;
1150}
1151
1152/// CmpEnumVals - Comparison predicate for sorting enumeration values.
1153///
1154static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1155 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1156{
1157 return lhs.first < rhs.first;
1158}
1159
1160/// EqEnumVals - Comparison preficate for uniqing enumeration values.
1161///
1162static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1163 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1164{
1165 return lhs.first == rhs.first;
1166}
1167
1168/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
1169/// potentially integral-promoted expression @p expr.
1170static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
1171 if (const auto *FE = dyn_cast<FullExpr>(Val: E))
1172 E = FE->getSubExpr();
1173 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(Val: E)) {
1174 if (ImpCast->getCastKind() != CK_IntegralCast) break;
1175 E = ImpCast->getSubExpr();
1176 }
1177 return E->getType();
1178}
1179
1180ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
1181 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
1182 Expr *Cond;
1183
1184 public:
1185 SwitchConvertDiagnoser(Expr *Cond)
1186 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
1187 Cond(Cond) {}
1188
1189 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1190 QualType T) override {
1191 return S.Diag(Loc, DiagID: diag::err_typecheck_statement_requires_integer) << T;
1192 }
1193
1194 SemaDiagnosticBuilder diagnoseIncomplete(
1195 Sema &S, SourceLocation Loc, QualType T) override {
1196 return S.Diag(Loc, DiagID: diag::err_switch_incomplete_class_type)
1197 << T << Cond->getSourceRange();
1198 }
1199
1200 SemaDiagnosticBuilder diagnoseExplicitConv(
1201 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1202 return S.Diag(Loc, DiagID: diag::err_switch_explicit_conversion) << T << ConvTy;
1203 }
1204
1205 SemaDiagnosticBuilder noteExplicitConv(
1206 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1207 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_switch_conversion)
1208 << ConvTy->isEnumeralType() << ConvTy;
1209 }
1210
1211 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1212 QualType T) override {
1213 return S.Diag(Loc, DiagID: diag::err_switch_multiple_conversions) << T;
1214 }
1215
1216 SemaDiagnosticBuilder noteAmbiguous(
1217 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1218 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_switch_conversion)
1219 << ConvTy->isEnumeralType() << ConvTy;
1220 }
1221
1222 SemaDiagnosticBuilder diagnoseConversion(
1223 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1224 llvm_unreachable("conversion functions are permitted");
1225 }
1226 } SwitchDiagnoser(Cond);
1227
1228 ExprResult CondResult =
1229 PerformContextualImplicitConversion(Loc: SwitchLoc, FromE: Cond, Converter&: SwitchDiagnoser);
1230 if (CondResult.isInvalid())
1231 return ExprError();
1232
1233 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
1234 // failed and produced a diagnostic.
1235 Cond = CondResult.get();
1236 if (!Cond->isTypeDependent() &&
1237 !Cond->getType()->isIntegralOrEnumerationType())
1238 return ExprError();
1239
1240 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
1241 return UsualUnaryConversions(E: Cond);
1242}
1243
1244StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
1245 SourceLocation LParenLoc,
1246 Stmt *InitStmt, ConditionResult Cond,
1247 SourceLocation RParenLoc) {
1248 Expr *CondExpr = Cond.get().second;
1249 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
1250
1251 if (CondExpr && !CondExpr->isTypeDependent()) {
1252 // We have already converted the expression to an integral or enumeration
1253 // type, when we parsed the switch condition. There are cases where we don't
1254 // have an appropriate type, e.g. a typo-expr Cond was corrected to an
1255 // inappropriate-type expr, we just return an error.
1256 if (!CondExpr->getType()->isIntegralOrEnumerationType())
1257 return StmtError();
1258 if (CondExpr->isKnownToHaveBooleanValue()) {
1259 // switch(bool_expr) {...} is often a programmer error, e.g.
1260 // switch(n && mask) { ... } // Doh - should be "n & mask".
1261 // One can always use an if statement instead of switch(bool_expr).
1262 Diag(Loc: SwitchLoc, DiagID: diag::warn_bool_switch_condition)
1263 << CondExpr->getSourceRange();
1264 }
1265 }
1266
1267 setFunctionHasBranchIntoScope();
1268
1269 auto *SS = SwitchStmt::Create(Ctx: Context, Init: InitStmt, Var: Cond.get().first, Cond: CondExpr,
1270 LParenLoc, RParenLoc);
1271 SS->setSwitchLoc(SwitchLoc);
1272 getCurFunction()->SwitchStack.push_back(
1273 Elt: FunctionScopeInfo::SwitchInfo(SS, CurContext));
1274 return SS;
1275}
1276
1277static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
1278 Val = Val.extOrTrunc(width: BitWidth);
1279 Val.setIsSigned(IsSigned);
1280}
1281
1282/// Check the specified case value is in range for the given unpromoted switch
1283/// type.
1284static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
1285 unsigned UnpromotedWidth, bool UnpromotedSign) {
1286 // In C++11 onwards, this is checked by the language rules.
1287 if (S.getLangOpts().CPlusPlus11)
1288 return;
1289
1290 // If the case value was signed and negative and the switch expression is
1291 // unsigned, don't bother to warn: this is implementation-defined behavior.
1292 // FIXME: Introduce a second, default-ignored warning for this case?
1293 if (UnpromotedWidth < Val.getBitWidth()) {
1294 llvm::APSInt ConvVal(Val);
1295 AdjustAPSInt(Val&: ConvVal, BitWidth: UnpromotedWidth, IsSigned: UnpromotedSign);
1296 AdjustAPSInt(Val&: ConvVal, BitWidth: Val.getBitWidth(), IsSigned: Val.isSigned());
1297 // FIXME: Use different diagnostics for overflow in conversion to promoted
1298 // type versus "switch expression cannot have this value". Use proper
1299 // IntRange checking rather than just looking at the unpromoted type here.
1300 if (ConvVal != Val)
1301 S.Diag(Loc, DiagID: diag::warn_case_value_overflow) << toString(I: Val, Radix: 10)
1302 << toString(I: ConvVal, Radix: 10);
1303 }
1304}
1305
1306typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
1307
1308/// Returns true if we should emit a diagnostic about this case expression not
1309/// being a part of the enum used in the switch controlling expression.
1310static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
1311 const EnumDecl *ED,
1312 const Expr *CaseExpr,
1313 EnumValsTy::iterator &EI,
1314 EnumValsTy::iterator &EIEnd,
1315 const llvm::APSInt &Val) {
1316 if (!ED->isClosed())
1317 return false;
1318
1319 if (const DeclRefExpr *DRE =
1320 dyn_cast<DeclRefExpr>(Val: CaseExpr->IgnoreParenImpCasts())) {
1321 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
1322 QualType VarType = VD->getType();
1323 CanQualType EnumType = S.Context.getCanonicalTagType(TD: ED);
1324 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
1325 S.Context.hasSameUnqualifiedType(T1: EnumType, T2: VarType))
1326 return false;
1327 }
1328 }
1329
1330 if (ED->hasAttr<FlagEnumAttr>())
1331 return !S.IsValueInFlagEnum(ED, Val, AllowMask: false);
1332
1333 while (EI != EIEnd && EI->first < Val)
1334 EI++;
1335
1336 if (EI != EIEnd && EI->first == Val)
1337 return false;
1338
1339 return true;
1340}
1341
1342static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
1343 const Expr *Case) {
1344 QualType CondType = Cond->getType();
1345 QualType CaseType = Case->getType();
1346
1347 const EnumType *CondEnumType = CondType->getAsCanonical<EnumType>();
1348 const EnumType *CaseEnumType = CaseType->getAsCanonical<EnumType>();
1349 if (!CondEnumType || !CaseEnumType)
1350 return;
1351
1352 // Ignore anonymous enums.
1353 if (!CondEnumType->getDecl()->getIdentifier() &&
1354 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
1355 return;
1356 if (!CaseEnumType->getDecl()->getIdentifier() &&
1357 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
1358 return;
1359
1360 if (S.Context.hasSameUnqualifiedType(T1: CondType, T2: CaseType))
1361 return;
1362
1363 S.Diag(Loc: Case->getExprLoc(), DiagID: diag::warn_comparison_of_mixed_enum_types_switch)
1364 << CondType << CaseType << Cond->getSourceRange()
1365 << Case->getSourceRange();
1366}
1367
1368StmtResult
1369Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
1370 Stmt *BodyStmt) {
1371 SwitchStmt *SS = cast<SwitchStmt>(Val: Switch);
1372 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
1373 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
1374 "switch stack missing push/pop!");
1375
1376 getCurFunction()->SwitchStack.pop_back();
1377
1378 if (!BodyStmt) return StmtError();
1379
1380 // OpenACC3.3 2.14.4:
1381 // The update directive is executable. It must not appear in place of the
1382 // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1383 // C++.
1384 if (isa<OpenACCUpdateConstruct>(Val: BodyStmt)) {
1385 Diag(Loc: BodyStmt->getBeginLoc(), DiagID: diag::err_acc_update_as_body) << /*switch*/ 3;
1386 BodyStmt = new (Context) NullStmt(BodyStmt->getBeginLoc());
1387 }
1388
1389 SS->setBody(BodyStmt);
1390
1391 Expr *CondExpr = SS->getCond();
1392 if (!CondExpr) return StmtError();
1393
1394 QualType CondType = CondExpr->getType();
1395
1396 // C++ 6.4.2.p2:
1397 // Integral promotions are performed (on the switch condition).
1398 //
1399 // A case value unrepresentable by the original switch condition
1400 // type (before the promotion) doesn't make sense, even when it can
1401 // be represented by the promoted type. Therefore we need to find
1402 // the pre-promotion type of the switch condition.
1403 const Expr *CondExprBeforePromotion = CondExpr;
1404 QualType CondTypeBeforePromotion =
1405 GetTypeBeforeIntegralPromotion(E&: CondExprBeforePromotion);
1406
1407 // Get the bitwidth of the switched-on value after promotions. We must
1408 // convert the integer case values to this width before comparison.
1409 bool HasDependentValue
1410 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
1411 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(T: CondType);
1412 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
1413
1414 // Get the width and signedness that the condition might actually have, for
1415 // warning purposes.
1416 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
1417 // type.
1418 unsigned CondWidthBeforePromotion
1419 = HasDependentValue ? 0 : Context.getIntWidth(T: CondTypeBeforePromotion);
1420 bool CondIsSignedBeforePromotion
1421 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
1422
1423 // Accumulate all of the case values in a vector so that we can sort them
1424 // and detect duplicates. This vector contains the APInt for the case after
1425 // it has been converted to the condition type.
1426 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
1427 CaseValsTy CaseVals;
1428
1429 // Keep track of any GNU case ranges we see. The APSInt is the low value.
1430 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
1431 CaseRangesTy CaseRanges;
1432
1433 DefaultStmt *TheDefaultStmt = nullptr;
1434
1435 bool CaseListIsErroneous = false;
1436
1437 // FIXME: We'd better diagnose missing or duplicate default labels even
1438 // in the dependent case. Because default labels themselves are never
1439 // dependent.
1440 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
1441 SC = SC->getNextSwitchCase()) {
1442
1443 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(Val: SC)) {
1444 if (TheDefaultStmt) {
1445 Diag(Loc: DS->getDefaultLoc(), DiagID: diag::err_multiple_default_labels_defined);
1446 Diag(Loc: TheDefaultStmt->getDefaultLoc(), DiagID: diag::note_duplicate_case_prev);
1447
1448 // FIXME: Remove the default statement from the switch block so that
1449 // we'll return a valid AST. This requires recursing down the AST and
1450 // finding it, not something we are set up to do right now. For now,
1451 // just lop the entire switch stmt out of the AST.
1452 CaseListIsErroneous = true;
1453 }
1454 TheDefaultStmt = DS;
1455
1456 } else {
1457 CaseStmt *CS = cast<CaseStmt>(Val: SC);
1458
1459 Expr *Lo = CS->getLHS();
1460
1461 if (Lo->isValueDependent()) {
1462 HasDependentValue = true;
1463 break;
1464 }
1465
1466 // We already verified that the expression has a constant value;
1467 // get that value (prior to conversions).
1468 const Expr *LoBeforePromotion = Lo;
1469 GetTypeBeforeIntegralPromotion(E&: LoBeforePromotion);
1470 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Ctx: Context);
1471
1472 // Check the unconverted value is within the range of possible values of
1473 // the switch expression.
1474 checkCaseValue(S&: *this, Loc: Lo->getBeginLoc(), Val: LoVal, UnpromotedWidth: CondWidthBeforePromotion,
1475 UnpromotedSign: CondIsSignedBeforePromotion);
1476
1477 // FIXME: This duplicates the check performed for warn_not_in_enum below.
1478 checkEnumTypesInSwitchStmt(S&: *this, Cond: CondExprBeforePromotion,
1479 Case: LoBeforePromotion);
1480
1481 // Convert the value to the same width/sign as the condition.
1482 AdjustAPSInt(Val&: LoVal, BitWidth: CondWidth, IsSigned: CondIsSigned);
1483
1484 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
1485 if (CS->getRHS()) {
1486 if (CS->getRHS()->isValueDependent()) {
1487 HasDependentValue = true;
1488 break;
1489 }
1490 CaseRanges.push_back(x: std::make_pair(x&: LoVal, y&: CS));
1491 } else
1492 CaseVals.push_back(Elt: std::make_pair(x&: LoVal, y&: CS));
1493 }
1494 }
1495
1496 if (!HasDependentValue) {
1497 // If we don't have a default statement, check whether the
1498 // condition is constant.
1499 llvm::APSInt ConstantCondValue;
1500 bool HasConstantCond = false;
1501 if (!TheDefaultStmt) {
1502 Expr::EvalResult Result;
1503 HasConstantCond = CondExpr->EvaluateAsInt(Result, Ctx: Context,
1504 AllowSideEffects: Expr::SE_AllowSideEffects);
1505 if (Result.Val.isInt())
1506 ConstantCondValue = Result.Val.getInt();
1507 assert(!HasConstantCond ||
1508 (ConstantCondValue.getBitWidth() == CondWidth &&
1509 ConstantCondValue.isSigned() == CondIsSigned));
1510 Diag(Loc: SwitchLoc, DiagID: diag::warn_switch_default);
1511 }
1512 bool ShouldCheckConstantCond = HasConstantCond;
1513
1514 // Sort all the scalar case values so we can easily detect duplicates.
1515 llvm::stable_sort(Range&: CaseVals, C: CmpCaseVals);
1516
1517 if (!CaseVals.empty()) {
1518 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
1519 if (ShouldCheckConstantCond &&
1520 CaseVals[i].first == ConstantCondValue)
1521 ShouldCheckConstantCond = false;
1522
1523 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
1524 // If we have a duplicate, report it.
1525 // First, determine if either case value has a name
1526 StringRef PrevString, CurrString;
1527 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
1528 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
1529 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Val: PrevCase)) {
1530 PrevString = DeclRef->getDecl()->getName();
1531 }
1532 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Val: CurrCase)) {
1533 CurrString = DeclRef->getDecl()->getName();
1534 }
1535 SmallString<16> CaseValStr;
1536 CaseVals[i-1].first.toString(Str&: CaseValStr);
1537
1538 if (PrevString == CurrString)
1539 Diag(Loc: CaseVals[i].second->getLHS()->getBeginLoc(),
1540 DiagID: diag::err_duplicate_case)
1541 << (PrevString.empty() ? CaseValStr.str() : PrevString);
1542 else
1543 Diag(Loc: CaseVals[i].second->getLHS()->getBeginLoc(),
1544 DiagID: diag::err_duplicate_case_differing_expr)
1545 << (PrevString.empty() ? CaseValStr.str() : PrevString)
1546 << (CurrString.empty() ? CaseValStr.str() : CurrString)
1547 << CaseValStr;
1548
1549 Diag(Loc: CaseVals[i - 1].second->getLHS()->getBeginLoc(),
1550 DiagID: diag::note_duplicate_case_prev);
1551 // FIXME: We really want to remove the bogus case stmt from the
1552 // substmt, but we have no way to do this right now.
1553 CaseListIsErroneous = true;
1554 }
1555 }
1556 }
1557
1558 // Detect duplicate case ranges, which usually don't exist at all in
1559 // the first place.
1560 if (!CaseRanges.empty()) {
1561 // Sort all the case ranges by their low value so we can easily detect
1562 // overlaps between ranges.
1563 llvm::stable_sort(Range&: CaseRanges);
1564
1565 // Scan the ranges, computing the high values and removing empty ranges.
1566 std::vector<llvm::APSInt> HiVals;
1567 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1568 llvm::APSInt &LoVal = CaseRanges[i].first;
1569 CaseStmt *CR = CaseRanges[i].second;
1570 Expr *Hi = CR->getRHS();
1571
1572 const Expr *HiBeforePromotion = Hi;
1573 GetTypeBeforeIntegralPromotion(E&: HiBeforePromotion);
1574 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Ctx: Context);
1575
1576 // Check the unconverted value is within the range of possible values of
1577 // the switch expression.
1578 checkCaseValue(S&: *this, Loc: Hi->getBeginLoc(), Val: HiVal,
1579 UnpromotedWidth: CondWidthBeforePromotion, UnpromotedSign: CondIsSignedBeforePromotion);
1580
1581 // Convert the value to the same width/sign as the condition.
1582 AdjustAPSInt(Val&: HiVal, BitWidth: CondWidth, IsSigned: CondIsSigned);
1583
1584 // If the low value is bigger than the high value, the case is empty.
1585 if (LoVal > HiVal) {
1586 Diag(Loc: CR->getLHS()->getBeginLoc(), DiagID: diag::warn_case_empty_range)
1587 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1588 CaseRanges.erase(position: CaseRanges.begin()+i);
1589 --i;
1590 --e;
1591 continue;
1592 }
1593
1594 if (ShouldCheckConstantCond &&
1595 LoVal <= ConstantCondValue &&
1596 ConstantCondValue <= HiVal)
1597 ShouldCheckConstantCond = false;
1598
1599 HiVals.push_back(x: HiVal);
1600 }
1601
1602 // Rescan the ranges, looking for overlap with singleton values and other
1603 // ranges. Since the range list is sorted, we only need to compare case
1604 // ranges with their neighbors.
1605 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1606 llvm::APSInt &CRLo = CaseRanges[i].first;
1607 llvm::APSInt &CRHi = HiVals[i];
1608 CaseStmt *CR = CaseRanges[i].second;
1609
1610 // Check to see whether the case range overlaps with any
1611 // singleton cases.
1612 CaseStmt *OverlapStmt = nullptr;
1613 llvm::APSInt OverlapVal(32);
1614
1615 // Find the smallest value >= the lower bound. If I is in the
1616 // case range, then we have overlap.
1617 CaseValsTy::iterator I =
1618 llvm::lower_bound(Range&: CaseVals, Value&: CRLo, C: CaseCompareFunctor());
1619 if (I != CaseVals.end() && I->first < CRHi) {
1620 OverlapVal = I->first; // Found overlap with scalar.
1621 OverlapStmt = I->second;
1622 }
1623
1624 // Find the smallest value bigger than the upper bound.
1625 I = std::upper_bound(first: I, last: CaseVals.end(), val: CRHi, comp: CaseCompareFunctor());
1626 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1627 OverlapVal = (I-1)->first; // Found overlap with scalar.
1628 OverlapStmt = (I-1)->second;
1629 }
1630
1631 // Check to see if this case stmt overlaps with the subsequent
1632 // case range.
1633 if (i && CRLo <= HiVals[i-1]) {
1634 OverlapVal = HiVals[i-1]; // Found overlap with range.
1635 OverlapStmt = CaseRanges[i-1].second;
1636 }
1637
1638 if (OverlapStmt) {
1639 // If we have a duplicate, report it.
1640 Diag(Loc: CR->getLHS()->getBeginLoc(), DiagID: diag::err_duplicate_case)
1641 << toString(I: OverlapVal, Radix: 10);
1642 Diag(Loc: OverlapStmt->getLHS()->getBeginLoc(),
1643 DiagID: diag::note_duplicate_case_prev);
1644 // FIXME: We really want to remove the bogus case stmt from the
1645 // substmt, but we have no way to do this right now.
1646 CaseListIsErroneous = true;
1647 }
1648 }
1649 }
1650
1651 // Complain if we have a constant condition and we didn't find a match.
1652 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1653 ShouldCheckConstantCond) {
1654 // TODO: it would be nice if we printed enums as enums, chars as
1655 // chars, etc.
1656 Diag(Loc: CondExpr->getExprLoc(), DiagID: diag::warn_missing_case_for_condition)
1657 << toString(I: ConstantCondValue, Radix: 10)
1658 << CondExpr->getSourceRange();
1659 }
1660
1661 // Check to see if switch is over an Enum and handles all of its
1662 // values. We only issue a warning if there is not 'default:', but
1663 // we still do the analysis to preserve this information in the AST
1664 // (which can be used by flow-based analyes).
1665 //
1666 // If switch has default case, then ignore it.
1667 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1668 CondTypeBeforePromotion->isEnumeralType()) {
1669 const auto *ED = CondTypeBeforePromotion->castAsEnumDecl();
1670 if (!ED->isCompleteDefinition() || ED->enumerators().empty())
1671 goto enum_out;
1672
1673 EnumValsTy EnumVals;
1674
1675 // Gather all enum values, set their type and sort them,
1676 // allowing easier comparison with CaseVals.
1677 for (auto *EDI : ED->enumerators()) {
1678 llvm::APSInt Val = EDI->getInitVal();
1679 AdjustAPSInt(Val, BitWidth: CondWidth, IsSigned: CondIsSigned);
1680 EnumVals.push_back(Elt: std::make_pair(x&: Val, y&: EDI));
1681 }
1682 llvm::stable_sort(Range&: EnumVals, C: CmpEnumVals);
1683 auto EI = EnumVals.begin(), EIEnd = llvm::unique(R&: EnumVals, P: EqEnumVals);
1684
1685 // See which case values aren't in enum.
1686 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1687 CI != CaseVals.end(); CI++) {
1688 Expr *CaseExpr = CI->second->getLHS();
1689 if (ShouldDiagnoseSwitchCaseNotInEnum(S: *this, ED, CaseExpr, EI, EIEnd,
1690 Val: CI->first))
1691 Diag(Loc: CaseExpr->getExprLoc(), DiagID: diag::warn_not_in_enum)
1692 << CondTypeBeforePromotion;
1693 }
1694
1695 // See which of case ranges aren't in enum
1696 EI = EnumVals.begin();
1697 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1698 RI != CaseRanges.end(); RI++) {
1699 Expr *CaseExpr = RI->second->getLHS();
1700 if (ShouldDiagnoseSwitchCaseNotInEnum(S: *this, ED, CaseExpr, EI, EIEnd,
1701 Val: RI->first))
1702 Diag(Loc: CaseExpr->getExprLoc(), DiagID: diag::warn_not_in_enum)
1703 << CondTypeBeforePromotion;
1704
1705 llvm::APSInt Hi =
1706 RI->second->getRHS()->EvaluateKnownConstInt(Ctx: Context);
1707 AdjustAPSInt(Val&: Hi, BitWidth: CondWidth, IsSigned: CondIsSigned);
1708
1709 CaseExpr = RI->second->getRHS();
1710 if (ShouldDiagnoseSwitchCaseNotInEnum(S: *this, ED, CaseExpr, EI, EIEnd,
1711 Val: Hi))
1712 Diag(Loc: CaseExpr->getExprLoc(), DiagID: diag::warn_not_in_enum)
1713 << CondTypeBeforePromotion;
1714 }
1715
1716 // Check which enum vals aren't in switch
1717 auto CI = CaseVals.begin();
1718 auto RI = CaseRanges.begin();
1719 bool hasCasesNotInSwitch = false;
1720
1721 SmallVector<DeclarationName,8> UnhandledNames;
1722
1723 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1724 // Don't warn about omitted unavailable EnumConstantDecls.
1725 switch (EI->second->getAvailability()) {
1726 case AR_Deprecated:
1727 // Deprecated enumerators need to be handled: they may be deprecated,
1728 // but can still occur.
1729 break;
1730
1731 case AR_Unavailable:
1732 // Omitting an unavailable enumerator is ok; it should never occur.
1733 continue;
1734
1735 case AR_NotYetIntroduced:
1736 // Partially available enum constants should be present. Note that we
1737 // suppress -Wunguarded-availability diagnostics for such uses.
1738 case AR_Available:
1739 break;
1740 }
1741
1742 if (EI->second->hasAttr<UnusedAttr>())
1743 continue;
1744
1745 // Drop unneeded case values
1746 while (CI != CaseVals.end() && CI->first < EI->first)
1747 CI++;
1748
1749 if (CI != CaseVals.end() && CI->first == EI->first)
1750 continue;
1751
1752 // Drop unneeded case ranges
1753 for (; RI != CaseRanges.end(); RI++) {
1754 llvm::APSInt Hi =
1755 RI->second->getRHS()->EvaluateKnownConstInt(Ctx: Context);
1756 AdjustAPSInt(Val&: Hi, BitWidth: CondWidth, IsSigned: CondIsSigned);
1757 if (EI->first <= Hi)
1758 break;
1759 }
1760
1761 if (RI == CaseRanges.end() || EI->first < RI->first) {
1762 hasCasesNotInSwitch = true;
1763 UnhandledNames.push_back(Elt: EI->second->getDeclName());
1764 }
1765 }
1766
1767 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1768 Diag(Loc: TheDefaultStmt->getDefaultLoc(), DiagID: diag::warn_unreachable_default);
1769
1770 // Produce a nice diagnostic if multiple values aren't handled.
1771 if (!UnhandledNames.empty()) {
1772 auto DB = Diag(Loc: CondExpr->getExprLoc(), DiagID: TheDefaultStmt
1773 ? diag::warn_def_missing_case
1774 : diag::warn_missing_case)
1775 << CondExpr->getSourceRange() << (int)UnhandledNames.size();
1776
1777 for (size_t I = 0, E = std::min(a: UnhandledNames.size(), b: (size_t)3);
1778 I != E; ++I)
1779 DB << UnhandledNames[I];
1780 }
1781
1782 if (!hasCasesNotInSwitch)
1783 SS->setAllEnumCasesCovered();
1784 }
1785 enum_out:;
1786 }
1787
1788 if (BodyStmt)
1789 DiagnoseEmptyStmtBody(StmtLoc: CondExpr->getEndLoc(), Body: BodyStmt,
1790 DiagID: diag::warn_empty_switch_body);
1791
1792 // FIXME: If the case list was broken is some way, we don't have a good system
1793 // to patch it up. Instead, just return the whole substmt as broken.
1794 if (CaseListIsErroneous)
1795 return StmtError();
1796
1797 return SS;
1798}
1799
1800void
1801Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1802 Expr *SrcExpr) {
1803
1804 if (!DstType->isEnumeralType())
1805 return;
1806
1807 if (!SrcType->isIntegerType() ||
1808 Context.hasSameUnqualifiedType(T1: SrcType, T2: DstType))
1809 return;
1810
1811 if (SrcExpr->isTypeDependent() || SrcExpr->isValueDependent())
1812 return;
1813
1814 const auto *ED = DstType->castAsEnumDecl();
1815 if (!ED->isClosed())
1816 return;
1817
1818 if (Diags.isIgnored(DiagID: diag::warn_not_in_enum_assignment, Loc: SrcExpr->getExprLoc()))
1819 return;
1820
1821 std::optional<llvm::APSInt> RHSVal = SrcExpr->getIntegerConstantExpr(Ctx: Context);
1822 if (!RHSVal)
1823 return;
1824
1825 // Get the bitwidth of the enum value before promotions.
1826 unsigned DstWidth = Context.getIntWidth(T: DstType);
1827 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1828 AdjustAPSInt(Val&: *RHSVal, BitWidth: DstWidth, IsSigned: DstIsSigned);
1829
1830 if (ED->hasAttr<FlagEnumAttr>()) {
1831 if (!IsValueInFlagEnum(ED, Val: *RHSVal, /*AllowMask=*/true))
1832 Diag(Loc: SrcExpr->getExprLoc(), DiagID: diag::warn_not_in_enum_assignment)
1833 << DstType.getUnqualifiedType();
1834 return;
1835 }
1836
1837 const EnumDecl *Key = ED->getCanonicalDecl();
1838 auto [It, Inserted] = AssignEnumCache.try_emplace(Key);
1839 auto &Values = It->second;
1840
1841 if (Inserted) {
1842 Values.reserve(N: std::distance(first: ED->enumerator_begin(), last: ED->enumerator_end()));
1843
1844 for (auto *EC : ED->enumerators()) {
1845 Values.push_back(Elt: EC->getInitVal());
1846 AdjustAPSInt(Val&: Values.back(), BitWidth: DstWidth, IsSigned: DstIsSigned);
1847 }
1848
1849 if (Values.empty())
1850 return;
1851
1852 llvm::sort(C&: Values);
1853 Values.erase(CS: llvm::unique(R&: Values), CE: Values.end());
1854 }
1855
1856 if (llvm::binary_search(Range&: Values, Value&: *RHSVal))
1857 return;
1858
1859 Diag(Loc: SrcExpr->getExprLoc(), DiagID: diag::warn_not_in_enum_assignment)
1860 << DstType.getUnqualifiedType();
1861}
1862
1863// Checks for issues that are common to `for`/`while` statements.
1864static void CheckLoopBody(Sema &S, Expr *CondExpr, Stmt *Body) {
1865 // Check for comma operator misuse.
1866 if (CondExpr &&
1867 !S.Diags.isIgnored(DiagID: diag::warn_comma_operator, Loc: CondExpr->getExprLoc()))
1868 CommaVisitor(S).Visit(S: CondExpr);
1869
1870 if (isa<NullStmt>(Val: Body)) {
1871 // Tell Sema::ActOnCompoundStmt to perform a check on
1872 // this suspicious empty `for`/`while` loop when
1873 // processing the compound statement that contains this loop.
1874 //
1875 // The actual check cannot be done here directly as it may
1876 // depend on other statements following the `for`/`while`
1877 // loop, in the outer enclosing CompoundStmt; see the
1878 // comment in Sema::ActOnCompoundStmt for an example
1879 // of when this happens.
1880 //
1881 // This does not apply for `if` statements and range-`for`
1882 // loops which call DiagnoseEmptyStmtBody() directly.
1883 S.getCurCompoundScope().setHasEmptyLoopBodies();
1884 } else
1885 CheckRedundantDeferStmt(S, Body);
1886}
1887
1888StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
1889 SourceLocation LParenLoc, ConditionResult Cond,
1890 SourceLocation RParenLoc, Stmt *Body) {
1891 if (Cond.isInvalid())
1892 return StmtError();
1893
1894 // OpenACC3.3 2.14.4:
1895 // The update directive is executable. It must not appear in place of the
1896 // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1897 // C++.
1898 if (isa<OpenACCUpdateConstruct>(Val: Body)) {
1899 Diag(Loc: Body->getBeginLoc(), DiagID: diag::err_acc_update_as_body) << /*while*/ 1;
1900 Body = new (Context) NullStmt(Body->getBeginLoc());
1901 }
1902
1903 auto CondVal = Cond.get();
1904
1905 CheckLoopBody(S&: *this, CondExpr: CondVal.second, Body);
1906
1907 return WhileStmt::Create(Ctx: Context, Var: CondVal.first, Cond: CondVal.second, Body,
1908 WL: WhileLoc, LParenLoc, RParenLoc);
1909}
1910
1911StmtResult
1912Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1913 SourceLocation WhileLoc, SourceLocation CondLParen,
1914 Expr *Cond, SourceLocation CondRParen) {
1915 assert(Cond && "ActOnDoStmt(): missing expression");
1916
1917 ExprResult CondResult = CheckBooleanCondition(Loc: DoLoc, E: Cond);
1918 if (CondResult.isInvalid())
1919 return StmtError();
1920 Cond = CondResult.get();
1921
1922 CondResult = ActOnFinishFullExpr(Expr: Cond, CC: DoLoc, /*DiscardedValue*/ false);
1923 if (CondResult.isInvalid())
1924 return StmtError();
1925 Cond = CondResult.get();
1926
1927 // OpenACC3.3 2.14.4:
1928 // The update directive is executable. It must not appear in place of the
1929 // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1930 // C++.
1931 if (isa<OpenACCUpdateConstruct>(Val: Body)) {
1932 Diag(Loc: Body->getBeginLoc(), DiagID: diag::err_acc_update_as_body) << /*do*/ 2;
1933 Body = new (Context) NullStmt(Body->getBeginLoc());
1934 }
1935
1936 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1937}
1938
1939namespace {
1940 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1941 using DeclSetVector = llvm::SmallSetVector<VarDecl *, 8>;
1942
1943 // This visitor will traverse a conditional statement and store all
1944 // the evaluated decls into a vector. Simple is set to true if none
1945 // of the excluded constructs are used.
1946 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1947 DeclSetVector &Decls;
1948 SmallVectorImpl<SourceRange> &Ranges;
1949 bool Simple;
1950 public:
1951 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1952
1953 DeclExtractor(Sema &S, DeclSetVector &Decls,
1954 SmallVectorImpl<SourceRange> &Ranges) :
1955 Inherited(S.Context),
1956 Decls(Decls),
1957 Ranges(Ranges),
1958 Simple(true) {}
1959
1960 bool isSimple() { return Simple; }
1961
1962 // Replaces the method in EvaluatedExprVisitor.
1963 void VisitMemberExpr(MemberExpr* E) {
1964 Simple = false;
1965 }
1966
1967 // Any Stmt not explicitly listed will cause the condition to be marked
1968 // complex.
1969 void VisitStmt(Stmt *S) { Simple = false; }
1970
1971 void VisitBinaryOperator(BinaryOperator *E) {
1972 Visit(S: E->getLHS());
1973 Visit(S: E->getRHS());
1974 }
1975
1976 void VisitCastExpr(CastExpr *E) {
1977 Visit(S: E->getSubExpr());
1978 }
1979
1980 void VisitUnaryOperator(UnaryOperator *E) {
1981 // Skip checking conditionals with derefernces.
1982 if (E->getOpcode() == UO_Deref)
1983 Simple = false;
1984 else
1985 Visit(S: E->getSubExpr());
1986 }
1987
1988 void VisitConditionalOperator(ConditionalOperator *E) {
1989 Visit(S: E->getCond());
1990 Visit(S: E->getTrueExpr());
1991 Visit(S: E->getFalseExpr());
1992 }
1993
1994 void VisitParenExpr(ParenExpr *E) {
1995 Visit(S: E->getSubExpr());
1996 }
1997
1998 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1999 Visit(S: E->getOpaqueValue()->getSourceExpr());
2000 Visit(S: E->getFalseExpr());
2001 }
2002
2003 void VisitIntegerLiteral(IntegerLiteral *E) { }
2004 void VisitFloatingLiteral(FloatingLiteral *E) { }
2005 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
2006 void VisitCharacterLiteral(CharacterLiteral *E) { }
2007 void VisitGNUNullExpr(GNUNullExpr *E) { }
2008 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
2009
2010 void VisitDeclRefExpr(DeclRefExpr *E) {
2011 VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl());
2012 if (!VD) {
2013 // Don't allow unhandled Decl types.
2014 Simple = false;
2015 return;
2016 }
2017
2018 Ranges.push_back(Elt: E->getSourceRange());
2019
2020 Decls.insert(X: VD);
2021 }
2022
2023 }; // end class DeclExtractor
2024
2025 // DeclMatcher checks to see if the decls are used in a non-evaluated
2026 // context.
2027 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
2028 DeclSetVector &Decls;
2029 bool FoundDecl;
2030
2031 public:
2032 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
2033
2034 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
2035 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
2036 if (!Statement) return;
2037
2038 Visit(S: Statement);
2039 }
2040
2041 void VisitReturnStmt(ReturnStmt *S) {
2042 FoundDecl = true;
2043 }
2044
2045 void VisitBreakStmt(BreakStmt *S) {
2046 FoundDecl = true;
2047 }
2048
2049 void VisitGotoStmt(GotoStmt *S) {
2050 FoundDecl = true;
2051 }
2052
2053 void VisitCastExpr(CastExpr *E) {
2054 if (E->getCastKind() == CK_LValueToRValue)
2055 CheckLValueToRValueCast(E: E->getSubExpr());
2056 else
2057 Visit(S: E->getSubExpr());
2058 }
2059
2060 void CheckLValueToRValueCast(Expr *E) {
2061 E = E->IgnoreParenImpCasts();
2062
2063 if (isa<DeclRefExpr>(Val: E)) {
2064 return;
2065 }
2066
2067 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
2068 Visit(S: CO->getCond());
2069 CheckLValueToRValueCast(E: CO->getTrueExpr());
2070 CheckLValueToRValueCast(E: CO->getFalseExpr());
2071 return;
2072 }
2073
2074 if (BinaryConditionalOperator *BCO =
2075 dyn_cast<BinaryConditionalOperator>(Val: E)) {
2076 CheckLValueToRValueCast(E: BCO->getOpaqueValue()->getSourceExpr());
2077 CheckLValueToRValueCast(E: BCO->getFalseExpr());
2078 return;
2079 }
2080
2081 Visit(S: E);
2082 }
2083
2084 void VisitDeclRefExpr(DeclRefExpr *E) {
2085 if (const auto *VD = dyn_cast<VarDecl>(Val: E->getDecl())) {
2086 if (Decls.count(key: VD))
2087 FoundDecl = true;
2088 } else if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: E->getDecl());
2089 MD && isLambdaCallOperator(MD)) {
2090 // FIXME: This has limitations handling updates to the loop control
2091 // variable that occur indirectly inside a lambda called from the loop
2092 // body. For example:
2093 //
2094 // int a = 0;
2095 // int *c = &a;
2096 // auto incr_c = [c]() { ++*c; };
2097 // for (a = 10; a <= 20; incr_c())
2098 // foo(a);
2099 for (const auto &Capture : MD->getParent()->captures()) {
2100 if (!Capture.capturesVariable())
2101 continue;
2102
2103 LambdaCaptureKind CK = Capture.getCaptureKind();
2104 if (CK != LCK_ByRef)
2105 continue;
2106
2107 const auto *VD = dyn_cast<VarDecl>(Val: Capture.getCapturedVar());
2108 if (VD && Decls.count(key: VD))
2109 FoundDecl = true;
2110 }
2111 }
2112 }
2113
2114 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
2115 // Only need to visit the semantics for POE.
2116 // SyntaticForm doesn't really use the Decal.
2117 for (auto *S : POE->semantics()) {
2118 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: S))
2119 // Look past the OVE into the expression it binds.
2120 Visit(S: OVE->getSourceExpr());
2121 else
2122 Visit(S);
2123 }
2124 }
2125
2126 bool FoundDeclInUse() { return FoundDecl; }
2127
2128 }; // end class DeclMatcher
2129
2130 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
2131 Expr *Third, Stmt *Body) {
2132 // Condition is empty
2133 if (!Second) return;
2134
2135 if (S.Diags.isIgnored(DiagID: diag::warn_variables_not_in_loop_body,
2136 Loc: Second->getBeginLoc()))
2137 return;
2138
2139 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_variables_not_in_loop_body);
2140 DeclSetVector Decls;
2141 SmallVector<SourceRange, 10> Ranges;
2142 DeclExtractor DE(S, Decls, Ranges);
2143 DE.Visit(S: Second);
2144
2145 // Don't analyze complex conditionals.
2146 if (!DE.isSimple()) return;
2147
2148 // No decls found.
2149 if (Decls.size() == 0) return;
2150
2151 // Don't warn on volatile, static, or global variables.
2152 for (auto *VD : Decls)
2153 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
2154 return;
2155
2156 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
2157 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
2158 DeclMatcher(S, Decls, Body).FoundDeclInUse())
2159 return;
2160
2161 // Load decl names into diagnostic.
2162 if (Decls.size() > 4) {
2163 PDiag << 0;
2164 } else {
2165 PDiag << (unsigned)Decls.size();
2166 for (auto *VD : Decls)
2167 PDiag << VD->getDeclName();
2168 }
2169
2170 for (auto Range : Ranges)
2171 PDiag << Range;
2172
2173 S.Diag(Loc: Ranges.begin()->getBegin(), PD: PDiag);
2174 }
2175
2176 // If Statement is an incemement or decrement, return true and sets the
2177 // variables Increment and DRE.
2178 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
2179 DeclRefExpr *&DRE) {
2180 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Val: Statement))
2181 if (!Cleanups->cleanupsHaveSideEffects())
2182 Statement = Cleanups->getSubExpr();
2183
2184 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Statement)) {
2185 switch (UO->getOpcode()) {
2186 default: return false;
2187 case UO_PostInc:
2188 case UO_PreInc:
2189 Increment = true;
2190 break;
2191 case UO_PostDec:
2192 case UO_PreDec:
2193 Increment = false;
2194 break;
2195 }
2196 DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr());
2197 return DRE;
2198 }
2199
2200 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Val: Statement)) {
2201 FunctionDecl *FD = Call->getDirectCallee();
2202 if (!FD || !FD->isOverloadedOperator()) return false;
2203 switch (FD->getOverloadedOperator()) {
2204 default: return false;
2205 case OO_PlusPlus:
2206 Increment = true;
2207 break;
2208 case OO_MinusMinus:
2209 Increment = false;
2210 break;
2211 }
2212 DRE = dyn_cast<DeclRefExpr>(Val: Call->getArg(Arg: 0));
2213 return DRE;
2214 }
2215
2216 return false;
2217 }
2218
2219 // A visitor to determine if a continue or break statement is a
2220 // subexpression.
2221 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
2222 SourceLocation BreakLoc;
2223 SourceLocation ContinueLoc;
2224 bool InSwitch = false;
2225
2226 public:
2227 BreakContinueFinder(Sema &S, const Stmt* Body) :
2228 Inherited(S.Context) {
2229 Visit(S: Body);
2230 }
2231
2232 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
2233
2234 void VisitContinueStmt(const ContinueStmt* E) {
2235 ContinueLoc = E->getKwLoc();
2236 }
2237
2238 void VisitBreakStmt(const BreakStmt* E) {
2239 if (!InSwitch)
2240 BreakLoc = E->getKwLoc();
2241 }
2242
2243 void VisitSwitchStmt(const SwitchStmt* S) {
2244 if (const Stmt *Init = S->getInit())
2245 Visit(S: Init);
2246 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
2247 Visit(S: CondVar);
2248 if (const Stmt *Cond = S->getCond())
2249 Visit(S: Cond);
2250
2251 // Don't return break statements from the body of a switch.
2252 InSwitch = true;
2253 if (const Stmt *Body = S->getBody())
2254 Visit(S: Body);
2255 InSwitch = false;
2256 }
2257
2258 void VisitForStmt(const ForStmt *S) {
2259 // Only visit the init statement of a for loop; the body
2260 // has a different break/continue scope.
2261 if (const Stmt *Init = S->getInit())
2262 Visit(S: Init);
2263 }
2264
2265 void VisitWhileStmt(const WhileStmt *) {
2266 // Do nothing; the children of a while loop have a different
2267 // break/continue scope.
2268 }
2269
2270 void VisitDoStmt(const DoStmt *) {
2271 // Do nothing; the children of a while loop have a different
2272 // break/continue scope.
2273 }
2274
2275 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2276 // Only visit the initialization of a for loop; the body
2277 // has a different break/continue scope.
2278 if (const Stmt *Init = S->getInit())
2279 Visit(S: Init);
2280 if (const Stmt *Range = S->getRangeStmt())
2281 Visit(S: Range);
2282 if (const Stmt *Begin = S->getBeginStmt())
2283 Visit(S: Begin);
2284 if (const Stmt *End = S->getEndStmt())
2285 Visit(S: End);
2286 }
2287
2288 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
2289 // Only visit the initialization of a for loop; the body
2290 // has a different break/continue scope.
2291 if (const Stmt *Element = S->getElement())
2292 Visit(S: Element);
2293 if (const Stmt *Collection = S->getCollection())
2294 Visit(S: Collection);
2295 }
2296
2297 bool ContinueFound() { return ContinueLoc.isValid(); }
2298 bool BreakFound() { return BreakLoc.isValid(); }
2299 SourceLocation GetContinueLoc() { return ContinueLoc; }
2300 SourceLocation GetBreakLoc() { return BreakLoc; }
2301
2302 }; // end class BreakContinueFinder
2303
2304 // Emit a warning when a loop increment/decrement appears twice per loop
2305 // iteration. The conditions which trigger this warning are:
2306 // 1) The last statement in the loop body and the third expression in the
2307 // for loop are both increment or both decrement of the same variable
2308 // 2) No continue statements in the loop body.
2309 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
2310 // Return when there is nothing to check.
2311 if (!Body || !Third) return;
2312
2313 // Get the last statement from the loop body.
2314 CompoundStmt *CS = dyn_cast<CompoundStmt>(Val: Body);
2315 if (!CS || CS->body_empty()) return;
2316 Stmt *LastStmt = CS->body_back();
2317 if (!LastStmt) return;
2318
2319 if (S.Diags.isIgnored(DiagID: diag::warn_redundant_loop_iteration,
2320 Loc: Third->getBeginLoc()))
2321 return;
2322
2323 bool LoopIncrement, LastIncrement;
2324 DeclRefExpr *LoopDRE, *LastDRE;
2325
2326 if (!ProcessIterationStmt(S, Statement: Third, Increment&: LoopIncrement, DRE&: LoopDRE)) return;
2327 if (!ProcessIterationStmt(S, Statement: LastStmt, Increment&: LastIncrement, DRE&: LastDRE)) return;
2328
2329 // Check that the two statements are both increments or both decrements
2330 // on the same variable.
2331 if (LoopIncrement != LastIncrement ||
2332 LoopDRE->getDecl() != LastDRE->getDecl()) return;
2333
2334 if (BreakContinueFinder(S, Body).ContinueFound()) return;
2335
2336 S.Diag(Loc: LastDRE->getLocation(), DiagID: diag::warn_redundant_loop_iteration)
2337 << LastDRE->getDecl() << LastIncrement;
2338 S.Diag(Loc: LoopDRE->getLocation(), DiagID: diag::note_loop_iteration_here)
2339 << LoopIncrement;
2340 }
2341
2342} // end namespace
2343
2344StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
2345 Stmt *First, ConditionResult Second,
2346 FullExprArg third, SourceLocation RParenLoc,
2347 Stmt *Body) {
2348 if (Second.isInvalid())
2349 return StmtError();
2350
2351 if (!getLangOpts().CPlusPlus) {
2352 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(Val: First)) {
2353 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2354 // declare identifiers for objects having storage class 'auto' or
2355 // 'register'.
2356 const Decl *NonVarSeen = nullptr;
2357 bool VarDeclSeen = false;
2358 for (auto *DI : DS->decls()) {
2359 if (VarDecl *VD = dyn_cast<VarDecl>(Val: DI)) {
2360 VarDeclSeen = true;
2361 if (VD->isLocalVarDecl() && !VD->hasLocalStorage())
2362 DiagCompat(Loc: DI->getLocation(),
2363 CompatDiagId: diag_compat::non_local_variable_decl_in_for);
2364 } else if (!NonVarSeen) {
2365 // Keep track of the first non-variable declaration we saw so that
2366 // we can diagnose if we don't see any variable declarations. This
2367 // covers a case like declaring a typedef, function, or structure
2368 // type rather than a variable.
2369 //
2370 // Note, _Static_assert is acceptable because it does not declare an
2371 // identifier at all, so "for object having" does not apply.
2372 if (!isa<StaticAssertDecl>(Val: DI))
2373 NonVarSeen = DI;
2374 }
2375 }
2376 // Diagnose if we saw a non-variable declaration but no variable
2377 // declarations.
2378 if (NonVarSeen && !VarDeclSeen)
2379 DiagCompat(Loc: NonVarSeen->getLocation(),
2380 CompatDiagId: diag_compat::non_variable_decl_in_for);
2381 }
2382 }
2383
2384 if (!Second.get().first)
2385 CheckForLoopConditionalStatement(S&: *this, Second: Second.get().second, Third: third.get(),
2386 Body);
2387 CheckForRedundantIteration(S&: *this, Third: third.get(), Body);
2388
2389 CheckLoopBody(S&: *this, CondExpr: Second.get().second, Body);
2390
2391 Expr *Third = third.release().getAs<Expr>();
2392
2393 return new (Context)
2394 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
2395 Body, ForLoc, LParenLoc, RParenLoc);
2396}
2397
2398StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
2399 // Reduce placeholder expressions here. Note that this rejects the
2400 // use of pseudo-object l-values in this position.
2401 ExprResult result = CheckPlaceholderExpr(E);
2402 if (result.isInvalid()) return StmtError();
2403 E = result.get();
2404
2405 ExprResult FullExpr = ActOnFinishFullExpr(Expr: E, /*DiscardedValue*/ false);
2406 if (FullExpr.isInvalid())
2407 return StmtError();
2408 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
2409}
2410
2411/// Finish building a variable declaration for a for-range statement.
2412/// \return true if an error occurs.
2413static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
2414 SourceLocation Loc, int DiagID) {
2415 if (Decl->getType()->isUndeducedType()) {
2416 ExprResult Res = Init;
2417 if (!Res.isUsable()) {
2418 Decl->setInvalidDecl();
2419 return true;
2420 }
2421 Init = Res.get();
2422 }
2423
2424 // Deduce the type for the iterator variable now rather than leaving it to
2425 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2426 QualType InitType;
2427 if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVoidType()) {
2428 SemaRef.Diag(Loc, DiagID) << Init->getType();
2429 } else {
2430 TemplateDeductionInfo Info(Init->getExprLoc());
2431 TemplateDeductionResult Result = SemaRef.DeduceAutoType(
2432 AutoTypeLoc: Decl->getTypeSourceInfo()->getTypeLoc(), Initializer: Init, Result&: InitType, Info);
2433 if (Result != TemplateDeductionResult::Success &&
2434 Result != TemplateDeductionResult::AlreadyDiagnosed)
2435 SemaRef.Diag(Loc, DiagID) << Init->getType();
2436 }
2437
2438 if (InitType.isNull()) {
2439 Decl->setInvalidDecl();
2440 return true;
2441 }
2442 Decl->setType(InitType);
2443
2444 // In ARC, infer lifetime.
2445 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2446 // we're doing the equivalent of fast iteration.
2447 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2448 SemaRef.ObjC().inferObjCARCLifetime(decl: Decl))
2449 Decl->setInvalidDecl();
2450
2451 SemaRef.AddInitializerToDecl(dcl: Decl, init: Init, /*DirectInit=*/false);
2452 SemaRef.FinalizeDeclaration(D: Decl);
2453 SemaRef.CurContext->addHiddenDecl(D: Decl);
2454 return false;
2455}
2456
2457namespace {
2458// An enum to represent whether something is dealing with a call to begin()
2459// or a call to end() in a range-based for loop.
2460enum BeginEndFunction {
2461 BEF_begin,
2462 BEF_end
2463};
2464
2465/// Produce a note indicating which begin/end function was implicitly called
2466/// by a C++11 for-range statement. This is often not obvious from the code,
2467/// nor from the diagnostics produced when analysing the implicit expressions
2468/// required in a for-range statement.
2469void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2470 BeginEndFunction BEF) {
2471 CallExpr *CE = dyn_cast<CallExpr>(Val: E);
2472 if (!CE)
2473 return;
2474 FunctionDecl *D = dyn_cast<FunctionDecl>(Val: CE->getCalleeDecl());
2475 if (!D)
2476 return;
2477 SourceLocation Loc = D->getLocation();
2478
2479 std::string Description;
2480 bool IsTemplate = false;
2481 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2482 Description = SemaRef.getTemplateArgumentBindingsText(
2483 Params: FunTmpl->getTemplateParameters(), Args: *D->getTemplateSpecializationArgs());
2484 IsTemplate = true;
2485 }
2486
2487 SemaRef.Diag(Loc, DiagID: diag::note_for_range_begin_end)
2488 << BEF << IsTemplate << Description << E->getType();
2489}
2490} // namespace
2491
2492/// Build a variable declaration for a for-range statement.
2493VarDecl *Sema::BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
2494 IdentifierInfo *II, bool IsConstexpr) {
2495 // Making the variable constexpr doesn't automatically add 'const' to the
2496 // type, so do that now.
2497 if (IsConstexpr && !Type->isReferenceType())
2498 Type = Type.withConst();
2499
2500 DeclContext *DC = CurContext;
2501 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T: Type, Loc);
2502 VarDecl *Decl =
2503 VarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: II, T: Type, TInfo, S: SC_None);
2504 Decl->setImplicit();
2505 Decl->setCXXForRangeImplicitVar(true);
2506 if (IsConstexpr)
2507 // CWG3044 changed this from 'static constexpr' to 'constexpr'.
2508 Decl->setConstexpr(true);
2509 return Decl;
2510}
2511
2512static bool ObjCEnumerationCollection(Expr *Collection) {
2513 return !Collection->isTypeDependent()
2514 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2515}
2516
2517StmtResult Sema::BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
2518 bool IsConstexpr) {
2519
2520 // Divide by 2, since the variables are in the inner scope (loop body).
2521 const auto DepthStr = std::to_string(val: S->getDepth() / 2);
2522 IdentifierInfo *Name =
2523 PP.getIdentifierInfo(Name: std::string("__range") + DepthStr);
2524 SourceLocation RangeLoc = Range->getBeginLoc();
2525 VarDecl *RangeVar = BuildForRangeVarDecl(Loc: RangeLoc, Type, II: Name, IsConstexpr);
2526 if (FinishForRangeVarDecl(SemaRef&: *this, Decl: RangeVar, Init: Range, Loc: RangeLoc,
2527 DiagID: diag::err_for_range_deduction_failure))
2528
2529 return StmtError();
2530
2531 // Claim the type doesn't contain auto: we've already done the checking.
2532 DeclGroupPtrTy RangeGroup =
2533 BuildDeclaratorGroup(Group: MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2534 return ActOnDeclStmt(dg: RangeGroup, StartLoc: RangeLoc, EndLoc: RangeLoc);
2535}
2536
2537StmtResult Sema::ActOnCXXForRangeStmt(
2538 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2539 Stmt *First, SourceLocation ColonLoc, Expr *Range, SourceLocation RParenLoc,
2540 BuildForRangeKind Kind,
2541 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2542 // FIXME: recover in order to allow the body to be parsed.
2543 if (!First)
2544 return StmtError();
2545
2546 if (Range && ObjCEnumerationCollection(Collection: Range)) {
2547 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2548 if (InitStmt)
2549 return Diag(Loc: InitStmt->getBeginLoc(), DiagID: diag::err_objc_for_range_init_stmt)
2550 << InitStmt->getSourceRange();
2551 return ObjC().ActOnObjCForCollectionStmt(ForColLoc: ForLoc, First, collection: Range, RParenLoc);
2552 }
2553
2554 DeclStmt *DS = dyn_cast<DeclStmt>(Val: First);
2555 assert(DS && "first part of for range not a decl stmt");
2556
2557 if (!DS->isSingleDecl()) {
2558 Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_type_defined_in_for_range);
2559 return StmtError();
2560 }
2561
2562 // This function is responsible for attaching an initializer to LoopVar. We
2563 // must call ActOnInitializerError if we fail to do so.
2564 Decl *LoopVar = DS->getSingleDecl();
2565 if (LoopVar->isInvalidDecl() || !Range ||
2566 DiagnoseUnexpandedParameterPack(E: Range, UPPC: UPPC_Expression)) {
2567 ActOnInitializerError(Dcl: LoopVar);
2568 return StmtError();
2569 }
2570
2571 // Build the coroutine state immediately and not later during template
2572 // instantiation
2573 if (!CoawaitLoc.isInvalid()) {
2574 if (!ActOnCoroutineBodyStart(S, KwLoc: CoawaitLoc, Keyword: "co_await")) {
2575 ActOnInitializerError(Dcl: LoopVar);
2576 return StmtError();
2577 }
2578 }
2579
2580 // Build auto && __range = range-init
2581 auto RangeDecl =
2582 BuildCXXForRangeRangeVar(S, Range, Type: Context.getAutoRRefDeductType());
2583 if (RangeDecl.isInvalid()) {
2584 ActOnInitializerError(Dcl: LoopVar);
2585 return StmtError();
2586 }
2587
2588 StmtResult R = BuildCXXForRangeStmt(
2589 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl: RangeDecl.get(),
2590 /*BeginStmt=*/Begin: nullptr, /*EndStmt=*/End: nullptr,
2591 /*Cond=*/nullptr, /*Inc=*/nullptr, LoopVarDecl: DS, RParenLoc, Kind,
2592 LifetimeExtendTemps);
2593 if (R.isInvalid()) {
2594 ActOnInitializerError(Dcl: LoopVar);
2595 return StmtError();
2596 }
2597
2598 return R;
2599}
2600
2601/// Create the initialization, compare, and increment steps for
2602/// the range-based for loop expression.
2603/// This function does not handle array-based for loops,
2604/// which are created in Sema::BuildCXXForRangeStmt.
2605///
2606/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2607/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2608/// CandidateSet and BEF are set and some non-success value is returned on
2609/// failure.
2610static Sema::ForRangeStatus
2611BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2612 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2613 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2614 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2615 ExprResult *EndExpr, BeginEndFunction *BEF) {
2616 DeclarationNameInfo BeginNameInfo(
2617 &SemaRef.PP.getIdentifierTable().get(Name: "begin"), ColonLoc);
2618 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get(Name: "end"),
2619 ColonLoc);
2620
2621 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2622 Sema::LookupMemberName);
2623 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2624
2625 auto BuildBegin = [&] {
2626 *BEF = BEF_begin;
2627 Sema::ForRangeStatus RangeStatus =
2628 SemaRef.BuildForRangeBeginEndCall(Loc: ColonLoc, RangeLoc: ColonLoc, NameInfo: BeginNameInfo,
2629 MemberLookup&: BeginMemberLookup, CandidateSet,
2630 Range: BeginRange, CallExpr: BeginExpr);
2631
2632 if (RangeStatus != Sema::FRS_Success) {
2633 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2634 SemaRef.Diag(Loc: BeginRange->getBeginLoc(), DiagID: diag::note_in_for_range)
2635 << ColonLoc << BEF_begin << BeginRange->getType();
2636 return RangeStatus;
2637 }
2638 if (!CoawaitLoc.isInvalid()) {
2639 // FIXME: getCurScope() should not be used during template instantiation.
2640 // We should pick up the set of unqualified lookup results for operator
2641 // co_await during the initial parse.
2642 *BeginExpr = SemaRef.ActOnCoawaitExpr(S: SemaRef.getCurScope(), KwLoc: ColonLoc,
2643 E: BeginExpr->get());
2644 if (BeginExpr->isInvalid())
2645 return Sema::FRS_DiagnosticIssued;
2646 }
2647 if (FinishForRangeVarDecl(SemaRef, Decl: BeginVar, Init: BeginExpr->get(), Loc: ColonLoc,
2648 DiagID: diag::err_for_range_iter_deduction_failure)) {
2649 NoteForRangeBeginEndFunction(SemaRef, E: BeginExpr->get(), BEF: *BEF);
2650 return Sema::FRS_DiagnosticIssued;
2651 }
2652 return Sema::FRS_Success;
2653 };
2654
2655 auto BuildEnd = [&] {
2656 *BEF = BEF_end;
2657 Sema::ForRangeStatus RangeStatus =
2658 SemaRef.BuildForRangeBeginEndCall(Loc: ColonLoc, RangeLoc: ColonLoc, NameInfo: EndNameInfo,
2659 MemberLookup&: EndMemberLookup, CandidateSet,
2660 Range: EndRange, CallExpr: EndExpr);
2661 if (RangeStatus != Sema::FRS_Success) {
2662 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2663 SemaRef.Diag(Loc: EndRange->getBeginLoc(), DiagID: diag::note_in_for_range)
2664 << ColonLoc << BEF_end << EndRange->getType();
2665 return RangeStatus;
2666 }
2667 if (FinishForRangeVarDecl(SemaRef, Decl: EndVar, Init: EndExpr->get(), Loc: ColonLoc,
2668 DiagID: diag::err_for_range_iter_deduction_failure)) {
2669 NoteForRangeBeginEndFunction(SemaRef, E: EndExpr->get(), BEF: *BEF);
2670 return Sema::FRS_DiagnosticIssued;
2671 }
2672 return Sema::FRS_Success;
2673 };
2674
2675 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2676 // - if _RangeT is a class type, the unqualified-ids begin and end are
2677 // looked up in the scope of class _RangeT as if by class member access
2678 // lookup (3.4.5), and if either (or both) finds at least one
2679 // declaration, begin-expr and end-expr are __range.begin() and
2680 // __range.end(), respectively;
2681 SemaRef.LookupQualifiedName(R&: BeginMemberLookup, LookupCtx: D);
2682 if (BeginMemberLookup.isAmbiguous())
2683 return Sema::FRS_DiagnosticIssued;
2684
2685 SemaRef.LookupQualifiedName(R&: EndMemberLookup, LookupCtx: D);
2686 if (EndMemberLookup.isAmbiguous())
2687 return Sema::FRS_DiagnosticIssued;
2688
2689 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2690 // Look up the non-member form of the member we didn't find, first.
2691 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2692 // a 'begin' but ignored it because there was no member 'end'"
2693 // diagnostic.
2694 auto BuildNonmember = [&](
2695 BeginEndFunction BEFFound, LookupResult &Found,
2696 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2697 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2698 LookupResult OldFound = std::move(Found);
2699 Found.clear();
2700
2701 if (Sema::ForRangeStatus Result = BuildNotFound())
2702 return Result;
2703
2704 switch (BuildFound()) {
2705 case Sema::FRS_Success:
2706 return Sema::FRS_Success;
2707
2708 case Sema::FRS_NoViableFunction:
2709 CandidateSet->NoteCandidates(
2710 PA: PartialDiagnosticAt(BeginRange->getBeginLoc(),
2711 SemaRef.PDiag(DiagID: diag::err_for_range_invalid)
2712 << BeginRange->getType() << BEFFound),
2713 S&: SemaRef, OCD: OCD_AllCandidates, Args: BeginRange);
2714 [[fallthrough]];
2715
2716 case Sema::FRS_DiagnosticIssued:
2717 for (NamedDecl *D : OldFound) {
2718 SemaRef.Diag(Loc: D->getLocation(),
2719 DiagID: diag::note_for_range_member_begin_end_ignored)
2720 << BeginRange->getType() << BEFFound;
2721 }
2722 return Sema::FRS_DiagnosticIssued;
2723 }
2724 llvm_unreachable("unexpected ForRangeStatus");
2725 };
2726 if (BeginMemberLookup.empty())
2727 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2728 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2729 }
2730 } else {
2731 // - otherwise, begin-expr and end-expr are begin(__range) and
2732 // end(__range), respectively, where begin and end are looked up with
2733 // argument-dependent lookup (3.4.2). For the purposes of this name
2734 // lookup, namespace std is an associated namespace.
2735 }
2736
2737 if (Sema::ForRangeStatus Result = BuildBegin())
2738 return Result;
2739 return BuildEnd();
2740}
2741
2742/// Speculatively attempt to dereference an invalid range expression.
2743/// If the attempt fails, this function will return a valid, null StmtResult
2744/// and emit no diagnostics.
2745static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2746 SourceLocation ForLoc,
2747 SourceLocation CoawaitLoc,
2748 Stmt *InitStmt,
2749 Stmt *LoopVarDecl,
2750 SourceLocation ColonLoc,
2751 Expr *Range,
2752 SourceLocation RangeLoc,
2753 SourceLocation RParenLoc) {
2754 // Determine whether we can rebuild the for-range statement with a
2755 // dereferenced range expression.
2756 ExprResult AdjustedRange;
2757 {
2758 Sema::SFINAETrap Trap(SemaRef);
2759
2760 AdjustedRange = SemaRef.BuildUnaryOp(S, OpLoc: RangeLoc, Opc: UO_Deref, Input: Range);
2761 if (AdjustedRange.isInvalid())
2762 return StmtResult();
2763
2764 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2765 S, ForLoc, CoawaitLoc, InitStmt, First: LoopVarDecl, ColonLoc,
2766 Range: AdjustedRange.get(), RParenLoc, Kind: Sema::BFRK_Check);
2767 if (SR.isInvalid())
2768 return StmtResult();
2769 }
2770
2771 // The attempt to dereference worked well enough that it could produce a valid
2772 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2773 // case there are any other (non-fatal) problems with it.
2774 SemaRef.Diag(Loc: RangeLoc, DiagID: diag::err_for_range_dereference)
2775 << Range->getType() << FixItHint::CreateInsertion(InsertionLoc: RangeLoc, Code: "*");
2776 return SemaRef.ActOnCXXForRangeStmt(
2777 S, ForLoc, CoawaitLoc, InitStmt, First: LoopVarDecl, ColonLoc,
2778 Range: AdjustedRange.get(), RParenLoc, Kind: Sema::BFRK_Rebuild);
2779}
2780
2781void Sema::ApplyForRangeOrExpansionStatementLifetimeExtension(
2782 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries) {
2783 if (Temporaries.empty())
2784 return;
2785
2786 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: RangeVar);
2787 for (auto *MTE : Temporaries)
2788 MTE->setExtendingDecl(ExtendedBy: RangeVar, ManglingNumber: Entity.allocateManglingNumber());
2789}
2790
2791Sema::ForRangeBeginEndInfo Sema::BuildCXXForRangeBeginEndVars(
2792 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
2793 SourceLocation CoawaitLoc,
2794 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
2795 BuildForRangeKind Kind, bool IsConstexpr, StmtResult *RebuildResult,
2796 llvm::function_ref<StmtResult()> RebuildWithDereference,
2797 IdentifierInfo *BeginName, IdentifierInfo *EndName) {
2798 QualType RangeVarType = RangeVar->getType();
2799 SourceLocation RangeLoc = RangeVar->getLocation();
2800 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2801
2802 ExprResult BeginRangeRef =
2803 BuildDeclRefExpr(D: RangeVar, Ty: RangeVarNonRefType, VK: VK_LValue, Loc: ColonLoc);
2804 if (BeginRangeRef.isInvalid())
2805 return {};
2806
2807 ExprResult EndRangeRef =
2808 BuildDeclRefExpr(D: RangeVar, Ty: RangeVarNonRefType, VK: VK_LValue, Loc: ColonLoc);
2809 if (EndRangeRef.isInvalid())
2810 return {};
2811
2812 QualType AutoType = Context.getAutoDeductType();
2813 Expr *Range = RangeVar->getInit();
2814 if (!Range)
2815 return {};
2816 QualType RangeType = Range->getType();
2817
2818 if (RequireCompleteType(Loc: RangeLoc, T: RangeType,
2819 DiagID: diag::err_for_range_incomplete_type))
2820 return {};
2821
2822 // Build auto __begin = begin-expr, __end = end-expr.
2823 // Divide by 2, since the variables are in the inner scope (loop body).
2824 const auto DepthStr = std::to_string(val: S->getDepth() / 2);
2825 if (!BeginName)
2826 BeginName = PP.getIdentifierInfo(Name: std::string("__begin") + DepthStr);
2827 if (!EndName)
2828 EndName = PP.getIdentifierInfo(Name: std::string("__end") + DepthStr);
2829 VarDecl *BeginVar =
2830 BuildForRangeVarDecl(Loc: ColonLoc, Type: AutoType, II: BeginName, IsConstexpr);
2831 VarDecl *EndVar =
2832 BuildForRangeVarDecl(Loc: ColonLoc, Type: AutoType, II: EndName, IsConstexpr);
2833
2834 // Build begin-expr and end-expr and attach to __begin and __end variables.
2835 ExprResult BeginExpr, EndExpr;
2836 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2837 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2838 // __range + __bound, respectively, where __bound is the array bound. If
2839 // _RangeT is an array of unknown size or an array of incomplete type,
2840 // the program is ill-formed;
2841
2842 // begin-expr is __range.
2843 BeginExpr = BeginRangeRef;
2844 if (!CoawaitLoc.isInvalid()) {
2845 BeginExpr = ActOnCoawaitExpr(S, KwLoc: ColonLoc, E: BeginExpr.get());
2846 if (BeginExpr.isInvalid())
2847 return {};
2848 }
2849 if (FinishForRangeVarDecl(SemaRef&: *this, Decl: BeginVar, Init: BeginRangeRef.get(), Loc: ColonLoc,
2850 DiagID: diag::err_for_range_iter_deduction_failure)) {
2851 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr.get(), BEF: BEF_begin);
2852 return {};
2853 }
2854
2855 // Find the array bound.
2856 ExprResult BoundExpr;
2857 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: UnqAT))
2858 BoundExpr = IntegerLiteral::Create(
2859 C: Context, V: CAT->getSize(), type: Context.getPointerDiffType(), l: RangeLoc);
2860 else if (const VariableArrayType *VAT =
2861 dyn_cast<VariableArrayType>(Val: UnqAT)) {
2862 // For a variably modified type we can't just use the expression within
2863 // the array bounds, since we don't want that to be re-evaluated here.
2864 // Rather, we need to determine what it was when the array was first
2865 // created - so we resort to using sizeof(vla)/sizeof(element).
2866 // For e.g.
2867 // void f(int b) {
2868 // int vla[b];
2869 // b = -1; <-- This should not affect the num of iterations below
2870 // for (int &c : vla) { .. }
2871 // }
2872
2873 // FIXME: This results in codegen generating IR that recalculates the
2874 // run-time number of elements (as opposed to just using the IR Value
2875 // that corresponds to the run-time value of each bound that was
2876 // generated when the array was created.) If this proves too embarrassing
2877 // even for unoptimized IR, consider passing a magic-value/cookie to
2878 // codegen that then knows to simply use that initial llvm::Value (that
2879 // corresponds to the bound at time of array creation) within
2880 // getelementptr. But be prepared to pay the price of increasing a
2881 // customized form of coupling between the two components - which could
2882 // be hard to maintain as the codebase evolves.
2883
2884 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2885 OpLoc: EndVar->getLocation(), ExprKind: UETT_SizeOf,
2886 /*IsType=*/true,
2887 TyOrEx: CreateParsedType(T: VAT->desugar(), TInfo: Context.getTrivialTypeSourceInfo(
2888 T: VAT->desugar(), Loc: RangeLoc))
2889 .getAsOpaquePtr(),
2890 ArgRange: EndVar->getSourceRange());
2891 if (SizeOfVLAExprR.isInvalid())
2892 return {};
2893
2894 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2895 OpLoc: EndVar->getLocation(), ExprKind: UETT_SizeOf,
2896 /*IsType=*/true,
2897 TyOrEx: CreateParsedType(T: VAT->desugar(), TInfo: Context.getTrivialTypeSourceInfo(
2898 T: VAT->getElementType(), Loc: RangeLoc))
2899 .getAsOpaquePtr(),
2900 ArgRange: EndVar->getSourceRange());
2901 if (SizeOfEachElementExprR.isInvalid())
2902 return {};
2903
2904 BoundExpr =
2905 ActOnBinOp(S, TokLoc: EndVar->getLocation(), Kind: tok::slash, LHSExpr: SizeOfVLAExprR.get(),
2906 RHSExpr: SizeOfEachElementExprR.get());
2907 if (BoundExpr.isInvalid())
2908 return {};
2909
2910 } else {
2911 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2912 // UnqAT is not incomplete and Range is not type-dependent.
2913 llvm_unreachable("Unexpected array type in for-range");
2914 }
2915
2916 // end-expr is __range + __bound.
2917 EndExpr =
2918 ActOnBinOp(S, TokLoc: ColonLoc, Kind: tok::plus, LHSExpr: EndRangeRef.get(), RHSExpr: BoundExpr.get());
2919 if (EndExpr.isInvalid())
2920 return {};
2921 if (FinishForRangeVarDecl(SemaRef&: *this, Decl: EndVar, Init: EndExpr.get(), Loc: ColonLoc,
2922 DiagID: diag::err_for_range_iter_deduction_failure)) {
2923 NoteForRangeBeginEndFunction(SemaRef&: *this, E: EndExpr.get(), BEF: BEF_end);
2924 return {};
2925 }
2926 } else {
2927 OverloadCandidateSet CandidateSet(RangeLoc,
2928 OverloadCandidateSet::CSK_Normal);
2929 BeginEndFunction BEFFailure;
2930 ForRangeStatus RangeStatus =
2931 BuildNonArrayForRange(SemaRef&: *this, BeginRange: BeginRangeRef.get(), EndRange: EndRangeRef.get(),
2932 RangeType, BeginVar, EndVar, ColonLoc, CoawaitLoc,
2933 CandidateSet: &CandidateSet, BeginExpr: &BeginExpr, EndExpr: &EndExpr, BEF: &BEFFailure);
2934
2935 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2936 BEFFailure == BEF_begin) {
2937 // If the range is being built from an array parameter, emit a
2938 // a diagnostic that it is being treated as a pointer.
2939 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Range)) {
2940 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) {
2941 QualType ArrayTy = PVD->getOriginalType();
2942 QualType PointerTy = PVD->getType();
2943 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2944 Diag(Loc: Range->getBeginLoc(), DiagID: diag::err_range_on_array_parameter)
2945 << RangeLoc << PVD << ArrayTy << PointerTy;
2946 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
2947 return {};
2948 }
2949 }
2950 }
2951
2952 // If building the range failed, try dereferencing the range expression
2953 // unless a diagnostic was issued or the end function is problematic.
2954 if (RebuildWithDereference) {
2955 assert(RebuildResult);
2956 StmtResult SR = RebuildWithDereference();
2957 if (SR.isInvalid() || SR.isUsable()) {
2958 *RebuildResult = SR;
2959 return {};
2960 }
2961 }
2962 }
2963
2964 // Otherwise, emit diagnostics if we haven't already.
2965 if (RangeStatus == FRS_NoViableFunction) {
2966 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2967 CandidateSet.NoteCandidates(
2968 PA: PartialDiagnosticAt(Range->getBeginLoc(),
2969 PDiag(DiagID: diag::err_for_range_invalid)
2970 << RangeLoc << Range->getType()
2971 << BEFFailure),
2972 S&: *this, OCD: OCD_AllCandidates, Args: Range);
2973 }
2974 // Return an error if no fix was discovered.
2975 if (RangeStatus != FRS_Success)
2976 return {};
2977 }
2978
2979 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2980 "invalid range expression in for loop");
2981
2982 return {.BeginVar: BeginVar, .EndVar: EndVar, .BeginExpr: BeginExpr.get(), .EndExpr: EndExpr.get()};
2983}
2984
2985void Sema::ActOnDependentForRangeInitializer(VarDecl *LoopVar,
2986 BuildForRangeKind BFRK) {
2987 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2988 // them in properly when we instantiate the loop.
2989 if (!LoopVar->isInvalidDecl() && BFRK != BFRK_Check) {
2990 if (auto *DD = dyn_cast<DecompositionDecl>(Val: LoopVar))
2991 for (auto *Binding : DD->bindings()) {
2992 if (!Binding->isParameterPack())
2993 Binding->setType(Context.DependentTy);
2994 }
2995 LoopVar->setType(SubstAutoTypeDependent(TypeWithAuto: LoopVar->getType()));
2996 }
2997}
2998
2999StmtResult Sema::BuildCXXForRangeStmt(
3000 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
3001 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3002 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
3003 BuildForRangeKind Kind,
3004 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
3005 // FIXME: This should not be used during template instantiation. We should
3006 // pick up the set of unqualified lookup results for the != and + operators
3007 // in the initial parse.
3008 //
3009 // Testcase (accepts-invalid):
3010 // template<typename T> void f() { for (auto x : T()) {} }
3011 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
3012 // bool operator!=(N::X, N::X); void operator++(N::X);
3013 // void g() { f<N::X>(); }
3014 Scope *S = getCurScope();
3015
3016 DeclStmt *RangeDS = cast<DeclStmt>(Val: RangeDecl);
3017 VarDecl *RangeVar = cast<VarDecl>(Val: RangeDS->getSingleDecl());
3018 QualType RangeVarType = RangeVar->getType();
3019
3020 DeclStmt *LoopVarDS = cast<DeclStmt>(Val: LoopVarDecl);
3021 VarDecl *LoopVar = cast<VarDecl>(Val: LoopVarDS->getSingleDecl());
3022
3023 StmtResult BeginDeclStmt = Begin;
3024 StmtResult EndDeclStmt = End;
3025 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
3026
3027 if (RangeVarType->isDependentType()) {
3028 // The range is implicitly used as a placeholder when it is dependent.
3029 RangeVar->markUsed(C&: Context);
3030 ActOnDependentForRangeInitializer(LoopVar, BFRK: Kind);
3031 } else if (!BeginDeclStmt.get()) {
3032 StmtResult RebuildResult;
3033 auto RebuildWithDereference = [&] {
3034 return RebuildForRangeWithDereference(
3035 SemaRef&: *this, S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
3036 Range: RangeVar->getInit(), RangeLoc: RangeVar->getLocation(), RParenLoc);
3037 };
3038
3039 ForRangeBeginEndInfo ForRangeInfo = BuildCXXForRangeBeginEndVars(
3040 S, RangeVar, ColonLoc, CoawaitLoc, LifetimeExtendTemps, Kind,
3041 /*Constexpr=*/IsConstexpr: false, RebuildResult: &RebuildResult, RebuildWithDereference);
3042
3043 if (!RebuildResult.isUnset())
3044 return RebuildResult;
3045 if (!ForRangeInfo.isValid())
3046 return StmtError();
3047
3048 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
3049 // C++1z removes this restriction.
3050 auto [BeginVar, EndVar, BeginExpr, EndExpr] = ForRangeInfo;
3051 SourceLocation RangeLoc = RangeVar->getLocation();
3052 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
3053 if (!Context.hasSameType(T1: BeginType, T2: EndType)) {
3054 DiagCompat(Loc: RangeLoc, CompatDiagId: diag_compat::for_range_begin_end_types_differ)
3055 << BeginType << EndType;
3056 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr, BEF: BEF_begin);
3057 NoteForRangeBeginEndFunction(SemaRef&: *this, E: EndExpr, BEF: BEF_end);
3058 }
3059
3060 BeginDeclStmt =
3061 ActOnDeclStmt(dg: ConvertDeclToDeclGroup(Ptr: BeginVar), StartLoc: ColonLoc, EndLoc: ColonLoc);
3062 EndDeclStmt =
3063 ActOnDeclStmt(dg: ConvertDeclToDeclGroup(Ptr: EndVar), StartLoc: ColonLoc, EndLoc: ColonLoc);
3064
3065 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
3066 ExprResult BeginRef = BuildDeclRefExpr(D: BeginVar, Ty: BeginRefNonRefType,
3067 VK: VK_LValue, Loc: ColonLoc);
3068 if (BeginRef.isInvalid())
3069 return StmtError();
3070
3071 ExprResult EndRef = BuildDeclRefExpr(D: EndVar, Ty: EndType.getNonReferenceType(),
3072 VK: VK_LValue, Loc: ColonLoc);
3073 if (EndRef.isInvalid())
3074 return StmtError();
3075
3076 // Build and check __begin != __end expression.
3077 NotEqExpr = ActOnBinOp(S, TokLoc: ColonLoc, Kind: tok::exclaimequal,
3078 LHSExpr: BeginRef.get(), RHSExpr: EndRef.get());
3079 if (!NotEqExpr.isInvalid())
3080 NotEqExpr = CheckBooleanCondition(Loc: ColonLoc, E: NotEqExpr.get());
3081 if (!NotEqExpr.isInvalid())
3082 NotEqExpr =
3083 ActOnFinishFullExpr(Expr: NotEqExpr.get(), /*DiscardedValue*/ false);
3084 if (NotEqExpr.isInvalid()) {
3085 Diag(Loc: RangeLoc, DiagID: diag::note_for_range_invalid_iterator)
3086 << RangeLoc << diag::InvalidRangeForIterator::OpNotEq
3087 << BeginRef.get()->getType();
3088 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr, BEF: BEF_begin);
3089 if (!Context.hasSameType(T1: BeginType, T2: EndType))
3090 NoteForRangeBeginEndFunction(SemaRef&: *this, E: EndExpr, BEF: BEF_end);
3091 return StmtError();
3092 }
3093
3094 // Build and check ++__begin expression.
3095 BeginRef = BuildDeclRefExpr(D: BeginVar, Ty: BeginRefNonRefType,
3096 VK: VK_LValue, Loc: ColonLoc);
3097 if (BeginRef.isInvalid())
3098 return StmtError();
3099
3100 IncrExpr = ActOnUnaryOp(S, OpLoc: ColonLoc, Op: tok::plusplus, Input: BeginRef.get());
3101 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
3102 // FIXME: getCurScope() should not be used during template instantiation.
3103 // We should pick up the set of unqualified lookup results for operator
3104 // co_await during the initial parse.
3105 IncrExpr = ActOnCoawaitExpr(S, KwLoc: CoawaitLoc, E: IncrExpr.get());
3106 if (!IncrExpr.isInvalid())
3107 IncrExpr = ActOnFinishFullExpr(Expr: IncrExpr.get(), /*DiscardedValue*/ false);
3108 if (IncrExpr.isInvalid()) {
3109 Diag(Loc: RangeLoc, DiagID: diag::note_for_range_invalid_iterator)
3110 << RangeLoc << diag::InvalidRangeForIterator::OpAdvance
3111 << BeginRef.get()->getType();
3112 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr, BEF: BEF_begin);
3113 return StmtError();
3114 }
3115
3116 // Build and check *__begin expression.
3117 BeginRef = BuildDeclRefExpr(D: BeginVar, Ty: BeginRefNonRefType,
3118 VK: VK_LValue, Loc: ColonLoc);
3119 if (BeginRef.isInvalid())
3120 return StmtError();
3121
3122 ExprResult DerefExpr = ActOnUnaryOp(S, OpLoc: ColonLoc, Op: tok::star, Input: BeginRef.get());
3123 if (DerefExpr.isInvalid()) {
3124 Diag(Loc: RangeLoc, DiagID: diag::note_for_range_invalid_iterator)
3125 << RangeLoc << diag::InvalidRangeForIterator::OpDeref
3126 << BeginRef.get()->getType();
3127 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr, BEF: BEF_begin);
3128 return StmtError();
3129 }
3130
3131 // Attach *__begin as initializer for VD. Don't touch it if we're just
3132 // trying to determine whether this would be a valid range.
3133 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
3134 AddInitializerToDecl(dcl: LoopVar, init: DerefExpr.get(), /*DirectInit=*/false);
3135 if (LoopVar->isInvalidDecl() ||
3136 (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
3137 NoteForRangeBeginEndFunction(SemaRef&: *this, E: BeginExpr, BEF: BEF_begin);
3138 }
3139 }
3140
3141 // Don't bother to actually allocate the result if we're just trying to
3142 // determine whether it would be valid.
3143 if (Kind == BFRK_Check)
3144 return StmtResult();
3145
3146 // In OpenMP loop region loop control variable must be private. Perform
3147 // analysis of first part (if any).
3148 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
3149 OpenMP().ActOnOpenMPLoopInitialization(ForLoc, Init: BeginDeclStmt.get());
3150
3151 // P2718R0 - Lifetime extension in range-based for loops.
3152 if (getLangOpts().CPlusPlus23)
3153 ApplyForRangeOrExpansionStatementLifetimeExtension(RangeVar,
3154 Temporaries: LifetimeExtendTemps);
3155
3156 return new (Context) CXXForRangeStmt(
3157 InitStmt, RangeDS, cast_or_null<DeclStmt>(Val: BeginDeclStmt.get()),
3158 cast_or_null<DeclStmt>(Val: EndDeclStmt.get()), NotEqExpr.get(),
3159 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
3160 ColonLoc, RParenLoc);
3161}
3162
3163// Warn when the loop variable is a const reference that creates a copy.
3164// Suggest using the non-reference type for copies. If a copy can be prevented
3165// suggest the const reference type that would do so.
3166// For instance, given "for (const &Foo : Range)", suggest
3167// "for (const Foo : Range)" to denote a copy is made for the loop. If
3168// possible, also suggest "for (const &Bar : Range)" if this type prevents
3169// the copy altogether.
3170static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
3171 const VarDecl *VD,
3172 QualType RangeInitType) {
3173 const Expr *InitExpr = VD->getInit();
3174 if (!InitExpr)
3175 return;
3176
3177 QualType VariableType = VD->getType();
3178
3179 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Val: InitExpr))
3180 if (!Cleanups->cleanupsHaveSideEffects())
3181 InitExpr = Cleanups->getSubExpr();
3182
3183 const MaterializeTemporaryExpr *MTE =
3184 dyn_cast<MaterializeTemporaryExpr>(Val: InitExpr);
3185
3186 // No copy made.
3187 if (!MTE)
3188 return;
3189
3190 const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
3191
3192 // Searching for either UnaryOperator for dereference of a pointer or
3193 // CXXOperatorCallExpr for handling iterators.
3194 while (!isa<CXXOperatorCallExpr>(Val: E) && !isa<UnaryOperator>(Val: E)) {
3195 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: E)) {
3196 E = CCE->getArg(Arg: 0);
3197 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(Val: E)) {
3198 const MemberExpr *ME = cast<MemberExpr>(Val: Call->getCallee());
3199 E = ME->getBase();
3200 } else {
3201 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(Val: E);
3202 E = MTE->getSubExpr();
3203 }
3204 E = E->IgnoreImpCasts();
3205 }
3206
3207 QualType ReferenceReturnType;
3208 if (isa<UnaryOperator>(Val: E)) {
3209 ReferenceReturnType = SemaRef.Context.getLValueReferenceType(T: E->getType());
3210 } else {
3211 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(Val: E);
3212 const FunctionDecl *FD = Call->getDirectCallee();
3213 QualType ReturnType = FD->getReturnType();
3214 if (ReturnType->isReferenceType())
3215 ReferenceReturnType = ReturnType;
3216 }
3217
3218 if (!ReferenceReturnType.isNull()) {
3219 // Loop variable creates a temporary. Suggest either to go with
3220 // non-reference loop variable to indicate a copy is made, or
3221 // the correct type to bind a const reference.
3222 SemaRef.Diag(Loc: VD->getLocation(),
3223 DiagID: diag::warn_for_range_const_ref_binds_temp_built_from_ref)
3224 << VD << VariableType << ReferenceReturnType;
3225 QualType NonReferenceType = VariableType.getNonReferenceType();
3226 NonReferenceType.removeLocalConst();
3227 QualType NewReferenceType =
3228 SemaRef.Context.getLValueReferenceType(T: E->getType().withConst());
3229 SemaRef.Diag(Loc: VD->getBeginLoc(), DiagID: diag::note_use_type_or_non_reference)
3230 << NonReferenceType << NewReferenceType << VD->getSourceRange()
3231 << FixItHint::CreateRemoval(RemoveRange: VD->getTypeSpecEndLoc());
3232 } else if (!VariableType->isRValueReferenceType()) {
3233 // The range always returns a copy, so a temporary is always created.
3234 // Suggest removing the reference from the loop variable.
3235 // If the type is a rvalue reference do not warn since that changes the
3236 // semantic of the code.
3237 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::warn_for_range_ref_binds_ret_temp)
3238 << VD << RangeInitType;
3239 QualType NonReferenceType = VariableType.getNonReferenceType();
3240 NonReferenceType.removeLocalConst();
3241 SemaRef.Diag(Loc: VD->getBeginLoc(), DiagID: diag::note_use_non_reference_type)
3242 << NonReferenceType << VD->getSourceRange()
3243 << FixItHint::CreateRemoval(RemoveRange: VD->getTypeSpecEndLoc());
3244 }
3245}
3246
3247/// Determines whether the @p VariableType's declaration is a record with the
3248/// clang::trivial_abi attribute.
3249static bool hasTrivialABIAttr(QualType VariableType) {
3250 if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
3251 return RD->hasAttr<TrivialABIAttr>();
3252
3253 return false;
3254}
3255
3256// Warns when the loop variable can be changed to a reference type to
3257// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
3258// "for (const Foo &x : Range)" if this form does not make a copy.
3259static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
3260 const VarDecl *VD) {
3261 const Expr *InitExpr = VD->getInit();
3262 if (!InitExpr)
3263 return;
3264
3265 QualType VariableType = VD->getType();
3266
3267 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Val: InitExpr)) {
3268 if (!CE->getConstructor()->isCopyConstructor())
3269 return;
3270 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Val: InitExpr)) {
3271 if (CE->getCastKind() != CK_LValueToRValue)
3272 return;
3273 } else {
3274 return;
3275 }
3276
3277 // Small trivially copyable types are cheap to copy. Do not emit the
3278 // diagnostic for these instances. 64 bytes is a common size of a cache line.
3279 // (The function `getTypeSize` returns the size in bits.)
3280 ASTContext &Ctx = SemaRef.Context;
3281 if (Ctx.getTypeSize(T: VariableType) <= 64 * 8 &&
3282 (VariableType.isTriviallyCopyConstructibleType(Context: Ctx) ||
3283 hasTrivialABIAttr(VariableType)))
3284 return;
3285
3286 // Suggest changing from a const variable to a const reference variable
3287 // if doing so will prevent a copy.
3288 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::warn_for_range_copy)
3289 << VD << VariableType;
3290 SemaRef.Diag(Loc: VD->getBeginLoc(), DiagID: diag::note_use_reference_type)
3291 << SemaRef.Context.getLValueReferenceType(T: VariableType)
3292 << VD->getSourceRange()
3293 << FixItHint::CreateInsertion(InsertionLoc: VD->getLocation(), Code: "&");
3294}
3295
3296/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3297/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
3298/// using "const foo x" to show that a copy is made
3299/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3300/// Suggest either "const bar x" to keep the copying or "const foo& x" to
3301/// prevent the copy.
3302/// 3) for (const foo x : foos) where x is constructed from a reference foo.
3303/// Suggest "const foo &x" to prevent the copy.
3304static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
3305 const CXXForRangeStmt *ForStmt) {
3306 if (SemaRef.inTemplateInstantiation())
3307 return;
3308
3309 SourceLocation Loc = ForStmt->getBeginLoc();
3310 if (SemaRef.Diags.isIgnored(
3311 DiagID: diag::warn_for_range_const_ref_binds_temp_built_from_ref, Loc) &&
3312 SemaRef.Diags.isIgnored(DiagID: diag::warn_for_range_ref_binds_ret_temp, Loc) &&
3313 SemaRef.Diags.isIgnored(DiagID: diag::warn_for_range_copy, Loc)) {
3314 return;
3315 }
3316
3317 const VarDecl *VD = ForStmt->getLoopVariable();
3318 if (!VD)
3319 return;
3320
3321 QualType VariableType = VD->getType();
3322
3323 if (VariableType->isIncompleteType())
3324 return;
3325
3326 const Expr *InitExpr = VD->getInit();
3327 if (!InitExpr)
3328 return;
3329
3330 if (InitExpr->getExprLoc().isMacroID())
3331 return;
3332
3333 if (VariableType->isReferenceType()) {
3334 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
3335 RangeInitType: ForStmt->getRangeInit()->getType());
3336 } else if (VariableType.isConstQualified()) {
3337 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
3338 }
3339}
3340
3341StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
3342 if (!S || !B)
3343 return StmtError();
3344
3345 if (isa<ObjCForCollectionStmt>(Val: S))
3346 return ObjC().FinishObjCForCollectionStmt(ForCollection: S, Body: B);
3347
3348 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(Val: S);
3349 ForStmt->setBody(B);
3350
3351 DiagnoseEmptyStmtBody(StmtLoc: ForStmt->getRParenLoc(), Body: B,
3352 DiagID: diag::warn_empty_range_based_for_body);
3353
3354 DiagnoseForRangeVariableCopies(SemaRef&: *this, ForStmt);
3355
3356 return S;
3357}
3358
3359StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
3360 SourceLocation LabelLoc,
3361 LabelDecl *TheDecl) {
3362 setFunctionHasBranchIntoScope();
3363
3364 // If this goto is in a compute construct scope, we need to make sure we check
3365 // gotos in/out.
3366 if (getCurScope()->isInOpenACCComputeConstructScope())
3367 setFunctionHasBranchProtectedScope();
3368
3369 TheDecl->markUsed(C&: Context);
3370 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
3371}
3372
3373StmtResult
3374Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
3375 Expr *E) {
3376 // Convert operand to void*
3377 if (!E->isTypeDependent()) {
3378 QualType ETy = E->getType();
3379 QualType DestTy = Context.getPointerType(T: Context.VoidTy.withConst());
3380 ExprResult ExprRes = E;
3381 AssignConvertType ConvTy =
3382 CheckSingleAssignmentConstraints(LHSType: DestTy, RHS&: ExprRes);
3383 if (ExprRes.isInvalid())
3384 return StmtError();
3385 E = ExprRes.get();
3386 if (DiagnoseAssignmentResult(ConvTy, Loc: StarLoc, DstType: DestTy, SrcType: ETy, SrcExpr: E,
3387 Action: AssignmentAction::Passing))
3388 return StmtError();
3389 }
3390
3391 ExprResult ExprRes = ActOnFinishFullExpr(Expr: E, /*DiscardedValue*/ false);
3392 if (ExprRes.isInvalid())
3393 return StmtError();
3394 E = ExprRes.get();
3395
3396 setFunctionHasIndirectGoto();
3397
3398 // If this goto is in a compute construct scope, we need to make sure we
3399 // check gotos in/out.
3400 if (getCurScope()->isInOpenACCComputeConstructScope())
3401 setFunctionHasBranchProtectedScope();
3402
3403 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
3404}
3405
3406static void CheckJumpOutOfSEHFinallyOrDefer(Sema &S, SourceLocation Loc,
3407 const Scope &DestScope,
3408 unsigned DeferJumpKind) {
3409 if (!S.CurrentSEHFinally.empty() &&
3410 DestScope.Contains(rhs: *S.CurrentSEHFinally.back())) {
3411 S.Diag(Loc, DiagID: diag::warn_jump_out_of_seh_finally);
3412 }
3413
3414 if (!S.CurrentDefer.empty()) {
3415 Scope *Parent = S.CurrentDefer.back().first;
3416 assert(Parent);
3417
3418 // Note: We don't create a new scope for defer statements, so 'Parent'
3419 // is actually the scope that contains the '_Defer'.
3420 if (DestScope.Contains(rhs: *Parent) || &DestScope == Parent)
3421 S.Diag(Loc, DiagID: diag::err_jump_out_of_defer_stmt) << DeferJumpKind;
3422 }
3423}
3424
3425static Scope *FindLabeledBreakContinueScope(Sema &S, Scope *CurScope,
3426 SourceLocation KWLoc,
3427 LabelDecl *Target,
3428 SourceLocation LabelLoc,
3429 bool IsContinue) {
3430 assert(Target && "not a named break/continue?");
3431
3432 Target->markUsed(C&: S.Context);
3433
3434 Scope *Found = nullptr;
3435 for (Scope *Scope = CurScope; Scope; Scope = Scope->getParent()) {
3436 if (Scope->isFunctionScope())
3437 break;
3438
3439 if (Scope->isOpenACCComputeConstructScope()) {
3440 S.Diag(Loc: KWLoc, DiagID: diag::err_acc_branch_in_out_compute_construct)
3441 << /*branch*/ 0 << /*out of*/ 0;
3442 return nullptr;
3443 }
3444
3445 if (Scope->isBreakOrContinueScope() &&
3446 Scope->getPrecedingLabel() == Target) {
3447 Found = Scope;
3448 break;
3449 }
3450 }
3451
3452 if (Found) {
3453 if (IsContinue && !Found->isContinueScope()) {
3454 S.Diag(Loc: LabelLoc, DiagID: diag::err_continue_switch);
3455 return nullptr;
3456 }
3457 return Found;
3458 }
3459
3460 S.Diag(Loc: LabelLoc, DiagID: diag::err_break_continue_label_not_found) << IsContinue;
3461 return nullptr;
3462}
3463
3464StmtResult Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
3465 LabelDecl *Target, SourceLocation LabelLoc) {
3466 Scope *S;
3467 if (Target) {
3468 S = FindLabeledBreakContinueScope(S&: *this, CurScope, KWLoc: ContinueLoc, Target,
3469 LabelLoc,
3470 /*IsContinue=*/true);
3471 if (!S)
3472 return StmtError();
3473 } else {
3474 S = CurScope->getContinueParent();
3475 }
3476
3477 if (!S) {
3478 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3479 return StmtError(Diag(Loc: ContinueLoc, DiagID: diag::err_continue_not_in_loop));
3480 }
3481
3482 // A 'continue' that would normally have execution continue on a block outside
3483 // of a compute construct counts as 'branching out of' the compute construct,
3484 // so diagnose here.
3485 if (S->isOpenACCComputeConstructScope())
3486 return StmtError(
3487 Diag(Loc: ContinueLoc, DiagID: diag::err_acc_branch_in_out_compute_construct)
3488 << /*branch*/ 0 << /*out of */ 0);
3489
3490 CheckJumpOutOfSEHFinallyOrDefer(S&: *this, Loc: ContinueLoc, DestScope: *S,
3491 DeferJumpKind: diag::DeferJumpKind::Continue);
3492
3493 return new (Context) ContinueStmt(ContinueLoc, LabelLoc, Target);
3494}
3495
3496StmtResult Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
3497 LabelDecl *Target, SourceLocation LabelLoc) {
3498 Scope *S;
3499 if (Target) {
3500 S = FindLabeledBreakContinueScope(S&: *this, CurScope, KWLoc: BreakLoc, Target,
3501 LabelLoc,
3502 /*IsContinue=*/false);
3503 if (!S)
3504 return StmtError();
3505 } else {
3506 S = CurScope->getBreakParent();
3507 }
3508
3509 if (!S) {
3510 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3511 return StmtError(Diag(Loc: BreakLoc, DiagID: diag::err_break_not_in_loop_or_switch));
3512 }
3513
3514 if (S->isOpenMPLoopScope())
3515 return StmtError(Diag(Loc: BreakLoc, DiagID: diag::err_omp_loop_cannot_use_stmt)
3516 << "break");
3517
3518 // OpenACC doesn't allow 'break'ing from a compute construct, so diagnose if
3519 // we are trying to do so. This can come in 2 flavors: 1-the break'able thing
3520 // (besides the compute construct) 'contains' the compute construct, at which
3521 // point the 'break' scope will be the compute construct. Else it could be a
3522 // loop of some sort that has a direct parent of the compute construct.
3523 // However, a 'break' in a 'switch' marked as a compute construct doesn't
3524 // count as 'branch out of' the compute construct.
3525 if (S->isOpenACCComputeConstructScope() ||
3526 (S->isLoopScope() && S->getParent() &&
3527 S->getParent()->isOpenACCComputeConstructScope()))
3528 return StmtError(
3529 Diag(Loc: BreakLoc, DiagID: diag::err_acc_branch_in_out_compute_construct)
3530 << /*branch*/ 0 << /*out of */ 0);
3531
3532 CheckJumpOutOfSEHFinallyOrDefer(S&: *this, Loc: BreakLoc, DestScope: *S,
3533 DeferJumpKind: diag::DeferJumpKind::Break);
3534
3535 return new (Context) BreakStmt(BreakLoc, LabelLoc, Target);
3536}
3537
3538Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *&E,
3539 SimplerImplicitMoveMode Mode) {
3540 if (!E)
3541 return NamedReturnInfo();
3542 // - in a return statement in a function [where] ...
3543 // ... the expression is the name of a non-volatile automatic object ...
3544 const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens());
3545 if (!DR || DR->refersToEnclosingVariableOrCapture())
3546 return NamedReturnInfo();
3547 const auto *VD = dyn_cast<VarDecl>(Val: DR->getDecl());
3548 if (!VD)
3549 return NamedReturnInfo();
3550 if (VD->getInit() && VD->getInit()->containsErrors())
3551 return NamedReturnInfo();
3552 NamedReturnInfo Res = getNamedReturnInfo(VD);
3553 if (Res.Candidate && !E->isXValue() &&
3554 (Mode == SimplerImplicitMoveMode::ForceOn ||
3555 (Mode != SimplerImplicitMoveMode::ForceOff &&
3556 getLangOpts().CPlusPlus23))) {
3557 E = ImplicitCastExpr::Create(Context, T: VD->getType().getNonReferenceType(),
3558 Kind: CK_NoOp, Operand: E, BasePath: nullptr, Cat: VK_XValue,
3559 FPO: FPOptionsOverride());
3560 }
3561 return Res;
3562}
3563
3564Sema::NamedReturnInfo Sema::getNamedReturnInfo(const VarDecl *VD) {
3565 NamedReturnInfo Info{.Candidate: VD, .S: NamedReturnInfo::MoveEligibleAndCopyElidable};
3566
3567 // C++20 [class.copy.elision]p3:
3568 // - in a return statement in a function with ...
3569 // (other than a function ... parameter)
3570 if (VD->getKind() == Decl::ParmVar)
3571 Info.S = NamedReturnInfo::MoveEligible;
3572 else if (VD->getKind() != Decl::Var)
3573 return NamedReturnInfo();
3574
3575 // (other than ... a catch-clause parameter)
3576 if (VD->isExceptionVariable())
3577 Info.S = NamedReturnInfo::MoveEligible;
3578
3579 // ...automatic...
3580 if (!VD->hasLocalStorage())
3581 return NamedReturnInfo();
3582
3583 // We don't want to implicitly move out of a __block variable during a return
3584 // because we cannot assume the variable will no longer be used.
3585 if (VD->hasAttr<BlocksAttr>())
3586 return NamedReturnInfo();
3587
3588 QualType VDType = VD->getType();
3589 if (VDType->isObjectType()) {
3590 // C++17 [class.copy.elision]p3:
3591 // ...non-volatile automatic object...
3592 if (VDType.isVolatileQualified())
3593 return NamedReturnInfo();
3594 } else if (VDType->isRValueReferenceType()) {
3595 // C++20 [class.copy.elision]p3:
3596 // ...either a non-volatile object or an rvalue reference to a non-volatile
3597 // object type...
3598 QualType VDReferencedType = VDType.getNonReferenceType();
3599 if (VDReferencedType.isVolatileQualified() ||
3600 !VDReferencedType->isObjectType())
3601 return NamedReturnInfo();
3602 Info.S = NamedReturnInfo::MoveEligible;
3603 } else {
3604 return NamedReturnInfo();
3605 }
3606
3607 // Variables with higher required alignment than their type's ABI
3608 // alignment cannot use NRVO.
3609 if (!VD->hasDependentAlignment() && !VDType->isIncompleteType() &&
3610 Context.getDeclAlign(D: VD) > Context.getTypeAlignInChars(T: VDType))
3611 Info.S = NamedReturnInfo::MoveEligible;
3612
3613 return Info;
3614}
3615
3616const VarDecl *Sema::getCopyElisionCandidate(NamedReturnInfo &Info,
3617 QualType ReturnType) {
3618 if (!Info.Candidate)
3619 return nullptr;
3620
3621 auto invalidNRVO = [&] {
3622 Info = NamedReturnInfo();
3623 return nullptr;
3624 };
3625
3626 // If we got a non-deduced auto ReturnType, we are in a dependent context and
3627 // there is no point in allowing copy elision since we won't have it deduced
3628 // by the point the VardDecl is instantiated, which is the last chance we have
3629 // of deciding if the candidate is really copy elidable.
3630 if ((ReturnType->getTypeClass() == Type::TypeClass::Auto &&
3631 ReturnType->isCanonicalUnqualified()) ||
3632 ReturnType->isSpecificBuiltinType(K: BuiltinType::Dependent))
3633 return invalidNRVO();
3634
3635 if (!ReturnType->isDependentType()) {
3636 // - in a return statement in a function with ...
3637 // ... a class return type ...
3638 if (!ReturnType->isRecordType())
3639 return invalidNRVO();
3640
3641 QualType VDType = Info.Candidate->getType();
3642 // ... the same cv-unqualified type as the function return type ...
3643 // When considering moving this expression out, allow dissimilar types.
3644 if (!VDType->isDependentType() &&
3645 !Context.hasSameUnqualifiedType(T1: ReturnType, T2: VDType))
3646 Info.S = NamedReturnInfo::MoveEligible;
3647 }
3648 return Info.isCopyElidable() ? Info.Candidate : nullptr;
3649}
3650
3651/// Verify that the initialization sequence that was picked for the
3652/// first overload resolution is permissible under C++98.
3653///
3654/// Reject (possibly converting) constructors not taking an rvalue reference,
3655/// or user conversion operators which are not ref-qualified.
3656static bool
3657VerifyInitializationSequenceCXX98(const Sema &S,
3658 const InitializationSequence &Seq) {
3659 const auto *Step = llvm::find_if(Range: Seq.steps(), P: [](const auto &Step) {
3660 return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3661 Step.Kind == InitializationSequence::SK_UserConversion;
3662 });
3663 if (Step != Seq.step_end()) {
3664 const auto *FD = Step->Function.Function;
3665 if (isa<CXXConstructorDecl>(Val: FD)
3666 ? !FD->getParamDecl(i: 0)->getType()->isRValueReferenceType()
3667 : cast<CXXMethodDecl>(Val: FD)->getRefQualifier() == RQ_None)
3668 return false;
3669 }
3670 return true;
3671}
3672
3673ExprResult Sema::PerformMoveOrCopyInitialization(
3674 const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value,
3675 bool SupressSimplerImplicitMoves) {
3676 if (getLangOpts().CPlusPlus &&
3677 (!getLangOpts().CPlusPlus23 || SupressSimplerImplicitMoves) &&
3678 NRInfo.isMoveEligible()) {
3679 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3680 CK_NoOp, Value, VK_XValue, FPOptionsOverride());
3681 Expr *InitExpr = &AsRvalue;
3682 auto Kind = InitializationKind::CreateCopy(InitLoc: Value->getBeginLoc(),
3683 EqualLoc: Value->getBeginLoc());
3684 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3685 auto Res = Seq.getFailedOverloadResult();
3686 if ((Res == OR_Success || Res == OR_Deleted) &&
3687 (getLangOpts().CPlusPlus11 ||
3688 VerifyInitializationSequenceCXX98(S: *this, Seq))) {
3689 // Promote "AsRvalue" to the heap, since we now need this
3690 // expression node to persist.
3691 Value =
3692 ImplicitCastExpr::Create(Context, T: Value->getType(), Kind: CK_NoOp, Operand: Value,
3693 BasePath: nullptr, Cat: VK_XValue, FPO: FPOptionsOverride());
3694 // Complete type-checking the initialization of the return type
3695 // using the constructor we found.
3696 return Seq.Perform(S&: *this, Entity, Kind, Args: Value);
3697 }
3698 }
3699 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3700 // above, or overload resolution failed. Either way, we need to try
3701 // (again) now with the return value expression as written.
3702 return PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Value);
3703}
3704
3705/// Determine whether the declared return type of the specified function
3706/// contains 'auto'.
3707static bool hasDeducedReturnType(FunctionDecl *FD) {
3708 const FunctionProtoType *FPT =
3709 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3710 return FPT->getReturnType()->isUndeducedType();
3711}
3712
3713StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,
3714 Expr *RetValExp,
3715 NamedReturnInfo &NRInfo,
3716 bool SupressSimplerImplicitMoves) {
3717 // If this is the first return we've seen, infer the return type.
3718 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3719 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(Val: getCurFunction());
3720 QualType FnRetType = CurCap->ReturnType;
3721 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(Val: CurCap);
3722 if (CurLambda && CurLambda->CallOperator->getType().isNull())
3723 return StmtError();
3724 bool HasDeducedReturnType =
3725 CurLambda && hasDeducedReturnType(FD: CurLambda->CallOperator);
3726
3727 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3728 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3729 if (RetValExp) {
3730 ExprResult ER =
3731 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
3732 if (ER.isInvalid())
3733 return StmtError();
3734 RetValExp = ER.get();
3735 }
3736 return ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp,
3737 /* NRVOCandidate=*/nullptr);
3738 }
3739
3740 if (HasDeducedReturnType) {
3741 FunctionDecl *FD = CurLambda->CallOperator;
3742 // If we've already decided this lambda is invalid, e.g. because
3743 // we saw a `return` whose expression had an error, don't keep
3744 // trying to deduce its return type.
3745 if (FD->isInvalidDecl())
3746 return StmtError();
3747 // In C++1y, the return type may involve 'auto'.
3748 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3749 if (CurCap->ReturnType.isNull())
3750 CurCap->ReturnType = FD->getReturnType();
3751
3752 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3753 assert(AT && "lost auto type from lambda return type");
3754 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetExpr: RetValExp, AT)) {
3755 FD->setInvalidDecl();
3756 // FIXME: preserve the ill-formed return expression.
3757 return StmtError();
3758 }
3759 CurCap->ReturnType = FnRetType = FD->getReturnType();
3760 } else if (CurCap->HasImplicitReturnType) {
3761 // For blocks/lambdas with implicit return types, we check each return
3762 // statement individually, and deduce the common return type when the block
3763 // or lambda is completed.
3764 // FIXME: Fold this into the 'auto' codepath above.
3765 if (RetValExp && !isa<InitListExpr>(Val: RetValExp)) {
3766 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RetValExp);
3767 if (Result.isInvalid())
3768 return StmtError();
3769 RetValExp = Result.get();
3770
3771 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3772 // when deducing a return type for a lambda-expression (or by extension
3773 // for a block). These rules differ from the stated C++11 rules only in
3774 // that they remove top-level cv-qualifiers.
3775 if (!CurContext->isDependentContext())
3776 FnRetType = RetValExp->getType().getUnqualifiedType();
3777 else
3778 FnRetType = CurCap->ReturnType = Context.DependentTy;
3779 } else {
3780 if (RetValExp) {
3781 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3782 // initializer list, because it is not an expression (even
3783 // though we represent it as one). We still deduce 'void'.
3784 Diag(Loc: ReturnLoc, DiagID: diag::err_lambda_return_init_list)
3785 << RetValExp->getSourceRange();
3786 RetValExp = nullptr;
3787 }
3788
3789 FnRetType = Context.VoidTy;
3790 }
3791
3792 // Although we'll properly infer the type of the block once it's completed,
3793 // make sure we provide a return type now for better error recovery.
3794 if (CurCap->ReturnType.isNull())
3795 CurCap->ReturnType = FnRetType;
3796 }
3797 const VarDecl *NRVOCandidate = getCopyElisionCandidate(Info&: NRInfo, ReturnType: FnRetType);
3798
3799 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(Val: CurCap)) {
3800 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
3801 Diag(Loc: ReturnLoc, DiagID: diag::err_noreturn_has_return_expr)
3802 << diag::FalloffFunctionKind::Block;
3803 return StmtError();
3804 }
3805 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(Val: CurCap)) {
3806 Diag(Loc: ReturnLoc, DiagID: diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3807 return StmtError();
3808 } else {
3809 assert(CurLambda && "unknown kind of captured scope");
3810 if (CurLambda->CallOperator->getType()
3811 ->castAs<FunctionType>()
3812 ->getNoReturnAttr()) {
3813 Diag(Loc: ReturnLoc, DiagID: diag::err_noreturn_has_return_expr)
3814 << diag::FalloffFunctionKind::Lambda;
3815 return StmtError();
3816 }
3817 }
3818
3819 // Otherwise, verify that this result type matches the previous one. We are
3820 // pickier with blocks than for normal functions because we don't have GCC
3821 // compatibility to worry about here.
3822 if (FnRetType->isDependentType()) {
3823 // Delay processing for now. TODO: there are lots of dependent
3824 // types we can conclusively prove aren't void.
3825 } else if (FnRetType->isVoidType()) {
3826 if (isa_and_nonnull<InitListExpr>(Val: RetValExp)) {
3827 Diag(Loc: ReturnLoc, DiagID: diag::err_return_block_has_expr)
3828 << (CurLambda != nullptr);
3829 RetValExp = nullptr;
3830 } else if (RetValExp && !(getLangOpts().CPlusPlus &&
3831 (RetValExp->isTypeDependent() ||
3832 RetValExp->getType()->isVoidType()))) {
3833 if (!getLangOpts().CPlusPlus && RetValExp->getType()->isVoidType())
3834 Diag(Loc: ReturnLoc, DiagID: diag::ext_return_has_void_expr) << "literal" << 2;
3835 else {
3836 Diag(Loc: ReturnLoc, DiagID: diag::err_return_block_has_expr)
3837 << (CurLambda != nullptr);
3838 RetValExp = nullptr;
3839 }
3840 }
3841 } else if (!RetValExp) {
3842 return StmtError(Diag(Loc: ReturnLoc, DiagID: diag::err_block_return_missing_expr));
3843 } else if (!RetValExp->isTypeDependent()) {
3844 // we have a non-void block with an expression, continue checking
3845
3846 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3847 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3848 // function return.
3849
3850 // In C++ the return statement is handled via a copy initialization.
3851 // the C version of which boils down to CheckSingleAssignmentConstraints.
3852 InitializedEntity Entity =
3853 InitializedEntity::InitializeResult(ReturnLoc, Type: FnRetType);
3854 ExprResult Res = PerformMoveOrCopyInitialization(
3855 Entity, NRInfo, Value: RetValExp, SupressSimplerImplicitMoves);
3856 if (Res.isInvalid()) {
3857 // FIXME: Cleanup temporaries here, anyway?
3858 return StmtError();
3859 }
3860 RetValExp = Res.get();
3861 CheckReturnValExpr(RetValExp, lhsType: FnRetType, ReturnLoc);
3862 }
3863
3864 if (RetValExp) {
3865 ExprResult ER =
3866 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
3867 if (ER.isInvalid())
3868 return StmtError();
3869 RetValExp = ER.get();
3870 }
3871 auto *Result =
3872 ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp, NRVOCandidate);
3873
3874 // If we need to check for the named return value optimization,
3875 // or if we need to infer the return type,
3876 // save the return statement in our scope for later processing.
3877 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3878 FunctionScopes.back()->Returns.push_back(Elt: Result);
3879
3880 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3881 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3882
3883 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(Val: CurCap);
3884 CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
3885 RetValExp->containsErrors())
3886 CurBlock->TheDecl->setInvalidDecl();
3887
3888 return Result;
3889}
3890
3891namespace {
3892/// Marks all typedefs in all local classes in a type referenced.
3893///
3894/// In a function like
3895/// auto f() {
3896/// struct S { typedef int a; };
3897/// return S();
3898/// }
3899///
3900/// the local type escapes and could be referenced in some TUs but not in
3901/// others. Pretend that all local typedefs are always referenced, to not warn
3902/// on this. This isn't necessary if f has internal linkage, or the typedef
3903/// is private.
3904class LocalTypedefNameReferencer : public DynamicRecursiveASTVisitor {
3905public:
3906 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3907 bool VisitRecordType(RecordType *RT) override;
3908
3909private:
3910 Sema &S;
3911};
3912bool LocalTypedefNameReferencer::VisitRecordType(RecordType *RT) {
3913 auto *R = dyn_cast<CXXRecordDecl>(Val: RT->getDecl());
3914 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3915 R->isDependentType())
3916 return true;
3917 for (auto *TmpD : R->decls())
3918 if (auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
3919 if (T->getAccess() != AS_private || R->hasFriends())
3920 S.MarkAnyDeclReferenced(Loc: T->getLocation(), D: T, /*OdrUse=*/MightBeOdrUse: false);
3921 return true;
3922}
3923}
3924
3925TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3926 return FD->getTypeSourceInfo()
3927 ->getTypeLoc()
3928 .getAsAdjusted<FunctionProtoTypeLoc>()
3929 .getReturnLoc();
3930}
3931
3932bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3933 SourceLocation ReturnLoc,
3934 Expr *RetExpr, const AutoType *AT) {
3935 // If this is the conversion function for a lambda, we choose to deduce its
3936 // type from the corresponding call operator, not from the synthesized return
3937 // statement within it. See Sema::DeduceReturnType.
3938 if (isLambdaConversionOperator(D: FD))
3939 return false;
3940
3941 if (isa_and_nonnull<InitListExpr>(Val: RetExpr)) {
3942 // If the deduction is for a return statement and the initializer is
3943 // a braced-init-list, the program is ill-formed.
3944 Diag(Loc: RetExpr->getExprLoc(),
3945 DiagID: getCurLambda() ? diag::err_lambda_return_init_list
3946 : diag::err_auto_fn_return_init_list)
3947 << RetExpr->getSourceRange();
3948 return true;
3949 }
3950
3951 if (FD->isDependentContext()) {
3952 // C++1y [dcl.spec.auto]p12:
3953 // Return type deduction [...] occurs when the definition is
3954 // instantiated even if the function body contains a return
3955 // statement with a non-type-dependent operand.
3956 assert(AT->isDeduced() && "should have deduced to dependent type");
3957 return false;
3958 }
3959
3960 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3961 // In the case of a return with no operand, the initializer is considered
3962 // to be void().
3963 CXXScalarValueInitExpr VoidVal(Context.VoidTy, nullptr, SourceLocation());
3964 if (!RetExpr) {
3965 // For a function with a deduced result type to return with omitted
3966 // expression, the result type as written must be 'auto' or
3967 // 'decltype(auto)', possibly cv-qualified or constrained, but not
3968 // ref-qualified.
3969 if (!OrigResultType.getType()->getAs<AutoType>()) {
3970 Diag(Loc: ReturnLoc, DiagID: diag::err_auto_fn_return_void_but_not_auto)
3971 << OrigResultType.getType();
3972 return true;
3973 }
3974 RetExpr = &VoidVal;
3975 }
3976
3977 QualType Deduced = AT->getDeducedType();
3978 {
3979 // Otherwise, [...] deduce a value for U using the rules of template
3980 // argument deduction.
3981 auto RetExprLoc = RetExpr->getExprLoc();
3982 TemplateDeductionInfo Info(RetExprLoc);
3983 SourceLocation TemplateSpecLoc;
3984 if (RetExpr->getType() == Context.OverloadTy) {
3985 auto FindResult = OverloadExpr::find(E: RetExpr);
3986 if (FindResult.Expression)
3987 TemplateSpecLoc = FindResult.Expression->getNameLoc();
3988 }
3989 TemplateSpecCandidateSet FailedTSC(TemplateSpecLoc);
3990 TemplateDeductionResult Res = DeduceAutoType(
3991 AutoTypeLoc: OrigResultType, Initializer: RetExpr, Result&: Deduced, Info, /*DependentDeduction=*/false,
3992 /*IgnoreConstraints=*/false, FailedTSC: &FailedTSC);
3993 if (Res != TemplateDeductionResult::Success && FD->isInvalidDecl())
3994 return true;
3995 switch (Res) {
3996 case TemplateDeductionResult::Success:
3997 break;
3998 case TemplateDeductionResult::AlreadyDiagnosed:
3999 return true;
4000 case TemplateDeductionResult::Inconsistent: {
4001 // If a function with a declared return type that contains a placeholder
4002 // type has multiple return statements, the return type is deduced for
4003 // each return statement. [...] if the type deduced is not the same in
4004 // each deduction, the program is ill-formed.
4005 const LambdaScopeInfo *LambdaSI = getCurLambda();
4006 if (LambdaSI && LambdaSI->HasImplicitReturnType)
4007 Diag(Loc: ReturnLoc, DiagID: diag::err_typecheck_missing_return_type_incompatible)
4008 << Info.SecondArg << Info.FirstArg << true /*IsLambda*/;
4009 else
4010 Diag(Loc: ReturnLoc, DiagID: diag::err_auto_fn_different_deductions)
4011 << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg
4012 << Info.FirstArg;
4013 return true;
4014 }
4015 default:
4016 Diag(Loc: RetExpr->getExprLoc(), DiagID: diag::err_auto_fn_deduction_failure)
4017 << OrigResultType.getType() << RetExpr->getType();
4018 FailedTSC.NoteCandidates(S&: *this, Loc: RetExprLoc);
4019 return true;
4020 }
4021 }
4022
4023 // If a local type is part of the returned type, mark its fields as
4024 // referenced.
4025 LocalTypedefNameReferencer(*this).TraverseType(T: RetExpr->getType());
4026
4027 // CUDA: Kernel function must have 'void' return type.
4028 if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() &&
4029 !Deduced->isVoidType()) {
4030 Diag(Loc: FD->getLocation(), DiagID: diag::err_kern_type_not_void_return)
4031 << FD->getType() << FD->getSourceRange();
4032 return true;
4033 }
4034
4035 if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced)
4036 // Update all declarations of the function to have the deduced return type.
4037 Context.adjustDeducedFunctionResultType(FD, ResultType: Deduced);
4038
4039 if (!Deduced->isDependentType() && !Deduced->isRecordType() &&
4040 !FD->isFunctionTemplateSpecialization())
4041 diagnoseIgnoredQualifiers(
4042 DiagID: diag::warn_qual_return_type,
4043 Quals: FD->getDeclaredReturnType().getLocalCVRQualifiers(), FallbackLoc: FD->getLocation());
4044 return false;
4045}
4046
4047StmtResult
4048Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4049 Scope *CurScope) {
4050 ExprResult RetVal = RetValExp;
4051 if (RetVal.isInvalid())
4052 return StmtError();
4053
4054 if (getCurScope()->isInOpenACCComputeConstructScope())
4055 return StmtError(
4056 Diag(Loc: ReturnLoc, DiagID: diag::err_acc_branch_in_out_compute_construct)
4057 << /*return*/ 1 << /*out of */ 0);
4058
4059 // using plain return in a coroutine is not allowed.
4060 FunctionScopeInfo *FSI = getCurFunction();
4061 if (FSI->FirstReturnLoc.isInvalid() && FSI->isCoroutine()) {
4062 assert(FSI->FirstCoroutineStmtLoc.isValid() &&
4063 "first coroutine location not set");
4064 Diag(Loc: ReturnLoc, DiagID: diag::err_return_in_coroutine);
4065 Diag(Loc: FSI->FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
4066 << FSI->getFirstCoroutineStmtKeyword();
4067 }
4068
4069 CheckInvalidBuiltinCountedByRef(E: RetVal.get(),
4070 K: BuiltinCountedByRefKind::ReturnArg);
4071
4072 StmtResult R =
4073 BuildReturnStmt(ReturnLoc, RetValExp: RetVal.get(), /*AllowRecovery=*/true);
4074 if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
4075 return R;
4076
4077 VarDecl *VD =
4078 const_cast<VarDecl *>(cast<ReturnStmt>(Val: R.get())->getNRVOCandidate());
4079
4080 CurScope->updateNRVOCandidate(VD);
4081
4082 CheckJumpOutOfSEHFinallyOrDefer(S&: *this, Loc: ReturnLoc, DestScope: *CurScope->getFnParent(),
4083 DeferJumpKind: diag::DeferJumpKind::Return);
4084
4085 return R;
4086}
4087
4088void Sema::ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope) {
4089 CurrentDefer.emplace_back(Args&: CurScope, Args&: DeferLoc);
4090}
4091
4092void Sema::ActOnDeferStmtError([[maybe_unused]] Scope *CurScope) {
4093 assert(!CurrentDefer.empty() && CurrentDefer.back().first == CurScope);
4094 CurrentDefer.pop_back();
4095}
4096
4097StmtResult Sema::ActOnEndOfDeferStmt(Stmt *Body,
4098 [[maybe_unused]] Scope *CurScope) {
4099 assert(!CurrentDefer.empty() && CurrentDefer.back().first == CurScope);
4100 SourceLocation DeferLoc = CurrentDefer.pop_back_val().second;
4101 DiagnoseEmptyStmtBody(StmtLoc: DeferLoc, Body, DiagID: diag::warn_empty_defer_body);
4102 CheckRedundantDeferStmt(S&: *this, Body);
4103 setFunctionHasBranchProtectedScope();
4104 return DeferStmt::Create(Context, DeferLoc, Body);
4105}
4106
4107static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S,
4108 const Expr *E) {
4109 if (!E || !S.getLangOpts().CPlusPlus23 || !S.getLangOpts().MSVCCompat)
4110 return false;
4111 const Decl *D = E->getReferencedDeclOfCallee();
4112 if (!D || !S.SourceMgr.isInSystemHeader(Loc: D->getLocation()))
4113 return false;
4114 for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
4115 if (DC->isStdNamespace())
4116 return true;
4117 }
4118 return false;
4119}
4120
4121StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4122 bool AllowRecovery) {
4123 // Check for unexpanded parameter packs.
4124 if (RetValExp && DiagnoseUnexpandedParameterPack(E: RetValExp))
4125 return StmtError();
4126
4127 // HACK: We suppress simpler implicit move here in msvc compatibility mode
4128 // just as a temporary work around, as the MSVC STL has issues with
4129 // this change.
4130 bool SupressSimplerImplicitMoves =
4131 CheckSimplerImplicitMovesMSVCWorkaround(S: *this, E: RetValExp);
4132 NamedReturnInfo NRInfo = getNamedReturnInfo(
4133 E&: RetValExp, Mode: SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
4134 : SimplerImplicitMoveMode::Normal);
4135
4136 if (isa<CapturingScopeInfo>(Val: getCurFunction()))
4137 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
4138 SupressSimplerImplicitMoves);
4139
4140 QualType FnRetType;
4141 QualType RelatedRetType;
4142 const AttrVec *Attrs = nullptr;
4143 bool isObjCMethod = false;
4144
4145 FunctionDecl *FD = getCurFunctionDecl();
4146 if (FD) {
4147 FnRetType = FD->getReturnType();
4148 if (FD->hasAttrs())
4149 Attrs = &FD->getAttrs();
4150 if (FD->isNoReturn() && !getCurFunction()->isCoroutine())
4151 Diag(Loc: ReturnLoc, DiagID: diag::warn_noreturn_function_has_return_expr) << FD;
4152 if (FD->isMain() && RetValExp)
4153 if (isa<CXXBoolLiteralExpr>(Val: RetValExp))
4154 Diag(Loc: ReturnLoc, DiagID: diag::warn_main_returns_bool_literal)
4155 << RetValExp->getSourceRange();
4156 if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
4157 if (const auto *RT = dyn_cast<RecordType>(Val: FnRetType.getCanonicalType())) {
4158 if (RT->getDecl()->isOrContainsUnion())
4159 Diag(Loc: RetValExp->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union) << 1;
4160 }
4161 }
4162 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
4163 FnRetType = MD->getReturnType();
4164 isObjCMethod = true;
4165 if (MD->hasAttrs())
4166 Attrs = &MD->getAttrs();
4167 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
4168 // In the implementation of a method with a related return type, the
4169 // type used to type-check the validity of return statements within the
4170 // method body is a pointer to the type of the class being implemented.
4171 RelatedRetType = Context.getObjCInterfaceType(Decl: MD->getClassInterface());
4172 RelatedRetType = Context.getObjCObjectPointerType(OIT: RelatedRetType);
4173 }
4174 } else // If we don't have a function/method context, bail.
4175 return StmtError();
4176
4177 if (RetValExp) {
4178 const auto *ATy = dyn_cast<ArrayType>(Val: RetValExp->getType());
4179 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
4180 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
4181 return StmtError();
4182 }
4183 }
4184
4185 // C++1z: discarded return statements are not considered when deducing a
4186 // return type.
4187 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
4188 FnRetType->getContainedAutoType()) {
4189 if (RetValExp) {
4190 ExprResult ER =
4191 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
4192 if (ER.isInvalid())
4193 return StmtError();
4194 RetValExp = ER.get();
4195 }
4196 return ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp,
4197 /* NRVOCandidate=*/nullptr);
4198 }
4199
4200 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
4201 // deduction.
4202 if (getLangOpts().CPlusPlus14) {
4203 if (AutoType *AT = FnRetType->getContainedAutoType()) {
4204 // If we've already decided this function is invalid, e.g. because
4205 // we saw a `return` whose expression had an error, don't keep
4206 // trying to deduce its return type.
4207 // (Some return values may be needlessly wrapped in RecoveryExpr).
4208 assert(FD);
4209 if (FD->isInvalidDecl() ||
4210 DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetExpr: RetValExp, AT)) {
4211 FD->setInvalidDecl();
4212 if (!AllowRecovery)
4213 return StmtError();
4214 // The deduction failure is diagnosed and marked, try to recover.
4215 if (RetValExp) {
4216 // Wrap return value with a recovery expression of the previous type.
4217 // If no deduction yet, use DependentTy.
4218 auto Recovery = CreateRecoveryExpr(
4219 Begin: RetValExp->getBeginLoc(), End: RetValExp->getEndLoc(), SubExprs: RetValExp,
4220 T: AT->isDeduced() ? FnRetType : QualType());
4221 if (Recovery.isInvalid())
4222 return StmtError();
4223 RetValExp = Recovery.get();
4224 } else {
4225 // Nothing to do: a ReturnStmt with no value is fine recovery.
4226 }
4227 } else {
4228 FnRetType = FD->getReturnType();
4229 }
4230 }
4231 }
4232 const VarDecl *NRVOCandidate = getCopyElisionCandidate(Info&: NRInfo, ReturnType: FnRetType);
4233
4234 bool HasDependentReturnType = FnRetType->isDependentType();
4235
4236 ReturnStmt *Result = nullptr;
4237 if (FnRetType->isVoidType()) {
4238 if (RetValExp) {
4239 if (auto *ILE = dyn_cast<InitListExpr>(Val: RetValExp)) {
4240 // We simply never allow init lists as the return value of void
4241 // functions. This is compatible because this was never allowed before,
4242 // so there's no legacy code to deal with.
4243 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4244 int FunctionKind = 0;
4245 if (isa<ObjCMethodDecl>(Val: CurDecl))
4246 FunctionKind = 1;
4247 else if (isa<CXXConstructorDecl>(Val: CurDecl))
4248 FunctionKind = 2;
4249 else if (isa<CXXDestructorDecl>(Val: CurDecl))
4250 FunctionKind = 3;
4251
4252 Diag(Loc: ReturnLoc, DiagID: diag::err_return_init_list)
4253 << CurDecl << FunctionKind << RetValExp->getSourceRange();
4254
4255 // Preserve the initializers in the AST.
4256 RetValExp = AllowRecovery
4257 ? CreateRecoveryExpr(Begin: ILE->getLBraceLoc(),
4258 End: ILE->getRBraceLoc(), SubExprs: ILE->inits())
4259 .get()
4260 : nullptr;
4261 } else if (!RetValExp->isTypeDependent()) {
4262 // C99 6.8.6.4p1 (ext_ since GCC warns)
4263 unsigned D = diag::ext_return_has_expr;
4264 if (RetValExp->getType()->isVoidType()) {
4265 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4266 if (isa<CXXConstructorDecl>(Val: CurDecl) ||
4267 isa<CXXDestructorDecl>(Val: CurDecl))
4268 D = diag::err_ctor_dtor_returns_void;
4269 else
4270 D = diag::ext_return_has_void_expr;
4271 }
4272 else {
4273 ExprResult Result = RetValExp;
4274 Result = IgnoredValueConversions(E: Result.get());
4275 if (Result.isInvalid())
4276 return StmtError();
4277 RetValExp = Result.get();
4278 RetValExp = ImpCastExprToType(E: RetValExp,
4279 Type: Context.VoidTy, CK: CK_ToVoid).get();
4280 }
4281 // return of void in constructor/destructor is illegal in C++.
4282 if (D == diag::err_ctor_dtor_returns_void) {
4283 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4284 Diag(Loc: ReturnLoc, DiagID: D) << CurDecl << isa<CXXDestructorDecl>(Val: CurDecl)
4285 << RetValExp->getSourceRange();
4286 }
4287 // return (some void expression); is legal in C++ and C2y.
4288 else if (D != diag::ext_return_has_void_expr ||
4289 (!getLangOpts().CPlusPlus && !getLangOpts().C2y)) {
4290 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4291
4292 int FunctionKind = 0;
4293 if (isa<ObjCMethodDecl>(Val: CurDecl))
4294 FunctionKind = 1;
4295 else if (isa<CXXConstructorDecl>(Val: CurDecl))
4296 FunctionKind = 2;
4297 else if (isa<CXXDestructorDecl>(Val: CurDecl))
4298 FunctionKind = 3;
4299
4300 Diag(Loc: ReturnLoc, DiagID: D)
4301 << CurDecl << FunctionKind << RetValExp->getSourceRange();
4302 }
4303 }
4304
4305 if (RetValExp) {
4306 ExprResult ER =
4307 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
4308 if (ER.isInvalid())
4309 return StmtError();
4310 RetValExp = ER.get();
4311 }
4312 }
4313
4314 Result = ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp,
4315 /* NRVOCandidate=*/nullptr);
4316 } else if (!RetValExp && !HasDependentReturnType) {
4317 if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) {
4318 // The intended return type might have been "void", so don't warn.
4319 } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
4320 // C++11 [stmt.return]p2
4321 Diag(Loc: ReturnLoc, DiagID: diag::err_constexpr_return_missing_expr)
4322 << FD << FD->isConsteval();
4323 FD->setInvalidDecl();
4324 } else {
4325 // C99 6.8.6.4p1 (ext_ since GCC warns)
4326 // C90 6.6.6.4p4
4327 unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
4328 : diag::warn_return_missing_expr;
4329 // Note that at this point one of getCurFunctionDecl() or
4330 // getCurMethodDecl() must be non-null (see above).
4331 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4332 "Not in a FunctionDecl or ObjCMethodDecl?");
4333 bool IsMethod = FD == nullptr;
4334 const NamedDecl *ND =
4335 IsMethod ? cast<NamedDecl>(Val: getCurMethodDecl()) : cast<NamedDecl>(Val: FD);
4336 Diag(Loc: ReturnLoc, DiagID) << ND << IsMethod;
4337 }
4338
4339 Result = ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, /* RetExpr=*/E: nullptr,
4340 /* NRVOCandidate=*/nullptr);
4341 } else {
4342 assert(RetValExp || HasDependentReturnType);
4343 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
4344
4345 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4346 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4347 // function return.
4348
4349 // In C++ the return statement is handled via a copy initialization,
4350 // the C version of which boils down to CheckSingleAssignmentConstraints.
4351 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
4352 // we have a non-void function with an expression, continue checking
4353 InitializedEntity Entity =
4354 InitializedEntity::InitializeResult(ReturnLoc, Type: RetType);
4355 ExprResult Res = PerformMoveOrCopyInitialization(
4356 Entity, NRInfo, Value: RetValExp, SupressSimplerImplicitMoves);
4357 if (Res.isInvalid() && AllowRecovery)
4358 Res = CreateRecoveryExpr(Begin: RetValExp->getBeginLoc(),
4359 End: RetValExp->getEndLoc(), SubExprs: RetValExp, T: RetType);
4360 if (Res.isInvalid()) {
4361 // FIXME: Clean up temporaries here anyway?
4362 return StmtError();
4363 }
4364 RetValExp = Res.getAs<Expr>();
4365
4366 // If we have a related result type, we need to implicitly
4367 // convert back to the formal result type. We can't pretend to
4368 // initialize the result again --- we might end double-retaining
4369 // --- so instead we initialize a notional temporary.
4370 if (!RelatedRetType.isNull()) {
4371 Entity = InitializedEntity::InitializeRelatedResult(MD: getCurMethodDecl(),
4372 Type: FnRetType);
4373 Res = PerformCopyInitialization(Entity, EqualLoc: ReturnLoc, Init: RetValExp);
4374 if (Res.isInvalid()) {
4375 // FIXME: Clean up temporaries here anyway?
4376 return StmtError();
4377 }
4378 RetValExp = Res.getAs<Expr>();
4379 }
4380
4381 CheckReturnValExpr(RetValExp, lhsType: FnRetType, ReturnLoc, isObjCMethod, Attrs,
4382 FD: getCurFunctionDecl());
4383 }
4384
4385 if (RetValExp) {
4386 ExprResult ER =
4387 ActOnFinishFullExpr(Expr: RetValExp, CC: ReturnLoc, /*DiscardedValue*/ false);
4388 if (ER.isInvalid())
4389 return StmtError();
4390 RetValExp = ER.get();
4391 }
4392 Result = ReturnStmt::Create(Ctx: Context, RL: ReturnLoc, E: RetValExp, NRVOCandidate);
4393 }
4394
4395 // If we need to check for the named return value optimization, save the
4396 // return statement in our scope for later processing.
4397 if (Result->getNRVOCandidate())
4398 FunctionScopes.back()->Returns.push_back(Elt: Result);
4399
4400 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
4401 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
4402
4403 return Result;
4404}
4405
4406StmtResult
4407Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
4408 Stmt *HandlerBlock) {
4409 // There's nothing to test that ActOnExceptionDecl didn't already test.
4410 return new (Context)
4411 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(Val: ExDecl), HandlerBlock);
4412}
4413
4414namespace {
4415class CatchHandlerType {
4416 QualType QT;
4417 LLVM_PREFERRED_TYPE(bool)
4418 unsigned IsPointer : 1;
4419
4420 friend struct llvm::DenseMapInfo<CatchHandlerType>;
4421
4422public:
4423 /// Used when creating a CatchHandlerType from a handler type; will determine
4424 /// whether the type is a pointer or reference and will strip off the top
4425 /// level pointer and cv-qualifiers.
4426 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
4427 if (QT->isPointerType())
4428 IsPointer = true;
4429
4430 QT = QT.getUnqualifiedType();
4431 if (IsPointer || QT->isReferenceType())
4432 QT = QT->getPointeeType();
4433 }
4434
4435 /// Used when creating a CatchHandlerType from a base class type; pretends the
4436 /// type passed in had the pointer qualifier, does not need to get an
4437 /// unqualified type.
4438 CatchHandlerType(QualType QT, bool IsPointer)
4439 : QT(QT), IsPointer(IsPointer) {}
4440
4441 QualType underlying() const { return QT; }
4442 bool isPointer() const { return IsPointer; }
4443
4444 friend bool operator==(const CatchHandlerType &LHS,
4445 const CatchHandlerType &RHS) {
4446 // If the pointer qualification does not match, we can return early.
4447 if (LHS.IsPointer != RHS.IsPointer)
4448 return false;
4449 // Otherwise, check the underlying type without cv-qualifiers.
4450 return LHS.QT == RHS.QT;
4451 }
4452};
4453} // namespace
4454
4455namespace llvm {
4456template <> struct DenseMapInfo<CatchHandlerType> {
4457 static unsigned getHashValue(const CatchHandlerType &Base) {
4458 return DenseMapInfo<QualType>::getHashValue(Val: Base.underlying());
4459 }
4460
4461 static bool isEqual(const CatchHandlerType &LHS,
4462 const CatchHandlerType &RHS) {
4463 return LHS == RHS;
4464 }
4465};
4466}
4467
4468namespace {
4469class CatchTypePublicBases {
4470 const llvm::DenseMap<QualType, CXXCatchStmt *> &TypesToCheck;
4471
4472 CXXCatchStmt *FoundHandler;
4473 QualType FoundHandlerType;
4474 QualType TestAgainstType;
4475
4476public:
4477 CatchTypePublicBases(const llvm::DenseMap<QualType, CXXCatchStmt *> &T,
4478 QualType QT)
4479 : TypesToCheck(T), FoundHandler(nullptr), TestAgainstType(QT) {}
4480
4481 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
4482 QualType getFoundHandlerType() const { return FoundHandlerType; }
4483
4484 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
4485 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
4486 QualType Check = S->getType().getCanonicalType();
4487 const auto &M = TypesToCheck;
4488 auto I = M.find(Val: Check);
4489 if (I != M.end()) {
4490 // We're pretty sure we found what we need to find. However, we still
4491 // need to make sure that we properly compare for pointers and
4492 // references, to handle cases like:
4493 //
4494 // } catch (Base *b) {
4495 // } catch (Derived &d) {
4496 // }
4497 //
4498 // where there is a qualification mismatch that disqualifies this
4499 // handler as a potential problem.
4500 if (I->second->getCaughtType()->isPointerType() ==
4501 TestAgainstType->isPointerType()) {
4502 FoundHandler = I->second;
4503 FoundHandlerType = Check;
4504 return true;
4505 }
4506 }
4507 }
4508 return false;
4509 }
4510};
4511}
4512
4513StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4514 ArrayRef<Stmt *> Handlers) {
4515 const llvm::Triple &T = Context.getTargetInfo().getTriple();
4516 const bool IsOpenMPGPUTarget =
4517 getLangOpts().OpenMPIsTargetDevice && T.isGPU();
4518
4519 DiagnoseExceptionUse(Loc: TryLoc, /* IsTry= */ true);
4520
4521 // In OpenMP target regions, we assume that catch is never reached on GPU
4522 // targets.
4523 if (IsOpenMPGPUTarget)
4524 targetDiag(Loc: TryLoc, DiagID: diag::warn_try_not_valid_on_target) << T.str();
4525
4526 // Exceptions aren't allowed in CUDA device code.
4527 if (getLangOpts().CUDA)
4528 CUDA().DiagIfDeviceCode(Loc: TryLoc, DiagID: diag::err_cuda_device_exceptions)
4529 << "try" << CUDA().CurrentTarget();
4530
4531 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4532 Diag(Loc: TryLoc, DiagID: diag::err_omp_simd_region_cannot_use_stmt) << "try";
4533
4534 sema::FunctionScopeInfo *FSI = getCurFunction();
4535
4536 // C++ try is incompatible with SEH __try.
4537 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4538 Diag(Loc: TryLoc, DiagID: diag::err_mixing_cxx_try_seh_try) << 0;
4539 Diag(Loc: FSI->FirstSEHTryLoc, DiagID: diag::note_conflicting_try_here) << "'__try'";
4540 }
4541
4542 const unsigned NumHandlers = Handlers.size();
4543 assert(!Handlers.empty() &&
4544 "The parser shouldn't call this if there are no handlers.");
4545
4546 llvm::DenseMap<QualType, CXXCatchStmt *> HandledBaseTypes;
4547 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4548 for (unsigned i = 0; i < NumHandlers; ++i) {
4549 CXXCatchStmt *H = cast<CXXCatchStmt>(Val: Handlers[i]);
4550
4551 // Diagnose when the handler is a catch-all handler, but it isn't the last
4552 // handler for the try block. [except.handle]p5. Also, skip exception
4553 // declarations that are invalid, since we can't usefully report on them.
4554 if (!H->getExceptionDecl()) {
4555 if (i < NumHandlers - 1)
4556 return StmtError(Diag(Loc: H->getBeginLoc(), DiagID: diag::err_early_catch_all));
4557 continue;
4558 } else if (H->getExceptionDecl()->isInvalidDecl())
4559 continue;
4560
4561 // Walk the type hierarchy to diagnose when this type has already been
4562 // handled (duplication), or cannot be handled (derivation inversion). We
4563 // ignore top-level cv-qualifiers, per [except.handle]p3
4564 CatchHandlerType HandlerCHT = H->getCaughtType().getCanonicalType();
4565
4566 // We can ignore whether the type is a reference or a pointer; we need the
4567 // underlying declaration type in order to get at the underlying record
4568 // decl, if there is one.
4569 QualType Underlying = HandlerCHT.underlying();
4570 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4571 if (!RD->hasDefinition())
4572 continue;
4573 // Check that none of the public, unambiguous base classes are in the
4574 // map ([except.handle]p1). Give the base classes the same pointer
4575 // qualification as the original type we are basing off of. This allows
4576 // comparison against the handler type using the same top-level pointer
4577 // as the original type.
4578 CXXBasePaths Paths;
4579 Paths.setOrigin(RD);
4580 CatchTypePublicBases CTPB(HandledBaseTypes,
4581 H->getCaughtType().getCanonicalType());
4582 if (RD->lookupInBases(BaseMatches: CTPB, Paths)) {
4583 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4584 if (!Paths.isAmbiguous(
4585 BaseType: CanQualType::CreateUnsafe(Other: CTPB.getFoundHandlerType()))) {
4586 Diag(Loc: H->getExceptionDecl()->getTypeSpecStartLoc(),
4587 DiagID: diag::warn_exception_caught_by_earlier_handler)
4588 << H->getCaughtType();
4589 Diag(Loc: Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4590 DiagID: diag::note_previous_exception_handler)
4591 << Problem->getCaughtType();
4592 }
4593 }
4594 // Strip the qualifiers here because we're going to be comparing this
4595 // type to the base type specifiers of a class, which are ignored in a
4596 // base specifier per [class.derived.general]p2.
4597 HandledBaseTypes[Underlying.getUnqualifiedType()] = H;
4598 }
4599
4600 // Add the type the list of ones we have handled; diagnose if we've already
4601 // handled it.
4602 auto R = HandledTypes.insert(
4603 KV: std::make_pair(x: H->getCaughtType().getCanonicalType(), y&: H));
4604 if (!R.second) {
4605 const CXXCatchStmt *Problem = R.first->second;
4606 Diag(Loc: H->getExceptionDecl()->getTypeSpecStartLoc(),
4607 DiagID: diag::warn_exception_caught_by_earlier_handler)
4608 << H->getCaughtType();
4609 Diag(Loc: Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4610 DiagID: diag::note_previous_exception_handler)
4611 << Problem->getCaughtType();
4612 }
4613 }
4614
4615 FSI->setHasCXXTry(TryLoc);
4616
4617 return CXXTryStmt::Create(C: Context, tryLoc: TryLoc, tryBlock: cast<CompoundStmt>(Val: TryBlock),
4618 handlers: Handlers);
4619}
4620
4621void Sema::DiagnoseExceptionUse(SourceLocation Loc, bool IsTry) {
4622 const llvm::Triple &T = Context.getTargetInfo().getTriple();
4623 const bool IsOpenMPGPUTarget =
4624 getLangOpts().OpenMPIsTargetDevice && T.isGPU();
4625
4626 // Don't report an error if 'try' is used in system headers or in an OpenMP
4627 // target region compiled for a GPU architecture.
4628 if (IsOpenMPGPUTarget || getLangOpts().CUDA)
4629 // Delay error emission for the OpenMP device code.
4630 return;
4631
4632 if (!getLangOpts().CXXExceptions &&
4633 !getSourceManager().isInSystemHeader(Loc) &&
4634 !CurContext->isDependentContext())
4635 targetDiag(Loc, DiagID: diag::err_exceptions_disabled) << (IsTry ? "try" : "throw");
4636}
4637
4638StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4639 Stmt *TryBlock, Stmt *Handler) {
4640 assert(TryBlock && Handler);
4641
4642 sema::FunctionScopeInfo *FSI = getCurFunction();
4643
4644 // SEH __try is incompatible with C++ try. Borland appears to support this,
4645 // however.
4646 if (!getLangOpts().Borland) {
4647 if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
4648 Diag(Loc: TryLoc, DiagID: diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
4649 Diag(Loc: FSI->FirstCXXOrObjCTryLoc, DiagID: diag::note_conflicting_try_here)
4650 << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX
4651 ? "'try'"
4652 : "'@try'");
4653 }
4654 }
4655
4656 FSI->setHasSEHTry(TryLoc);
4657
4658 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4659 // track if they use SEH.
4660 DeclContext *DC = CurContext;
4661 while (DC && !DC->isFunctionOrMethod())
4662 DC = DC->getParent();
4663 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: DC);
4664 if (FD)
4665 FD->setUsesSEHTry(true);
4666 else
4667 Diag(Loc: TryLoc, DiagID: diag::err_seh_try_outside_functions);
4668
4669 // Reject __try on unsupported targets.
4670 if (!Context.getTargetInfo().isSEHTrySupported())
4671 Diag(Loc: TryLoc, DiagID: diag::err_seh_try_unsupported);
4672
4673 return SEHTryStmt::Create(C: Context, isCXXTry: IsCXXTry, TryLoc, TryBlock, Handler);
4674}
4675
4676StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
4677 Stmt *Block) {
4678 assert(FilterExpr && Block);
4679 QualType FTy = FilterExpr->getType();
4680 if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4681 return StmtError(
4682 Diag(Loc: FilterExpr->getExprLoc(), DiagID: diag::err_filter_expression_integral)
4683 << FTy);
4684 }
4685 return SEHExceptStmt::Create(C: Context, ExceptLoc: Loc, FilterExpr, Block);
4686}
4687
4688void Sema::ActOnStartSEHFinallyBlock() {
4689 CurrentSEHFinally.push_back(Elt: CurScope);
4690}
4691
4692void Sema::ActOnAbortSEHFinallyBlock() {
4693 CurrentSEHFinally.pop_back();
4694}
4695
4696StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4697 assert(Block);
4698 CurrentSEHFinally.pop_back();
4699 return SEHFinallyStmt::Create(C: Context, FinallyLoc: Loc, Block);
4700}
4701
4702StmtResult
4703Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4704 Scope *SEHTryParent = CurScope;
4705 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4706 SEHTryParent = SEHTryParent->getParent();
4707 if (!SEHTryParent)
4708 return StmtError(Diag(Loc, DiagID: diag::err_ms___leave_not_in___try));
4709 CheckJumpOutOfSEHFinallyOrDefer(S&: *this, Loc, DestScope: *SEHTryParent,
4710 DeferJumpKind: diag::DeferJumpKind::SEHLeave);
4711
4712 return new (Context) SEHLeaveStmt(Loc);
4713}
4714
4715StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4716 bool IsIfExists,
4717 NestedNameSpecifierLoc QualifierLoc,
4718 DeclarationNameInfo NameInfo,
4719 Stmt *Nested)
4720{
4721 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4722 QualifierLoc, NameInfo,
4723 cast<CompoundStmt>(Val: Nested));
4724}
4725
4726
4727StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4728 bool IsIfExists,
4729 CXXScopeSpec &SS,
4730 UnqualifiedId &Name,
4731 Stmt *Nested) {
4732 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4733 QualifierLoc: SS.getWithLocInContext(Context),
4734 NameInfo: GetNameFromUnqualifiedId(Name),
4735 Nested);
4736}
4737
4738RecordDecl*
4739Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4740 unsigned NumParams) {
4741 DeclContext *DC = CurContext;
4742 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4743 DC = DC->getParent();
4744
4745 RecordDecl *RD = nullptr;
4746 if (getLangOpts().CPlusPlus)
4747 RD = CXXRecordDecl::Create(C: Context, TK: TagTypeKind::Struct, DC, StartLoc: Loc, IdLoc: Loc,
4748 /*Id=*/nullptr);
4749 else
4750 RD = RecordDecl::Create(C: Context, TK: TagTypeKind::Struct, DC, StartLoc: Loc, IdLoc: Loc,
4751 /*Id=*/nullptr);
4752
4753 RD->setCapturedRecord();
4754 DC->addDecl(D: RD);
4755 RD->setImplicit();
4756 RD->startDefinition();
4757
4758 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4759 CD = CapturedDecl::Create(C&: Context, DC: CurContext, NumParams);
4760 DC->addDecl(D: CD);
4761 return RD;
4762}
4763
4764static bool
4765buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4766 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4767 SmallVectorImpl<Expr *> &CaptureInits) {
4768 bool HasError = false; // Track if any errors occurred.
4769 llvm::SmallPtrSet<VarDecl *, 4> CapturedDecomposed;
4770 for (const sema::Capture &Cap : RSI->Captures) {
4771 if (Cap.isInvalid())
4772 continue;
4773
4774 ValueDecl *CapVar = nullptr;
4775 if (Cap.isVariableCapture()) {
4776 CapVar = Cap.getVariable();
4777 if (auto *BD = dyn_cast<BindingDecl>(Val: CapVar)) {
4778 // Detect structured bindings in OpenMP captured regions.
4779 // When a BindingDecl (e.g., 'a' from 'auto [a, b] = p')
4780 // is referenced inside an OpenMP region.
4781 // isVariableCapturable() in SemaExpr.cpp already resets this to the
4782 // DecompositionDecl during per-use expression checking. This runs
4783 // later, at region-end (ActOnCapturedRegionEnd), over the
4784 // already-built capture list, catching captures added without going
4785 // through that per-use path (e.g. via explicit map clauses).
4786 if (RSI->CapRegionKind == CR_OpenMP && BD->getHoldingVar()) {
4787 S.Diag(Loc: Cap.getLocation(), DiagID: diag::err_capture_tuple_binding_openmp)
4788 << CapVar;
4789 S.Diag(Loc: CapVar->getLocation(), DiagID: diag::note_entity_declared_at)
4790 << CapVar;
4791 HasError = true; // Mark error but continue.
4792 continue; // Skip this capture, move to next.
4793 }
4794 CapVar = cast<VarDecl>(Val: BD->getDecomposedDecl());
4795 }
4796 if (RSI->CapRegionKind == CR_OpenMP) {
4797 if (auto *DD = dyn_cast<DecompositionDecl>(Val: CapVar)) {
4798 if (!CapturedDecomposed.insert(Ptr: DD).second) {
4799 continue; // Skip duplicate
4800 }
4801 }
4802 }
4803 }
4804
4805 // Form the initializer for the capture.
4806 ExprResult Init = S.BuildCaptureInit(Capture: Cap, ImplicitCaptureLoc: Cap.getLocation(),
4807 IsOpenMPMapping: RSI->CapRegionKind == CR_OpenMP);
4808
4809 // FIXME: Bail out now if the capture is not used and the initializer has
4810 // no side-effects.
4811
4812 // Build the capture field. For OpenMP, pass IsOpenMP=true to handle
4813 // DecompositionDecl captures correctly.
4814 FieldDecl *Field = S.BuildCaptureField(RD: RSI->TheRecordDecl, Capture: Cap,
4815 IsOpenMP: RSI->CapRegionKind == CR_OpenMP);
4816
4817 // Add the capture to our list of captures.
4818 if (Cap.isThisCapture()) {
4819 Captures.push_back(
4820 Elt: CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_This));
4821 } else if (Cap.isVLATypeCapture()) {
4822 Captures.push_back(
4823 Elt: CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4824 } else {
4825 assert(Cap.isVariableCapture() && "unknown kind of capture");
4826
4827 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
4828 const ValueDecl *DSAVar = Cap.getVariable();
4829 // DSAs are tracked per binding; a captured DecompositionDecl has no
4830 // own DSA entry.
4831 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: DSAVar))
4832 if (!DD->bindings().empty())
4833 DSAVar = *DD->bindings().begin();
4834 S.OpenMP().setOpenMPCaptureKind(FD: Field, D: DSAVar, Level: RSI->OpenMPLevel);
4835 }
4836 Captures.emplace_back(Args: Cap.getLocation(),
4837 Args: Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4838 : CapturedStmt::VCK_ByCopy,
4839 Args: cast<VarDecl>(Val: CapVar));
4840 }
4841 CaptureInits.push_back(Elt: Init.get());
4842 }
4843 return HasError;
4844}
4845
4846static std::optional<int>
4847isOpenMPCapturedRegionInArmSMEFunction(Sema const &S, CapturedRegionKind Kind) {
4848 if (!S.getLangOpts().OpenMP || Kind != CR_OpenMP)
4849 return {};
4850 if (const FunctionDecl *FD = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
4851 if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true))
4852 return /* in streaming functions */ 0;
4853 if (hasArmZAState(FD))
4854 return /* in functions with ZA state */ 1;
4855 if (hasArmZT0State(FD))
4856 return /* in fuctions with ZT0 state */ 2;
4857 }
4858 return {};
4859}
4860
4861void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4862 CapturedRegionKind Kind,
4863 unsigned NumParams) {
4864 if (auto ErrorIndex = isOpenMPCapturedRegionInArmSMEFunction(S: *this, Kind))
4865 Diag(Loc, DiagID: diag::err_sme_openmp_captured_region) << *ErrorIndex;
4866
4867 CapturedDecl *CD = nullptr;
4868 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4869
4870 // Build the context parameter
4871 DeclContext *DC = CapturedDecl::castToDeclContext(D: CD);
4872 IdentifierInfo *ParamName = &Context.Idents.get(Name: "__context");
4873 CanQualType ParamType =
4874 Context.getPointerType(T: Context.getCanonicalTagType(TD: RD));
4875 auto *Param =
4876 ImplicitParamDecl::Create(C&: Context, DC, IdLoc: Loc, Id: ParamName, T: ParamType,
4877 ParamKind: ImplicitParamKind::CapturedContext);
4878 DC->addDecl(D: Param);
4879
4880 CD->setContextParam(i: 0, P: Param);
4881
4882 // Enter the capturing scope for this captured region.
4883 PushCapturedRegionScope(RegionScope: CurScope, CD, RD, K: Kind);
4884
4885 if (CurScope)
4886 PushDeclContext(S: CurScope, DC: CD);
4887 else
4888 CurContext = CD;
4889
4890 PushExpressionEvaluationContext(
4891 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
4892 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = false;
4893}
4894
4895void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4896 CapturedRegionKind Kind,
4897 ArrayRef<CapturedParamNameType> Params,
4898 unsigned OpenMPCaptureLevel) {
4899 if (auto ErrorIndex = isOpenMPCapturedRegionInArmSMEFunction(S: *this, Kind))
4900 Diag(Loc, DiagID: diag::err_sme_openmp_captured_region) << *ErrorIndex;
4901
4902 CapturedDecl *CD = nullptr;
4903 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams: Params.size());
4904
4905 // Build the context parameter
4906 DeclContext *DC = CapturedDecl::castToDeclContext(D: CD);
4907 bool ContextIsFound = false;
4908 unsigned ParamNum = 0;
4909 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4910 E = Params.end();
4911 I != E; ++I, ++ParamNum) {
4912 if (I->second.isNull()) {
4913 assert(!ContextIsFound &&
4914 "null type has been found already for '__context' parameter");
4915 IdentifierInfo *ParamName = &Context.Idents.get(Name: "__context");
4916 QualType ParamType =
4917 Context.getPointerType(T: Context.getCanonicalTagType(TD: RD))
4918 .withConst()
4919 .withRestrict();
4920 auto *Param =
4921 ImplicitParamDecl::Create(C&: Context, DC, IdLoc: Loc, Id: ParamName, T: ParamType,
4922 ParamKind: ImplicitParamKind::CapturedContext);
4923 DC->addDecl(D: Param);
4924 CD->setContextParam(i: ParamNum, P: Param);
4925 ContextIsFound = true;
4926 } else {
4927 IdentifierInfo *ParamName = &Context.Idents.get(Name: I->first);
4928 auto *Param =
4929 ImplicitParamDecl::Create(C&: Context, DC, IdLoc: Loc, Id: ParamName, T: I->second,
4930 ParamKind: ImplicitParamKind::CapturedContext);
4931 DC->addDecl(D: Param);
4932 CD->setParam(i: ParamNum, P: Param);
4933 }
4934 }
4935 assert(ContextIsFound && "no null type for '__context' parameter");
4936 if (!ContextIsFound) {
4937 // Add __context implicitly if it is not specified.
4938 IdentifierInfo *ParamName = &Context.Idents.get(Name: "__context");
4939 CanQualType ParamType =
4940 Context.getPointerType(T: Context.getCanonicalTagType(TD: RD));
4941 auto *Param =
4942 ImplicitParamDecl::Create(C&: Context, DC, IdLoc: Loc, Id: ParamName, T: ParamType,
4943 ParamKind: ImplicitParamKind::CapturedContext);
4944 DC->addDecl(D: Param);
4945 CD->setContextParam(i: ParamNum, P: Param);
4946 }
4947 // Enter the capturing scope for this captured region.
4948 PushCapturedRegionScope(RegionScope: CurScope, CD, RD, K: Kind, OpenMPCaptureLevel);
4949
4950 if (CurScope)
4951 PushDeclContext(S: CurScope, DC: CD);
4952 else
4953 CurContext = CD;
4954
4955 PushExpressionEvaluationContext(
4956 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
4957}
4958
4959void Sema::ActOnCapturedRegionError() {
4960 DiscardCleanupsInEvaluationContext();
4961 PopExpressionEvaluationContext();
4962 PopDeclContext();
4963 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4964 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(Val: ScopeRAII.get());
4965
4966 RecordDecl *Record = RSI->TheRecordDecl;
4967 Record->setInvalidDecl();
4968
4969 SmallVector<Decl*, 4> Fields(Record->fields());
4970 ActOnFields(/*Scope=*/S: nullptr, RecLoc: Record->getLocation(), TagDecl: Record, Fields,
4971 LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView());
4972}
4973
4974StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4975 // Leave the captured scope before we start creating captures in the
4976 // enclosing scope.
4977 DiscardCleanupsInEvaluationContext();
4978 PopExpressionEvaluationContext();
4979 PopDeclContext();
4980 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4981 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(Val: ScopeRAII.get());
4982
4983 SmallVector<CapturedStmt::Capture, 4> Captures;
4984 SmallVector<Expr *, 4> CaptureInits;
4985 if (buildCapturedStmtCaptureList(S&: *this, RSI, Captures, CaptureInits))
4986 return StmtError();
4987
4988 CapturedDecl *CD = RSI->TheCapturedDecl;
4989 RecordDecl *RD = RSI->TheRecordDecl;
4990
4991 CapturedStmt *Res = CapturedStmt::Create(
4992 Context: getASTContext(), S, Kind: static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4993 Captures, CaptureInits, CD, RD);
4994
4995 CD->setBody(Res->getCapturedStmt());
4996 RD->completeDefinition();
4997
4998 return Res;
4999}
5000