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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/Sema/SemaStmt.cpp