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

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