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