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/SemaObjC.h"
39 #include "clang/Sema/SemaOpenMP.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/STLForwardCompat.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/StringExtras.h"
48
49 using namespace clang;
50 using namespace sema;
51
ActOnExprStmt(ExprResult FE,bool DiscardedValue)52 StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
53 if (FE.isInvalid())
54 return StmtError();
55
56 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
57 if (FE.isInvalid())
58 return StmtError();
59
60 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
61 // void expression for its side effects. Conversion to void allows any
62 // operand, even incomplete types.
63
64 // Same thing in for stmt first clause (when expr) and third clause.
65 return StmtResult(FE.getAs<Stmt>());
66 }
67
68
ActOnExprStmtError()69 StmtResult Sema::ActOnExprStmtError() {
70 DiscardCleanupsInEvaluationContext();
71 return StmtError();
72 }
73
ActOnNullStmt(SourceLocation SemiLoc,bool HasLeadingEmptyMacro)74 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
75 bool HasLeadingEmptyMacro) {
76 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
77 }
78
ActOnDeclStmt(DeclGroupPtrTy dg,SourceLocation StartLoc,SourceLocation EndLoc)79 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
80 SourceLocation EndLoc) {
81 DeclGroupRef DG = dg.get();
82
83 // If we have an invalid decl, just return an error.
84 if (DG.isNull()) return StmtError();
85
86 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
87 }
88
ActOnForEachDeclStmt(DeclGroupPtrTy dg)89 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
90 DeclGroupRef DG = dg.get();
91
92 // If we don't have a declaration, or we have an invalid declaration,
93 // just return.
94 if (DG.isNull() || !DG.isSingleDecl())
95 return;
96
97 Decl *decl = DG.getSingleDecl();
98 if (!decl || decl->isInvalidDecl())
99 return;
100
101 // Only variable declarations are permitted.
102 VarDecl *var = dyn_cast<VarDecl>(decl);
103 if (!var) {
104 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
105 decl->setInvalidDecl();
106 return;
107 }
108
109 // foreach variables are never actually initialized in the way that
110 // the parser came up with.
111 var->setInit(nullptr);
112
113 // In ARC, we don't need to retain the iteration variable of a fast
114 // enumeration loop. Rather than actually trying to catch that
115 // during declaration processing, we remove the consequences here.
116 if (getLangOpts().ObjCAutoRefCount) {
117 QualType type = var->getType();
118
119 // Only do this if we inferred the lifetime. Inferred lifetime
120 // will show up as a local qualifier because explicit lifetime
121 // should have shown up as an AttributedType instead.
122 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
123 // Add 'const' and mark the variable as pseudo-strong.
124 var->setType(type.withConst());
125 var->setARCPseudoStrong(true);
126 }
127 }
128 }
129
130 /// Diagnose unused comparisons, both builtin and overloaded operators.
131 /// For '==' and '!=', suggest fixits for '=' or '|='.
132 ///
133 /// Adding a cast to void (or other expression wrappers) will prevent the
134 /// warning from firing.
DiagnoseUnusedComparison(Sema & S,const Expr * E)135 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
136 SourceLocation Loc;
137 bool CanAssign;
138 enum { Equality, Inequality, Relational, ThreeWay } Kind;
139
140 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
141 if (!Op->isComparisonOp())
142 return false;
143
144 if (Op->getOpcode() == BO_EQ)
145 Kind = Equality;
146 else if (Op->getOpcode() == BO_NE)
147 Kind = Inequality;
148 else if (Op->getOpcode() == BO_Cmp)
149 Kind = ThreeWay;
150 else {
151 assert(Op->isRelationalOp());
152 Kind = Relational;
153 }
154 Loc = Op->getOperatorLoc();
155 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
156 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
157 switch (Op->getOperator()) {
158 case OO_EqualEqual:
159 Kind = Equality;
160 break;
161 case OO_ExclaimEqual:
162 Kind = Inequality;
163 break;
164 case OO_Less:
165 case OO_Greater:
166 case OO_GreaterEqual:
167 case OO_LessEqual:
168 Kind = Relational;
169 break;
170 case OO_Spaceship:
171 Kind = ThreeWay;
172 break;
173 default:
174 return false;
175 }
176
177 Loc = Op->getOperatorLoc();
178 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
179 } else {
180 // Not a typo-prone comparison.
181 return false;
182 }
183
184 // Suppress warnings when the operator, suspicious as it may be, comes from
185 // a macro expansion.
186 if (S.SourceMgr.isMacroBodyExpansion(Loc))
187 return false;
188
189 S.Diag(Loc, diag::warn_unused_comparison)
190 << (unsigned)Kind << E->getSourceRange();
191
192 // If the LHS is a plausible entity to assign to, provide a fixit hint to
193 // correct common typos.
194 if (CanAssign) {
195 if (Kind == Inequality)
196 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
197 << FixItHint::CreateReplacement(Loc, "|=");
198 else if (Kind == Equality)
199 S.Diag(Loc, diag::note_equality_comparison_to_assign)
200 << FixItHint::CreateReplacement(Loc, "=");
201 }
202
203 return true;
204 }
205
DiagnoseNoDiscard(Sema & S,const WarnUnusedResultAttr * A,SourceLocation Loc,SourceRange R1,SourceRange R2,bool IsCtor)206 static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
207 SourceLocation Loc, SourceRange R1,
208 SourceRange R2, bool IsCtor) {
209 if (!A)
210 return false;
211 StringRef Msg = A->getMessage();
212
213 if (Msg.empty()) {
214 if (IsCtor)
215 return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
216 return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
217 }
218
219 if (IsCtor)
220 return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
221 << R2;
222 return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
223 }
224
DiagnoseUnusedExprResult(const Stmt * S,unsigned DiagID)225 void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
226 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
227 return DiagnoseUnusedExprResult(Label->getSubStmt(), DiagID);
228
229 const Expr *E = dyn_cast_or_null<Expr>(S);
230 if (!E)
231 return;
232
233 // If we are in an unevaluated expression context, then there can be no unused
234 // results because the results aren't expected to be used in the first place.
235 if (isUnevaluatedContext())
236 return;
237
238 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
239 // In most cases, we don't want to warn if the expression is written in a
240 // macro body, or if the macro comes from a system header. If the offending
241 // expression is a call to a function with the warn_unused_result attribute,
242 // we warn no matter the location. Because of the order in which the various
243 // checks need to happen, we factor out the macro-related test here.
244 bool ShouldSuppress =
245 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
246 SourceMgr.isInSystemMacro(ExprLoc);
247
248 const Expr *WarnExpr;
249 SourceLocation Loc;
250 SourceRange R1, R2;
251 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
252 return;
253
254 // If this is a GNU statement expression expanded from a macro, it is probably
255 // unused because it is a function-like macro that can be used as either an
256 // expression or statement. Don't warn, because it is almost certainly a
257 // false positive.
258 if (isa<StmtExpr>(E) && Loc.isMacroID())
259 return;
260
261 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
262 // That macro is frequently used to suppress "unused parameter" warnings,
263 // but its implementation makes clang's -Wunused-value fire. Prevent this.
264 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
265 SourceLocation SpellLoc = Loc;
266 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
267 return;
268 }
269
270 // Okay, we have an unused result. Depending on what the base expression is,
271 // we might want to make a more specific diagnostic. Check for one of these
272 // cases now.
273 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
274 E = Temps->getSubExpr();
275 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
276 E = TempExpr->getSubExpr();
277
278 if (DiagnoseUnusedComparison(*this, E))
279 return;
280
281 E = WarnExpr;
282 if (const auto *Cast = dyn_cast<CastExpr>(E))
283 if (Cast->getCastKind() == CK_NoOp ||
284 Cast->getCastKind() == CK_ConstructorConversion)
285 E = Cast->getSubExpr()->IgnoreImpCasts();
286
287 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
288 if (E->getType()->isVoidType())
289 return;
290
291 if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
292 CE->getUnusedResultAttr(Context)),
293 Loc, R1, R2, /*isCtor=*/false))
294 return;
295
296 // If the callee has attribute pure, const, or warn_unused_result, warn with
297 // a more specific message to make it clear what is happening. If the call
298 // is written in a macro body, only warn if it has the warn_unused_result
299 // attribute.
300 if (const Decl *FD = CE->getCalleeDecl()) {
301 if (ShouldSuppress)
302 return;
303 if (FD->hasAttr<PureAttr>()) {
304 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
305 return;
306 }
307 if (FD->hasAttr<ConstAttr>()) {
308 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
309 return;
310 }
311 }
312 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
313 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
314 const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
315 A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
316 if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
317 return;
318 }
319 } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
320 if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
321
322 if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
323 R2, /*isCtor=*/false))
324 return;
325 }
326 } else if (ShouldSuppress)
327 return;
328
329 E = WarnExpr;
330 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
331 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
332 Diag(Loc, diag::err_arc_unused_init_message) << R1;
333 return;
334 }
335 const ObjCMethodDecl *MD = ME->getMethodDecl();
336 if (MD) {
337 if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
338 R2, /*isCtor=*/false))
339 return;
340 }
341 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
342 const Expr *Source = POE->getSyntacticForm();
343 // Handle the actually selected call of an OpenMP specialized call.
344 if (LangOpts.OpenMP && isa<CallExpr>(Source) &&
345 POE->getNumSemanticExprs() == 1 &&
346 isa<CallExpr>(POE->getSemanticExpr(0)))
347 return DiagnoseUnusedExprResult(POE->getSemanticExpr(0), DiagID);
348 if (isa<ObjCSubscriptRefExpr>(Source))
349 DiagID = diag::warn_unused_container_subscript_expr;
350 else if (isa<ObjCPropertyRefExpr>(Source))
351 DiagID = diag::warn_unused_property_expr;
352 } else if (const CXXFunctionalCastExpr *FC
353 = dyn_cast<CXXFunctionalCastExpr>(E)) {
354 const Expr *E = FC->getSubExpr();
355 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
356 E = TE->getSubExpr();
357 if (isa<CXXTemporaryObjectExpr>(E))
358 return;
359 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
360 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
361 if (!RD->getAttr<WarnUnusedAttr>())
362 return;
363 }
364 // Diagnose "(void*) blah" as a typo for "(void) blah".
365 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
366 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
367 QualType T = TI->getType();
368
369 // We really do want to use the non-canonical type here.
370 if (T == Context.VoidPtrTy) {
371 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
372
373 Diag(Loc, diag::warn_unused_voidptr)
374 << FixItHint::CreateRemoval(TL.getStarLoc());
375 return;
376 }
377 }
378
379 // Tell the user to assign it into a variable to force a volatile load if this
380 // isn't an array.
381 if (E->isGLValue() && E->getType().isVolatileQualified() &&
382 !E->getType()->isArrayType()) {
383 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
384 return;
385 }
386
387 // Do not diagnose use of a comma operator in a SFINAE context because the
388 // type of the left operand could be used for SFINAE, so technically it is
389 // *used*.
390 if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
391 DiagIfReachable(Loc, S ? llvm::ArrayRef(S) : std::nullopt,
392 PDiag(DiagID) << R1 << R2);
393 }
394
ActOnStartOfCompoundStmt(bool IsStmtExpr)395 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
396 PushCompoundScope(IsStmtExpr);
397 }
398
ActOnAfterCompoundStatementLeadingPragmas()399 void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
400 if (getCurFPFeatures().isFPConstrained()) {
401 FunctionScopeInfo *FSI = getCurFunction();
402 assert(FSI);
403 FSI->setUsesFPIntrin();
404 }
405 }
406
ActOnFinishOfCompoundStmt()407 void Sema::ActOnFinishOfCompoundStmt() {
408 PopCompoundScope();
409 }
410
getCurCompoundScope() const411 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
412 return getCurFunction()->CompoundScopes.back();
413 }
414
ActOnCompoundStmt(SourceLocation L,SourceLocation R,ArrayRef<Stmt * > Elts,bool isStmtExpr)415 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
416 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
417 const unsigned NumElts = Elts.size();
418
419 // If we're in C mode, check that we don't have any decls after stmts. If
420 // so, emit an extension diagnostic in C89 and potentially a warning in later
421 // versions.
422 const unsigned MixedDeclsCodeID = getLangOpts().C99
423 ? diag::warn_mixed_decls_code
424 : diag::ext_mixed_decls_code;
425 if (!getLangOpts().CPlusPlus && !Diags.isIgnored(MixedDeclsCodeID, L)) {
426 // Note that __extension__ can be around a decl.
427 unsigned i = 0;
428 // Skip over all declarations.
429 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
430 /*empty*/;
431
432 // We found the end of the list or a statement. Scan for another declstmt.
433 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
434 /*empty*/;
435
436 if (i != NumElts) {
437 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
438 Diag(D->getLocation(), MixedDeclsCodeID);
439 }
440 }
441
442 // Check for suspicious empty body (null statement) in `for' and `while'
443 // statements. Don't do anything for template instantiations, this just adds
444 // noise.
445 if (NumElts != 0 && !CurrentInstantiationScope &&
446 getCurCompoundScope().HasEmptyLoopBodies) {
447 for (unsigned i = 0; i != NumElts - 1; ++i)
448 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
449 }
450
451 // Calculate difference between FP options in this compound statement and in
452 // the enclosing one. If this is a function body, take the difference against
453 // default options. In this case the difference will indicate options that are
454 // changed upon entry to the statement.
455 FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1)
456 ? FPOptions(getLangOpts())
457 : getCurCompoundScope().InitialFPFeatures;
458 FPOptionsOverride FPDiff = getCurFPFeatures().getChangesFrom(FPO);
459
460 return CompoundStmt::Create(Context, Elts, FPDiff, L, R);
461 }
462
463 ExprResult
ActOnCaseExpr(SourceLocation CaseLoc,ExprResult Val)464 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
465 if (!Val.get())
466 return Val;
467
468 if (DiagnoseUnexpandedParameterPack(Val.get()))
469 return ExprError();
470
471 // If we're not inside a switch, let the 'case' statement handling diagnose
472 // this. Just clean up after the expression as best we can.
473 if (getCurFunction()->SwitchStack.empty())
474 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
475 getLangOpts().CPlusPlus11);
476
477 Expr *CondExpr =
478 getCurFunction()->SwitchStack.back().getPointer()->getCond();
479 if (!CondExpr)
480 return ExprError();
481 QualType CondType = CondExpr->getType();
482
483 auto CheckAndFinish = [&](Expr *E) {
484 if (CondType->isDependentType() || E->isTypeDependent())
485 return ExprResult(E);
486
487 if (getLangOpts().CPlusPlus11) {
488 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
489 // constant expression of the promoted type of the switch condition.
490 llvm::APSInt TempVal;
491 return CheckConvertedConstantExpression(E, CondType, TempVal,
492 CCEK_CaseValue);
493 }
494
495 ExprResult ER = E;
496 if (!E->isValueDependent())
497 ER = VerifyIntegerConstantExpression(E, AllowFold);
498 if (!ER.isInvalid())
499 ER = DefaultLvalueConversion(ER.get());
500 if (!ER.isInvalid())
501 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
502 if (!ER.isInvalid())
503 ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
504 return ER;
505 };
506
507 ExprResult Converted = CorrectDelayedTyposInExpr(
508 Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
509 CheckAndFinish);
510 if (Converted.get() == Val.get())
511 Converted = CheckAndFinish(Val.get());
512 return Converted;
513 }
514
515 StmtResult
ActOnCaseStmt(SourceLocation CaseLoc,ExprResult LHSVal,SourceLocation DotDotDotLoc,ExprResult RHSVal,SourceLocation ColonLoc)516 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
517 SourceLocation DotDotDotLoc, ExprResult RHSVal,
518 SourceLocation ColonLoc) {
519 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
520 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
521 : RHSVal.isInvalid() || RHSVal.get()) &&
522 "missing RHS value");
523
524 if (getCurFunction()->SwitchStack.empty()) {
525 Diag(CaseLoc, diag::err_case_not_in_switch);
526 return StmtError();
527 }
528
529 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
530 getCurFunction()->SwitchStack.back().setInt(true);
531 return StmtError();
532 }
533
534 if (LangOpts.OpenACC &&
535 getCurScope()->isInOpenACCComputeConstructScope(Scope::SwitchScope)) {
536 Diag(CaseLoc, diag::err_acc_branch_in_out_compute_construct)
537 << /*branch*/ 0 << /*into*/ 1;
538 return StmtError();
539 }
540
541 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
542 CaseLoc, DotDotDotLoc, ColonLoc);
543 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
544 return CS;
545 }
546
ActOnCaseStmtBody(Stmt * S,Stmt * SubStmt)547 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
548 cast<CaseStmt>(S)->setSubStmt(SubStmt);
549 }
550
551 StmtResult
ActOnDefaultStmt(SourceLocation DefaultLoc,SourceLocation ColonLoc,Stmt * SubStmt,Scope * CurScope)552 Sema::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(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(DS);
568 return DS;
569 }
570
571 StmtResult
ActOnLabelStmt(SourceLocation IdentLoc,LabelDecl * TheDecl,SourceLocation ColonLoc,Stmt * SubStmt)572 Sema::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
BuildAttributedStmt(SourceLocation AttrsLoc,ArrayRef<const Attr * > Attrs,Stmt * SubStmt)606 StmtResult 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(SubStmt, *A)) {
614 return SubStmt;
615 }
616 setFunctionHasMustTail();
617 }
618 }
619
620 return AttributedStmt::Create(Context, AttrsLoc, Attrs, SubStmt);
621 }
622
ActOnAttributedStmt(const ParsedAttributes & Attrs,Stmt * SubStmt)623 StmtResult Sema::ActOnAttributedStmt(const ParsedAttributes &Attrs,
624 Stmt *SubStmt) {
625 SmallVector<const Attr *, 1> SemanticAttrs;
626 ProcessStmtAttributes(SubStmt, Attrs, SemanticAttrs);
627 if (!SemanticAttrs.empty())
628 return BuildAttributedStmt(Attrs.Range.getBegin(), 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
checkAndRewriteMustTailAttr(Stmt * St,const Attr & MTA)635 bool Sema::checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA) {
636 ReturnStmt *R = cast<ReturnStmt>(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, IgnoreImplicitAsWrittenSingleStep,
651 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
checkMustTailAttr(const Stmt * St,const Attr & MTA)660 bool 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(const_cast<Expr *>(E), IgnoreParensSingleStep,
667 IgnoreImplicitAsWrittenSingleStep,
668 IgnoreElidableImplicitConstructorSingleStep);
669 };
670
671 const Expr *E = cast<ReturnStmt>(St)->getRetValue();
672 const auto *CE = dyn_cast_or_null<CallExpr>(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>(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>(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>(CurContext);
723
724 // Find caller function signature.
725 if (!CallerDecl) {
726 int ContextType;
727 if (isa<BlockDecl>(CurContext))
728 ContextType = 0;
729 else if (isa<ObjCMethodDecl>(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>(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>(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>(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>(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>(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(A, 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
894 namespace {
895 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
896 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
897 Sema &SemaRef;
898 public:
CommaVisitor(Sema & SemaRef)899 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
VisitBinaryOperator(BinaryOperator * E)900 void VisitBinaryOperator(BinaryOperator *E) {
901 if (E->getOpcode() == BO_Comma)
902 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
903 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
904 }
905 };
906 }
907
ActOnIfStmt(SourceLocation IfLoc,IfStatementKind StatementKind,SourceLocation LParenLoc,Stmt * InitStmt,ConditionResult Cond,SourceLocation RParenLoc,Stmt * thenStmt,SourceLocation ElseLoc,Stmt * elseStmt)908 StmtResult 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(thenStmt, elseStmt);
953 if (std::get<0>(LHC)) {
954 const Attr *ThenAttr = std::get<1>(LHC);
955 const Attr *ElseAttr = std::get<2>(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>(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 thenStmt, ElseLoc, elseStmt);
979 }
980
BuildIfStmt(SourceLocation IfLoc,IfStatementKind StatementKind,SourceLocation LParenLoc,Stmt * InitStmt,ConditionResult Cond,SourceLocation RParenLoc,Stmt * thenStmt,SourceLocation ElseLoc,Stmt * elseStmt)981 StmtResult 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>(Cond.get().second))
992 setFunctionHasBranchProtectedScope();
993
994 return IfStmt::Create(Context, IfLoc, StatementKind, InitStmt,
995 Cond.get().first, Cond.get().second, LParenLoc,
996 RParenLoc, thenStmt, ElseLoc, elseStmt);
997 }
998
999 namespace {
1000 struct CaseCompareFunctor {
operator ()__anon4f6f6e9d0c11::CaseCompareFunctor1001 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
1002 const llvm::APSInt &RHS) {
1003 return LHS.first < RHS;
1004 }
operator ()__anon4f6f6e9d0c11::CaseCompareFunctor1005 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
1006 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
1007 return LHS.first < RHS.first;
1008 }
operator ()__anon4f6f6e9d0c11::CaseCompareFunctor1009 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 ///
CmpCaseVals(const std::pair<llvm::APSInt,CaseStmt * > & lhs,const std::pair<llvm::APSInt,CaseStmt * > & rhs)1018 static 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 ///
CmpEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)1031 static 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 ///
EqEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)1039 static 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.
GetTypeBeforeIntegralPromotion(const Expr * & E)1047 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
1048 if (const auto *FE = dyn_cast<FullExpr>(E))
1049 E = FE->getSubExpr();
1050 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
1051 if (ImpCast->getCastKind() != CK_IntegralCast) break;
1052 E = ImpCast->getSubExpr();
1053 }
1054 return E->getType();
1055 }
1056
CheckSwitchCondition(SourceLocation SwitchLoc,Expr * Cond)1057 ExprResult 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(SwitchLoc, Cond, 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(Cond);
1119 }
1120
ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,SourceLocation LParenLoc,Stmt * InitStmt,ConditionResult Cond,SourceLocation RParenLoc)1121 StmtResult 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(Context, InitStmt, Cond.get().first, CondExpr,
1147 LParenLoc, RParenLoc);
1148 getCurFunction()->SwitchStack.push_back(
1149 FunctionScopeInfo::SwitchInfo(SS, false));
1150 return SS;
1151 }
1152
AdjustAPSInt(llvm::APSInt & Val,unsigned BitWidth,bool IsSigned)1153 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
1154 Val = Val.extOrTrunc(BitWidth);
1155 Val.setIsSigned(IsSigned);
1156 }
1157
1158 /// Check the specified case value is in range for the given unpromoted switch
1159 /// type.
checkCaseValue(Sema & S,SourceLocation Loc,const llvm::APSInt & Val,unsigned UnpromotedWidth,bool UnpromotedSign)1160 static 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(ConvVal, UnpromotedWidth, UnpromotedSign);
1172 AdjustAPSInt(ConvVal, Val.getBitWidth(), 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
1182 typedef 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.
ShouldDiagnoseSwitchCaseNotInEnum(const Sema & S,const EnumDecl * ED,const Expr * CaseExpr,EnumValsTy::iterator & EI,EnumValsTy::iterator & EIEnd,const llvm::APSInt & Val)1186 static 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>(CaseExpr->IgnoreParenImpCasts())) {
1197 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1198 QualType VarType = VD->getType();
1199 QualType EnumType = S.Context.getTypeDeclType(ED);
1200 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
1201 S.Context.hasSameUnqualifiedType(EnumType, VarType))
1202 return false;
1203 }
1204 }
1205
1206 if (ED->hasAttr<FlagEnumAttr>())
1207 return !S.IsValueInFlagEnum(ED, Val, 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
checkEnumTypesInSwitchStmt(Sema & S,const Expr * Cond,const Expr * Case)1218 static 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(CondType, 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
1244 StmtResult
ActOnFinishSwitchStmt(SourceLocation SwitchLoc,Stmt * Switch,Stmt * BodyStmt)1245 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
1246 Stmt *BodyStmt) {
1247 SwitchStmt *SS = cast<SwitchStmt>(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(BodyStmt, 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(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(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(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>(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>(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(LoBeforePromotion);
1336 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(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(*this, CondExprBeforePromotion,
1345 LoBeforePromotion);
1346
1347 // Convert the value to the same width/sign as the condition.
1348 AdjustAPSInt(LoVal, CondWidth, 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(std::make_pair(LoVal, CS));
1357 } else
1358 CaseVals.push_back(std::make_pair(LoVal, 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, Context,
1370 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(CaseVals, 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>(PrevCase)) {
1396 PrevString = DeclRef->getDecl()->getName();
1397 }
1398 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
1399 CurrString = DeclRef->getDecl()->getName();
1400 }
1401 SmallString<16> CaseValStr;
1402 CaseVals[i-1].first.toString(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(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(HiBeforePromotion);
1440 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(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(HiVal, CondWidth, 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(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(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(CaseVals, CRLo, 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(I, CaseVals.end(), CRHi, 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, CondWidth, CondIsSigned);
1546 EnumVals.push_back(std::make_pair(Val, EDI));
1547 }
1548 llvm::stable_sort(EnumVals, CmpEnumVals);
1549 auto EI = EnumVals.begin(), EIEnd =
1550 std::unique(EnumVals.begin(), EnumVals.end(), 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(Context);
1574 AdjustAPSInt(Hi, CondWidth, 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(Context);
1619 AdjustAPSInt(Hi, CondWidth, 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(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(UnhandledNames.size(), (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
1662 void
DiagnoseAssignmentEnum(QualType DstType,QualType SrcType,Expr * SrcExpr)1663 Sema::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(SrcType, DstType) &&
1670 SrcType->isIntegerType()) {
1671 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1672 SrcExpr->isIntegerConstantExpr(Context)) {
1673 // Get the bitwidth of the enum value before promotions.
1674 unsigned DstWidth = Context.getIntWidth(DstType);
1675 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1676
1677 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1678 AdjustAPSInt(RhsVal, DstWidth, 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, DstWidth, DstIsSigned);
1698 EnumVals.push_back(std::make_pair(Val, EDI));
1699 }
1700 if (EnumVals.empty())
1701 return;
1702 llvm::stable_sort(EnumVals, CmpEnumVals);
1703 EnumValsTy::iterator EIend =
1704 std::unique(EnumVals.begin(), EnumVals.end(), 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
ActOnWhileStmt(SourceLocation WhileLoc,SourceLocation LParenLoc,ConditionResult Cond,SourceLocation RParenLoc,Stmt * Body)1719 StmtResult 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(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>(Body))
1733 getCurCompoundScope().setHasEmptyLoopBodies();
1734
1735 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1736 WhileLoc, LParenLoc, RParenLoc);
1737 }
1738
1739 StmtResult
ActOnDoStmt(SourceLocation DoLoc,Stmt * Body,SourceLocation WhileLoc,SourceLocation CondLParen,Expr * Cond,SourceLocation CondRParen)1740 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1741 SourceLocation WhileLoc, SourceLocation CondLParen,
1742 Expr *Cond, SourceLocation CondRParen) {
1743 assert(Cond && "ActOnDoStmt(): missing expression");
1744
1745 CheckBreakContinueBinding(Cond);
1746 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1747 if (CondResult.isInvalid())
1748 return StmtError();
1749 Cond = CondResult.get();
1750
1751 CondResult = ActOnFinishFullExpr(Cond, 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
1764 namespace {
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
DeclExtractor(Sema & S,DeclSetVector & Decls,SmallVectorImpl<SourceRange> & Ranges)1778 DeclExtractor(Sema &S, DeclSetVector &Decls,
1779 SmallVectorImpl<SourceRange> &Ranges) :
1780 Inherited(S.Context),
1781 Decls(Decls),
1782 Ranges(Ranges),
1783 Simple(true) {}
1784
isSimple()1785 bool isSimple() { return Simple; }
1786
1787 // Replaces the method in EvaluatedExprVisitor.
VisitMemberExpr(MemberExpr * E)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.
VisitStmt(Stmt * S)1794 void VisitStmt(Stmt *S) { Simple = false; }
1795
VisitBinaryOperator(BinaryOperator * E)1796 void VisitBinaryOperator(BinaryOperator *E) {
1797 Visit(E->getLHS());
1798 Visit(E->getRHS());
1799 }
1800
VisitCastExpr(CastExpr * E)1801 void VisitCastExpr(CastExpr *E) {
1802 Visit(E->getSubExpr());
1803 }
1804
VisitUnaryOperator(UnaryOperator * E)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
VisitConditionalOperator(ConditionalOperator * E)1813 void VisitConditionalOperator(ConditionalOperator *E) {
1814 Visit(E->getCond());
1815 Visit(E->getTrueExpr());
1816 Visit(E->getFalseExpr());
1817 }
1818
VisitParenExpr(ParenExpr * E)1819 void VisitParenExpr(ParenExpr *E) {
1820 Visit(E->getSubExpr());
1821 }
1822
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)1823 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1824 Visit(E->getOpaqueValue()->getSourceExpr());
1825 Visit(E->getFalseExpr());
1826 }
1827
VisitIntegerLiteral(IntegerLiteral * E)1828 void VisitIntegerLiteral(IntegerLiteral *E) { }
VisitFloatingLiteral(FloatingLiteral * E)1829 void VisitFloatingLiteral(FloatingLiteral *E) { }
VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr * E)1830 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
VisitCharacterLiteral(CharacterLiteral * E)1831 void VisitCharacterLiteral(CharacterLiteral *E) { }
VisitGNUNullExpr(GNUNullExpr * E)1832 void VisitGNUNullExpr(GNUNullExpr *E) { }
VisitImaginaryLiteral(ImaginaryLiteral * E)1833 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1834
VisitDeclRefExpr(DeclRefExpr * E)1835 void VisitDeclRefExpr(DeclRefExpr *E) {
1836 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1837 if (!VD) {
1838 // Don't allow unhandled Decl types.
1839 Simple = false;
1840 return;
1841 }
1842
1843 Ranges.push_back(E->getSourceRange());
1844
1845 Decls.insert(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
DeclMatcher(Sema & S,DeclSetVector & Decls,Stmt * Statement)1859 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1860 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1861 if (!Statement) return;
1862
1863 Visit(Statement);
1864 }
1865
VisitReturnStmt(ReturnStmt * S)1866 void VisitReturnStmt(ReturnStmt *S) {
1867 FoundDecl = true;
1868 }
1869
VisitBreakStmt(BreakStmt * S)1870 void VisitBreakStmt(BreakStmt *S) {
1871 FoundDecl = true;
1872 }
1873
VisitGotoStmt(GotoStmt * S)1874 void VisitGotoStmt(GotoStmt *S) {
1875 FoundDecl = true;
1876 }
1877
VisitCastExpr(CastExpr * E)1878 void VisitCastExpr(CastExpr *E) {
1879 if (E->getCastKind() == CK_LValueToRValue)
1880 CheckLValueToRValueCast(E->getSubExpr());
1881 else
1882 Visit(E->getSubExpr());
1883 }
1884
CheckLValueToRValueCast(Expr * E)1885 void CheckLValueToRValueCast(Expr *E) {
1886 E = E->IgnoreParenImpCasts();
1887
1888 if (isa<DeclRefExpr>(E)) {
1889 return;
1890 }
1891
1892 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1893 Visit(CO->getCond());
1894 CheckLValueToRValueCast(CO->getTrueExpr());
1895 CheckLValueToRValueCast(CO->getFalseExpr());
1896 return;
1897 }
1898
1899 if (BinaryConditionalOperator *BCO =
1900 dyn_cast<BinaryConditionalOperator>(E)) {
1901 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1902 CheckLValueToRValueCast(BCO->getFalseExpr());
1903 return;
1904 }
1905
1906 Visit(E);
1907 }
1908
VisitDeclRefExpr(DeclRefExpr * E)1909 void VisitDeclRefExpr(DeclRefExpr *E) {
1910 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1911 if (Decls.count(VD))
1912 FoundDecl = true;
1913 }
1914
VisitPseudoObjectExpr(PseudoObjectExpr * POE)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>(S))
1920 // Look past the OVE into the expression it binds.
1921 Visit(OVE->getSourceExpr());
1922 else
1923 Visit(S);
1924 }
1925 }
1926
FoundDeclInUse()1927 bool FoundDeclInUse() { return FoundDecl; }
1928
1929 }; // end class DeclMatcher
1930
CheckForLoopConditionalStatement(Sema & S,Expr * Second,Expr * Third,Stmt * Body)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.
ProcessIterationStmt(Sema & S,Stmt * Statement,bool & Increment,DeclRefExpr * & DRE)1979 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1980 DeclRefExpr *&DRE) {
1981 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1982 if (!Cleanups->cleanupsHaveSideEffects())
1983 Statement = Cleanups->getSubExpr();
1984
1985 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(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>(UO->getSubExpr());
1998 return DRE;
1999 }
2000
2001 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(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:
BreakContinueFinder(Sema & S,const Stmt * Body)2028 BreakContinueFinder(Sema &S, const Stmt* Body) :
2029 Inherited(S.Context) {
2030 Visit(Body);
2031 }
2032
2033 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
2034
VisitContinueStmt(const ContinueStmt * E)2035 void VisitContinueStmt(const ContinueStmt* E) {
2036 ContinueLoc = E->getContinueLoc();
2037 }
2038
VisitBreakStmt(const BreakStmt * E)2039 void VisitBreakStmt(const BreakStmt* E) {
2040 if (!InSwitch)
2041 BreakLoc = E->getBreakLoc();
2042 }
2043
VisitSwitchStmt(const SwitchStmt * S)2044 void VisitSwitchStmt(const SwitchStmt* S) {
2045 if (const Stmt *Init = S->getInit())
2046 Visit(Init);
2047 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
2048 Visit(CondVar);
2049 if (const Stmt *Cond = S->getCond())
2050 Visit(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(Body);
2056 InSwitch = false;
2057 }
2058
VisitForStmt(const ForStmt * S)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(Init);
2064 }
2065
VisitWhileStmt(const WhileStmt *)2066 void VisitWhileStmt(const WhileStmt *) {
2067 // Do nothing; the children of a while loop have a different
2068 // break/continue scope.
2069 }
2070
VisitDoStmt(const DoStmt *)2071 void VisitDoStmt(const DoStmt *) {
2072 // Do nothing; the children of a while loop have a different
2073 // break/continue scope.
2074 }
2075
VisitCXXForRangeStmt(const CXXForRangeStmt * S)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(Init);
2081 if (const Stmt *Range = S->getRangeStmt())
2082 Visit(Range);
2083 if (const Stmt *Begin = S->getBeginStmt())
2084 Visit(Begin);
2085 if (const Stmt *End = S->getEndStmt())
2086 Visit(End);
2087 }
2088
VisitObjCForCollectionStmt(const ObjCForCollectionStmt * S)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(Element);
2094 if (const Stmt *Collection = S->getCollection())
2095 Visit(Collection);
2096 }
2097
ContinueFound()2098 bool ContinueFound() { return ContinueLoc.isValid(); }
BreakFound()2099 bool BreakFound() { return BreakLoc.isValid(); }
GetContinueLoc()2100 SourceLocation GetContinueLoc() { return ContinueLoc; }
GetBreakLoc()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.
CheckForRedundantIteration(Sema & S,Expr * Third,Stmt * 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>(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, LastStmt, LastIncrement, 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
CheckBreakContinueBinding(Expr * E)2146 void 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
ActOnForStmt(SourceLocation ForLoc,SourceLocation LParenLoc,Stmt * First,ConditionResult Second,FullExprArg third,SourceLocation RParenLoc,Stmt * Body)2164 StmtResult 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>(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>(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(Second.get().second);
2201 CheckBreakContinueBinding(third.get());
2202
2203 if (!Second.get().first)
2204 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
2205 Body);
2206 CheckForRedundantIteration(*this, 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>(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
ActOnForEachLValueExpr(Expr * E)2222 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
2223 // Reduce placeholder expressions here. Note that this rejects the
2224 // use of pseudo-object l-values in this position.
2225 ExprResult result = CheckPlaceholderExpr(E);
2226 if (result.isInvalid()) return StmtError();
2227 E = result.get();
2228
2229 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2230 if (FullExpr.isInvalid())
2231 return StmtError();
2232 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
2233 }
2234
2235 /// Finish building a variable declaration for a for-range statement.
2236 /// \return true if an error occurs.
FinishForRangeVarDecl(Sema & SemaRef,VarDecl * Decl,Expr * Init,SourceLocation Loc,int DiagID)2237 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
2238 SourceLocation Loc, int DiagID) {
2239 if (Decl->getType()->isUndeducedType()) {
2240 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
2241 if (!Res.isUsable()) {
2242 Decl->setInvalidDecl();
2243 return true;
2244 }
2245 Init = Res.get();
2246 }
2247
2248 // Deduce the type for the iterator variable now rather than leaving it to
2249 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2250 QualType InitType;
2251 if (!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) {
2252 SemaRef.Diag(Loc, DiagID) << Init->getType();
2253 } else {
2254 TemplateDeductionInfo Info(Init->getExprLoc());
2255 TemplateDeductionResult Result = SemaRef.DeduceAutoType(
2256 Decl->getTypeSourceInfo()->getTypeLoc(), Init, InitType, Info);
2257 if (Result != TemplateDeductionResult::Success &&
2258 Result != TemplateDeductionResult::AlreadyDiagnosed)
2259 SemaRef.Diag(Loc, DiagID) << Init->getType();
2260 }
2261
2262 if (InitType.isNull()) {
2263 Decl->setInvalidDecl();
2264 return true;
2265 }
2266 Decl->setType(InitType);
2267
2268 // In ARC, infer lifetime.
2269 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2270 // we're doing the equivalent of fast iteration.
2271 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2272 SemaRef.ObjC().inferObjCARCLifetime(Decl))
2273 Decl->setInvalidDecl();
2274
2275 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
2276 SemaRef.FinalizeDeclaration(Decl);
2277 SemaRef.CurContext->addHiddenDecl(Decl);
2278 return false;
2279 }
2280
2281 namespace {
2282 // An enum to represent whether something is dealing with a call to begin()
2283 // or a call to end() in a range-based for loop.
2284 enum BeginEndFunction {
2285 BEF_begin,
2286 BEF_end
2287 };
2288
2289 /// Produce a note indicating which begin/end function was implicitly called
2290 /// by a C++11 for-range statement. This is often not obvious from the code,
2291 /// nor from the diagnostics produced when analysing the implicit expressions
2292 /// required in a for-range statement.
NoteForRangeBeginEndFunction(Sema & SemaRef,Expr * E,BeginEndFunction BEF)2293 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2294 BeginEndFunction BEF) {
2295 CallExpr *CE = dyn_cast<CallExpr>(E);
2296 if (!CE)
2297 return;
2298 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2299 if (!D)
2300 return;
2301 SourceLocation Loc = D->getLocation();
2302
2303 std::string Description;
2304 bool IsTemplate = false;
2305 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2306 Description = SemaRef.getTemplateArgumentBindingsText(
2307 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2308 IsTemplate = true;
2309 }
2310
2311 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2312 << BEF << IsTemplate << Description << E->getType();
2313 }
2314
2315 /// Build a variable declaration for a for-range statement.
BuildForRangeVarDecl(Sema & SemaRef,SourceLocation Loc,QualType Type,StringRef Name)2316 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2317 QualType Type, StringRef Name) {
2318 DeclContext *DC = SemaRef.CurContext;
2319 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2320 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2321 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2322 TInfo, SC_None);
2323 Decl->setImplicit();
2324 return Decl;
2325 }
2326
2327 }
2328
ObjCEnumerationCollection(Expr * Collection)2329 static bool ObjCEnumerationCollection(Expr *Collection) {
2330 return !Collection->isTypeDependent()
2331 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2332 }
2333
ActOnCXXForRangeStmt(Scope * S,SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * InitStmt,Stmt * First,SourceLocation ColonLoc,Expr * Range,SourceLocation RParenLoc,BuildForRangeKind Kind,ArrayRef<MaterializeTemporaryExpr * > LifetimeExtendTemps)2334 StmtResult Sema::ActOnCXXForRangeStmt(
2335 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2336 Stmt *First, SourceLocation ColonLoc, Expr *Range, SourceLocation RParenLoc,
2337 BuildForRangeKind Kind,
2338 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2339 // FIXME: recover in order to allow the body to be parsed.
2340 if (!First)
2341 return StmtError();
2342
2343 if (Range && ObjCEnumerationCollection(Range)) {
2344 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2345 if (InitStmt)
2346 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2347 << InitStmt->getSourceRange();
2348 return ObjC().ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2349 }
2350
2351 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2352 assert(DS && "first part of for range not a decl stmt");
2353
2354 if (!DS->isSingleDecl()) {
2355 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2356 return StmtError();
2357 }
2358
2359 // This function is responsible for attaching an initializer to LoopVar. We
2360 // must call ActOnInitializerError if we fail to do so.
2361 Decl *LoopVar = DS->getSingleDecl();
2362 if (LoopVar->isInvalidDecl() || !Range ||
2363 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2364 ActOnInitializerError(LoopVar);
2365 return StmtError();
2366 }
2367
2368 // Build the coroutine state immediately and not later during template
2369 // instantiation
2370 if (!CoawaitLoc.isInvalid()) {
2371 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) {
2372 ActOnInitializerError(LoopVar);
2373 return StmtError();
2374 }
2375 }
2376
2377 // Build auto && __range = range-init
2378 // Divide by 2, since the variables are in the inner scope (loop body).
2379 const auto DepthStr = std::to_string(S->getDepth() / 2);
2380 SourceLocation RangeLoc = Range->getBeginLoc();
2381 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2382 Context.getAutoRRefDeductType(),
2383 std::string("__range") + DepthStr);
2384 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2385 diag::err_for_range_deduction_failure)) {
2386 ActOnInitializerError(LoopVar);
2387 return StmtError();
2388 }
2389
2390 // Claim the type doesn't contain auto: we've already done the checking.
2391 DeclGroupPtrTy RangeGroup =
2392 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2393 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2394 if (RangeDecl.isInvalid()) {
2395 ActOnInitializerError(LoopVar);
2396 return StmtError();
2397 }
2398
2399 StmtResult R = BuildCXXForRangeStmt(
2400 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2401 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2402 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind,
2403 LifetimeExtendTemps);
2404 if (R.isInvalid()) {
2405 ActOnInitializerError(LoopVar);
2406 return StmtError();
2407 }
2408
2409 return R;
2410 }
2411
2412 /// Create the initialization, compare, and increment steps for
2413 /// the range-based for loop expression.
2414 /// This function does not handle array-based for loops,
2415 /// which are created in Sema::BuildCXXForRangeStmt.
2416 ///
2417 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2418 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2419 /// CandidateSet and BEF are set and some non-success value is returned on
2420 /// failure.
2421 static Sema::ForRangeStatus
BuildNonArrayForRange(Sema & SemaRef,Expr * BeginRange,Expr * EndRange,QualType RangeType,VarDecl * BeginVar,VarDecl * EndVar,SourceLocation ColonLoc,SourceLocation CoawaitLoc,OverloadCandidateSet * CandidateSet,ExprResult * BeginExpr,ExprResult * EndExpr,BeginEndFunction * BEF)2422 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2423 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2424 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2425 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2426 ExprResult *EndExpr, BeginEndFunction *BEF) {
2427 DeclarationNameInfo BeginNameInfo(
2428 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2429 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2430 ColonLoc);
2431
2432 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2433 Sema::LookupMemberName);
2434 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2435
2436 auto BuildBegin = [&] {
2437 *BEF = BEF_begin;
2438 Sema::ForRangeStatus RangeStatus =
2439 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2440 BeginMemberLookup, CandidateSet,
2441 BeginRange, BeginExpr);
2442
2443 if (RangeStatus != Sema::FRS_Success) {
2444 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2445 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2446 << ColonLoc << BEF_begin << BeginRange->getType();
2447 return RangeStatus;
2448 }
2449 if (!CoawaitLoc.isInvalid()) {
2450 // FIXME: getCurScope() should not be used during template instantiation.
2451 // We should pick up the set of unqualified lookup results for operator
2452 // co_await during the initial parse.
2453 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2454 BeginExpr->get());
2455 if (BeginExpr->isInvalid())
2456 return Sema::FRS_DiagnosticIssued;
2457 }
2458 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2459 diag::err_for_range_iter_deduction_failure)) {
2460 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2461 return Sema::FRS_DiagnosticIssued;
2462 }
2463 return Sema::FRS_Success;
2464 };
2465
2466 auto BuildEnd = [&] {
2467 *BEF = BEF_end;
2468 Sema::ForRangeStatus RangeStatus =
2469 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2470 EndMemberLookup, CandidateSet,
2471 EndRange, EndExpr);
2472 if (RangeStatus != Sema::FRS_Success) {
2473 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2474 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2475 << ColonLoc << BEF_end << EndRange->getType();
2476 return RangeStatus;
2477 }
2478 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2479 diag::err_for_range_iter_deduction_failure)) {
2480 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2481 return Sema::FRS_DiagnosticIssued;
2482 }
2483 return Sema::FRS_Success;
2484 };
2485
2486 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2487 // - if _RangeT is a class type, the unqualified-ids begin and end are
2488 // looked up in the scope of class _RangeT as if by class member access
2489 // lookup (3.4.5), and if either (or both) finds at least one
2490 // declaration, begin-expr and end-expr are __range.begin() and
2491 // __range.end(), respectively;
2492 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2493 if (BeginMemberLookup.isAmbiguous())
2494 return Sema::FRS_DiagnosticIssued;
2495
2496 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2497 if (EndMemberLookup.isAmbiguous())
2498 return Sema::FRS_DiagnosticIssued;
2499
2500 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2501 // Look up the non-member form of the member we didn't find, first.
2502 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2503 // a 'begin' but ignored it because there was no member 'end'"
2504 // diagnostic.
2505 auto BuildNonmember = [&](
2506 BeginEndFunction BEFFound, LookupResult &Found,
2507 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2508 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2509 LookupResult OldFound = std::move(Found);
2510 Found.clear();
2511
2512 if (Sema::ForRangeStatus Result = BuildNotFound())
2513 return Result;
2514
2515 switch (BuildFound()) {
2516 case Sema::FRS_Success:
2517 return Sema::FRS_Success;
2518
2519 case Sema::FRS_NoViableFunction:
2520 CandidateSet->NoteCandidates(
2521 PartialDiagnosticAt(BeginRange->getBeginLoc(),
2522 SemaRef.PDiag(diag::err_for_range_invalid)
2523 << BeginRange->getType() << BEFFound),
2524 SemaRef, OCD_AllCandidates, BeginRange);
2525 [[fallthrough]];
2526
2527 case Sema::FRS_DiagnosticIssued:
2528 for (NamedDecl *D : OldFound) {
2529 SemaRef.Diag(D->getLocation(),
2530 diag::note_for_range_member_begin_end_ignored)
2531 << BeginRange->getType() << BEFFound;
2532 }
2533 return Sema::FRS_DiagnosticIssued;
2534 }
2535 llvm_unreachable("unexpected ForRangeStatus");
2536 };
2537 if (BeginMemberLookup.empty())
2538 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2539 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2540 }
2541 } else {
2542 // - otherwise, begin-expr and end-expr are begin(__range) and
2543 // end(__range), respectively, where begin and end are looked up with
2544 // argument-dependent lookup (3.4.2). For the purposes of this name
2545 // lookup, namespace std is an associated namespace.
2546 }
2547
2548 if (Sema::ForRangeStatus Result = BuildBegin())
2549 return Result;
2550 return BuildEnd();
2551 }
2552
2553 /// Speculatively attempt to dereference an invalid range expression.
2554 /// If the attempt fails, this function will return a valid, null StmtResult
2555 /// and emit no diagnostics.
RebuildForRangeWithDereference(Sema & SemaRef,Scope * S,SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * InitStmt,Stmt * LoopVarDecl,SourceLocation ColonLoc,Expr * Range,SourceLocation RangeLoc,SourceLocation RParenLoc)2556 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2557 SourceLocation ForLoc,
2558 SourceLocation CoawaitLoc,
2559 Stmt *InitStmt,
2560 Stmt *LoopVarDecl,
2561 SourceLocation ColonLoc,
2562 Expr *Range,
2563 SourceLocation RangeLoc,
2564 SourceLocation RParenLoc) {
2565 // Determine whether we can rebuild the for-range statement with a
2566 // dereferenced range expression.
2567 ExprResult AdjustedRange;
2568 {
2569 Sema::SFINAETrap Trap(SemaRef);
2570
2571 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2572 if (AdjustedRange.isInvalid())
2573 return StmtResult();
2574
2575 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2576 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2577 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2578 if (SR.isInvalid())
2579 return StmtResult();
2580 }
2581
2582 // The attempt to dereference worked well enough that it could produce a valid
2583 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2584 // case there are any other (non-fatal) problems with it.
2585 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2586 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2587 return SemaRef.ActOnCXXForRangeStmt(
2588 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2589 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2590 }
2591
BuildCXXForRangeStmt(SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * InitStmt,SourceLocation ColonLoc,Stmt * RangeDecl,Stmt * Begin,Stmt * End,Expr * Cond,Expr * Inc,Stmt * LoopVarDecl,SourceLocation RParenLoc,BuildForRangeKind Kind,ArrayRef<MaterializeTemporaryExpr * > LifetimeExtendTemps)2592 StmtResult Sema::BuildCXXForRangeStmt(
2593 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2594 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
2595 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
2596 BuildForRangeKind Kind,
2597 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2598 // FIXME: This should not be used during template instantiation. We should
2599 // pick up the set of unqualified lookup results for the != and + operators
2600 // in the initial parse.
2601 //
2602 // Testcase (accepts-invalid):
2603 // template<typename T> void f() { for (auto x : T()) {} }
2604 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2605 // bool operator!=(N::X, N::X); void operator++(N::X);
2606 // void g() { f<N::X>(); }
2607 Scope *S = getCurScope();
2608
2609 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2610 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2611 QualType RangeVarType = RangeVar->getType();
2612
2613 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2614 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2615
2616 StmtResult BeginDeclStmt = Begin;
2617 StmtResult EndDeclStmt = End;
2618 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2619
2620 if (RangeVarType->isDependentType()) {
2621 // The range is implicitly used as a placeholder when it is dependent.
2622 RangeVar->markUsed(Context);
2623
2624 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2625 // them in properly when we instantiate the loop.
2626 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2627 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2628 for (auto *Binding : DD->bindings())
2629 Binding->setType(Context.DependentTy);
2630 LoopVar->setType(SubstAutoTypeDependent(LoopVar->getType()));
2631 }
2632 } else if (!BeginDeclStmt.get()) {
2633 SourceLocation RangeLoc = RangeVar->getLocation();
2634
2635 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2636
2637 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2638 VK_LValue, ColonLoc);
2639 if (BeginRangeRef.isInvalid())
2640 return StmtError();
2641
2642 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2643 VK_LValue, ColonLoc);
2644 if (EndRangeRef.isInvalid())
2645 return StmtError();
2646
2647 QualType AutoType = Context.getAutoDeductType();
2648 Expr *Range = RangeVar->getInit();
2649 if (!Range)
2650 return StmtError();
2651 QualType RangeType = Range->getType();
2652
2653 if (RequireCompleteType(RangeLoc, RangeType,
2654 diag::err_for_range_incomplete_type))
2655 return StmtError();
2656
2657 // P2718R0 - Lifetime extension in range-based for loops.
2658 if (getLangOpts().CPlusPlus23 && !LifetimeExtendTemps.empty()) {
2659 InitializedEntity Entity =
2660 InitializedEntity::InitializeVariable(RangeVar);
2661 for (auto *MTE : LifetimeExtendTemps)
2662 MTE->setExtendingDecl(RangeVar, Entity.allocateManglingNumber());
2663 }
2664
2665 // Build auto __begin = begin-expr, __end = end-expr.
2666 // Divide by 2, since the variables are in the inner scope (loop body).
2667 const auto DepthStr = std::to_string(S->getDepth() / 2);
2668 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2669 std::string("__begin") + DepthStr);
2670 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2671 std::string("__end") + DepthStr);
2672
2673 // Build begin-expr and end-expr and attach to __begin and __end variables.
2674 ExprResult BeginExpr, EndExpr;
2675 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2676 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2677 // __range + __bound, respectively, where __bound is the array bound. If
2678 // _RangeT is an array of unknown size or an array of incomplete type,
2679 // the program is ill-formed;
2680
2681 // begin-expr is __range.
2682 BeginExpr = BeginRangeRef;
2683 if (!CoawaitLoc.isInvalid()) {
2684 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2685 if (BeginExpr.isInvalid())
2686 return StmtError();
2687 }
2688 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2689 diag::err_for_range_iter_deduction_failure)) {
2690 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2691 return StmtError();
2692 }
2693
2694 // Find the array bound.
2695 ExprResult BoundExpr;
2696 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2697 BoundExpr = IntegerLiteral::Create(
2698 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2699 else if (const VariableArrayType *VAT =
2700 dyn_cast<VariableArrayType>(UnqAT)) {
2701 // For a variably modified type we can't just use the expression within
2702 // the array bounds, since we don't want that to be re-evaluated here.
2703 // Rather, we need to determine what it was when the array was first
2704 // created - so we resort to using sizeof(vla)/sizeof(element).
2705 // For e.g.
2706 // void f(int b) {
2707 // int vla[b];
2708 // b = -1; <-- This should not affect the num of iterations below
2709 // for (int &c : vla) { .. }
2710 // }
2711
2712 // FIXME: This results in codegen generating IR that recalculates the
2713 // run-time number of elements (as opposed to just using the IR Value
2714 // that corresponds to the run-time value of each bound that was
2715 // generated when the array was created.) If this proves too embarrassing
2716 // even for unoptimized IR, consider passing a magic-value/cookie to
2717 // codegen that then knows to simply use that initial llvm::Value (that
2718 // corresponds to the bound at time of array creation) within
2719 // getelementptr. But be prepared to pay the price of increasing a
2720 // customized form of coupling between the two components - which could
2721 // be hard to maintain as the codebase evolves.
2722
2723 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2724 EndVar->getLocation(), UETT_SizeOf,
2725 /*IsType=*/true,
2726 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2727 VAT->desugar(), RangeLoc))
2728 .getAsOpaquePtr(),
2729 EndVar->getSourceRange());
2730 if (SizeOfVLAExprR.isInvalid())
2731 return StmtError();
2732
2733 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2734 EndVar->getLocation(), UETT_SizeOf,
2735 /*IsType=*/true,
2736 CreateParsedType(VAT->desugar(),
2737 Context.getTrivialTypeSourceInfo(
2738 VAT->getElementType(), RangeLoc))
2739 .getAsOpaquePtr(),
2740 EndVar->getSourceRange());
2741 if (SizeOfEachElementExprR.isInvalid())
2742 return StmtError();
2743
2744 BoundExpr =
2745 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2746 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2747 if (BoundExpr.isInvalid())
2748 return StmtError();
2749
2750 } else {
2751 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2752 // UnqAT is not incomplete and Range is not type-dependent.
2753 llvm_unreachable("Unexpected array type in for-range");
2754 }
2755
2756 // end-expr is __range + __bound.
2757 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2758 BoundExpr.get());
2759 if (EndExpr.isInvalid())
2760 return StmtError();
2761 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2762 diag::err_for_range_iter_deduction_failure)) {
2763 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2764 return StmtError();
2765 }
2766 } else {
2767 OverloadCandidateSet CandidateSet(RangeLoc,
2768 OverloadCandidateSet::CSK_Normal);
2769 BeginEndFunction BEFFailure;
2770 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2771 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2772 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2773 &BEFFailure);
2774
2775 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2776 BEFFailure == BEF_begin) {
2777 // If the range is being built from an array parameter, emit a
2778 // a diagnostic that it is being treated as a pointer.
2779 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2780 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2781 QualType ArrayTy = PVD->getOriginalType();
2782 QualType PointerTy = PVD->getType();
2783 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2784 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2785 << RangeLoc << PVD << ArrayTy << PointerTy;
2786 Diag(PVD->getLocation(), diag::note_declared_at);
2787 return StmtError();
2788 }
2789 }
2790 }
2791
2792 // If building the range failed, try dereferencing the range expression
2793 // unless a diagnostic was issued or the end function is problematic.
2794 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2795 CoawaitLoc, InitStmt,
2796 LoopVarDecl, ColonLoc,
2797 Range, RangeLoc,
2798 RParenLoc);
2799 if (SR.isInvalid() || SR.isUsable())
2800 return SR;
2801 }
2802
2803 // Otherwise, emit diagnostics if we haven't already.
2804 if (RangeStatus == FRS_NoViableFunction) {
2805 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2806 CandidateSet.NoteCandidates(
2807 PartialDiagnosticAt(Range->getBeginLoc(),
2808 PDiag(diag::err_for_range_invalid)
2809 << RangeLoc << Range->getType()
2810 << BEFFailure),
2811 *this, OCD_AllCandidates, Range);
2812 }
2813 // Return an error if no fix was discovered.
2814 if (RangeStatus != FRS_Success)
2815 return StmtError();
2816 }
2817
2818 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2819 "invalid range expression in for loop");
2820
2821 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2822 // C++1z removes this restriction.
2823 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2824 if (!Context.hasSameType(BeginType, EndType)) {
2825 Diag(RangeLoc, getLangOpts().CPlusPlus17
2826 ? diag::warn_for_range_begin_end_types_differ
2827 : diag::ext_for_range_begin_end_types_differ)
2828 << BeginType << EndType;
2829 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2830 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2831 }
2832
2833 BeginDeclStmt =
2834 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2835 EndDeclStmt =
2836 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2837
2838 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2839 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2840 VK_LValue, ColonLoc);
2841 if (BeginRef.isInvalid())
2842 return StmtError();
2843
2844 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2845 VK_LValue, ColonLoc);
2846 if (EndRef.isInvalid())
2847 return StmtError();
2848
2849 // Build and check __begin != __end expression.
2850 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2851 BeginRef.get(), EndRef.get());
2852 if (!NotEqExpr.isInvalid())
2853 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2854 if (!NotEqExpr.isInvalid())
2855 NotEqExpr =
2856 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2857 if (NotEqExpr.isInvalid()) {
2858 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2859 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2860 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2861 if (!Context.hasSameType(BeginType, EndType))
2862 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2863 return StmtError();
2864 }
2865
2866 // Build and check ++__begin expression.
2867 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2868 VK_LValue, ColonLoc);
2869 if (BeginRef.isInvalid())
2870 return StmtError();
2871
2872 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2873 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2874 // FIXME: getCurScope() should not be used during template instantiation.
2875 // We should pick up the set of unqualified lookup results for operator
2876 // co_await during the initial parse.
2877 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2878 if (!IncrExpr.isInvalid())
2879 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2880 if (IncrExpr.isInvalid()) {
2881 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2882 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2883 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2884 return StmtError();
2885 }
2886
2887 // Build and check *__begin expression.
2888 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2889 VK_LValue, ColonLoc);
2890 if (BeginRef.isInvalid())
2891 return StmtError();
2892
2893 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2894 if (DerefExpr.isInvalid()) {
2895 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2896 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2897 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2898 return StmtError();
2899 }
2900
2901 // Attach *__begin as initializer for VD. Don't touch it if we're just
2902 // trying to determine whether this would be a valid range.
2903 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2904 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2905 if (LoopVar->isInvalidDecl() ||
2906 (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
2907 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2908 }
2909 }
2910
2911 // Don't bother to actually allocate the result if we're just trying to
2912 // determine whether it would be valid.
2913 if (Kind == BFRK_Check)
2914 return StmtResult();
2915
2916 // In OpenMP loop region loop control variable must be private. Perform
2917 // analysis of first part (if any).
2918 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
2919 OpenMP().ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
2920
2921 return new (Context) CXXForRangeStmt(
2922 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2923 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2924 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2925 ColonLoc, RParenLoc);
2926 }
2927
2928 // Warn when the loop variable is a const reference that creates a copy.
2929 // Suggest using the non-reference type for copies. If a copy can be prevented
2930 // suggest the const reference type that would do so.
2931 // For instance, given "for (const &Foo : Range)", suggest
2932 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2933 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2934 // the copy altogether.
DiagnoseForRangeReferenceVariableCopies(Sema & SemaRef,const VarDecl * VD,QualType RangeInitType)2935 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2936 const VarDecl *VD,
2937 QualType RangeInitType) {
2938 const Expr *InitExpr = VD->getInit();
2939 if (!InitExpr)
2940 return;
2941
2942 QualType VariableType = VD->getType();
2943
2944 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2945 if (!Cleanups->cleanupsHaveSideEffects())
2946 InitExpr = Cleanups->getSubExpr();
2947
2948 const MaterializeTemporaryExpr *MTE =
2949 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2950
2951 // No copy made.
2952 if (!MTE)
2953 return;
2954
2955 const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
2956
2957 // Searching for either UnaryOperator for dereference of a pointer or
2958 // CXXOperatorCallExpr for handling iterators.
2959 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2960 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2961 E = CCE->getArg(0);
2962 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2963 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2964 E = ME->getBase();
2965 } else {
2966 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2967 E = MTE->getSubExpr();
2968 }
2969 E = E->IgnoreImpCasts();
2970 }
2971
2972 QualType ReferenceReturnType;
2973 if (isa<UnaryOperator>(E)) {
2974 ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
2975 } else {
2976 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2977 const FunctionDecl *FD = Call->getDirectCallee();
2978 QualType ReturnType = FD->getReturnType();
2979 if (ReturnType->isReferenceType())
2980 ReferenceReturnType = ReturnType;
2981 }
2982
2983 if (!ReferenceReturnType.isNull()) {
2984 // Loop variable creates a temporary. Suggest either to go with
2985 // non-reference loop variable to indicate a copy is made, or
2986 // the correct type to bind a const reference.
2987 SemaRef.Diag(VD->getLocation(),
2988 diag::warn_for_range_const_ref_binds_temp_built_from_ref)
2989 << VD << VariableType << ReferenceReturnType;
2990 QualType NonReferenceType = VariableType.getNonReferenceType();
2991 NonReferenceType.removeLocalConst();
2992 QualType NewReferenceType =
2993 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2994 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2995 << NonReferenceType << NewReferenceType << VD->getSourceRange()
2996 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
2997 } else if (!VariableType->isRValueReferenceType()) {
2998 // The range always returns a copy, so a temporary is always created.
2999 // Suggest removing the reference from the loop variable.
3000 // If the type is a rvalue reference do not warn since that changes the
3001 // semantic of the code.
3002 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
3003 << VD << RangeInitType;
3004 QualType NonReferenceType = VariableType.getNonReferenceType();
3005 NonReferenceType.removeLocalConst();
3006 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
3007 << NonReferenceType << VD->getSourceRange()
3008 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3009 }
3010 }
3011
3012 /// Determines whether the @p VariableType's declaration is a record with the
3013 /// clang::trivial_abi attribute.
hasTrivialABIAttr(QualType VariableType)3014 static bool hasTrivialABIAttr(QualType VariableType) {
3015 if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
3016 return RD->hasAttr<TrivialABIAttr>();
3017
3018 return false;
3019 }
3020
3021 // Warns when the loop variable can be changed to a reference type to
3022 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
3023 // "for (const Foo &x : Range)" if this form does not make a copy.
DiagnoseForRangeConstVariableCopies(Sema & SemaRef,const VarDecl * VD)3024 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
3025 const VarDecl *VD) {
3026 const Expr *InitExpr = VD->getInit();
3027 if (!InitExpr)
3028 return;
3029
3030 QualType VariableType = VD->getType();
3031
3032 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
3033 if (!CE->getConstructor()->isCopyConstructor())
3034 return;
3035 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
3036 if (CE->getCastKind() != CK_LValueToRValue)
3037 return;
3038 } else {
3039 return;
3040 }
3041
3042 // Small trivially copyable types are cheap to copy. Do not emit the
3043 // diagnostic for these instances. 64 bytes is a common size of a cache line.
3044 // (The function `getTypeSize` returns the size in bits.)
3045 ASTContext &Ctx = SemaRef.Context;
3046 if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
3047 (VariableType.isTriviallyCopyConstructibleType(Ctx) ||
3048 hasTrivialABIAttr(VariableType)))
3049 return;
3050
3051 // Suggest changing from a const variable to a const reference variable
3052 // if doing so will prevent a copy.
3053 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
3054 << VD << VariableType;
3055 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
3056 << SemaRef.Context.getLValueReferenceType(VariableType)
3057 << VD->getSourceRange()
3058 << FixItHint::CreateInsertion(VD->getLocation(), "&");
3059 }
3060
3061 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3062 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
3063 /// using "const foo x" to show that a copy is made
3064 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3065 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
3066 /// prevent the copy.
3067 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
3068 /// Suggest "const foo &x" to prevent the copy.
DiagnoseForRangeVariableCopies(Sema & SemaRef,const CXXForRangeStmt * ForStmt)3069 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
3070 const CXXForRangeStmt *ForStmt) {
3071 if (SemaRef.inTemplateInstantiation())
3072 return;
3073
3074 if (SemaRef.Diags.isIgnored(
3075 diag::warn_for_range_const_ref_binds_temp_built_from_ref,
3076 ForStmt->getBeginLoc()) &&
3077 SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
3078 ForStmt->getBeginLoc()) &&
3079 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
3080 ForStmt->getBeginLoc())) {
3081 return;
3082 }
3083
3084 const VarDecl *VD = ForStmt->getLoopVariable();
3085 if (!VD)
3086 return;
3087
3088 QualType VariableType = VD->getType();
3089
3090 if (VariableType->isIncompleteType())
3091 return;
3092
3093 const Expr *InitExpr = VD->getInit();
3094 if (!InitExpr)
3095 return;
3096
3097 if (InitExpr->getExprLoc().isMacroID())
3098 return;
3099
3100 if (VariableType->isReferenceType()) {
3101 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
3102 ForStmt->getRangeInit()->getType());
3103 } else if (VariableType.isConstQualified()) {
3104 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
3105 }
3106 }
3107
FinishCXXForRangeStmt(Stmt * S,Stmt * B)3108 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
3109 if (!S || !B)
3110 return StmtError();
3111
3112 if (isa<ObjCForCollectionStmt>(S))
3113 return ObjC().FinishObjCForCollectionStmt(S, B);
3114
3115 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
3116 ForStmt->setBody(B);
3117
3118 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
3119 diag::warn_empty_range_based_for_body);
3120
3121 DiagnoseForRangeVariableCopies(*this, ForStmt);
3122
3123 return S;
3124 }
3125
ActOnGotoStmt(SourceLocation GotoLoc,SourceLocation LabelLoc,LabelDecl * TheDecl)3126 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
3127 SourceLocation LabelLoc,
3128 LabelDecl *TheDecl) {
3129 setFunctionHasBranchIntoScope();
3130
3131 // If this goto is in a compute construct scope, we need to make sure we check
3132 // gotos in/out.
3133 if (getCurScope()->isInOpenACCComputeConstructScope())
3134 setFunctionHasBranchProtectedScope();
3135
3136 TheDecl->markUsed(Context);
3137 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
3138 }
3139
3140 StmtResult
ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,Expr * E)3141 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
3142 Expr *E) {
3143 // Convert operand to void*
3144 if (!E->isTypeDependent()) {
3145 QualType ETy = E->getType();
3146 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
3147 ExprResult ExprRes = E;
3148 AssignConvertType ConvTy =
3149 CheckSingleAssignmentConstraints(DestTy, ExprRes);
3150 if (ExprRes.isInvalid())
3151 return StmtError();
3152 E = ExprRes.get();
3153 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
3154 return StmtError();
3155 }
3156
3157 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
3158 if (ExprRes.isInvalid())
3159 return StmtError();
3160 E = ExprRes.get();
3161
3162 setFunctionHasIndirectGoto();
3163
3164 // If this goto is in a compute construct scope, we need to make sure we
3165 // check gotos in/out.
3166 if (getCurScope()->isInOpenACCComputeConstructScope())
3167 setFunctionHasBranchProtectedScope();
3168
3169 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
3170 }
3171
CheckJumpOutOfSEHFinally(Sema & S,SourceLocation Loc,const Scope & DestScope)3172 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
3173 const Scope &DestScope) {
3174 if (!S.CurrentSEHFinally.empty() &&
3175 DestScope.Contains(*S.CurrentSEHFinally.back())) {
3176 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
3177 }
3178 }
3179
3180 StmtResult
ActOnContinueStmt(SourceLocation ContinueLoc,Scope * CurScope)3181 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
3182 Scope *S = CurScope->getContinueParent();
3183 if (!S) {
3184 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3185 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
3186 }
3187 if (S->isConditionVarScope()) {
3188 // We cannot 'continue;' from within a statement expression in the
3189 // initializer of a condition variable because we would jump past the
3190 // initialization of that variable.
3191 return StmtError(Diag(ContinueLoc, diag::err_continue_from_cond_var_init));
3192 }
3193
3194 // A 'continue' that would normally have execution continue on a block outside
3195 // of a compute construct counts as 'branching out of' the compute construct,
3196 // so diagnose here.
3197 if (S->isOpenACCComputeConstructScope())
3198 return StmtError(
3199 Diag(ContinueLoc, diag::err_acc_branch_in_out_compute_construct)
3200 << /*branch*/ 0 << /*out of */ 0);
3201
3202 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
3203
3204 return new (Context) ContinueStmt(ContinueLoc);
3205 }
3206
3207 StmtResult
ActOnBreakStmt(SourceLocation BreakLoc,Scope * CurScope)3208 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
3209 Scope *S = CurScope->getBreakParent();
3210 if (!S) {
3211 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3212 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
3213 }
3214 if (S->isOpenMPLoopScope())
3215 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
3216 << "break");
3217
3218 // OpenACC doesn't allow 'break'ing from a compute construct, so diagnose if
3219 // we are trying to do so. This can come in 2 flavors: 1-the break'able thing
3220 // (besides the compute construct) 'contains' the compute construct, at which
3221 // point the 'break' scope will be the compute construct. Else it could be a
3222 // loop of some sort that has a direct parent of the compute construct.
3223 // However, a 'break' in a 'switch' marked as a compute construct doesn't
3224 // count as 'branch out of' the compute construct.
3225 if (S->isOpenACCComputeConstructScope() ||
3226 (S->isLoopScope() && S->getParent() &&
3227 S->getParent()->isOpenACCComputeConstructScope()))
3228 return StmtError(
3229 Diag(BreakLoc, diag::err_acc_branch_in_out_compute_construct)
3230 << /*branch*/ 0 << /*out of */ 0);
3231
3232 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
3233
3234 return new (Context) BreakStmt(BreakLoc);
3235 }
3236
getNamedReturnInfo(Expr * & E,SimplerImplicitMoveMode Mode)3237 Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *&E,
3238 SimplerImplicitMoveMode Mode) {
3239 if (!E)
3240 return NamedReturnInfo();
3241 // - in a return statement in a function [where] ...
3242 // ... the expression is the name of a non-volatile automatic object ...
3243 const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
3244 if (!DR || DR->refersToEnclosingVariableOrCapture())
3245 return NamedReturnInfo();
3246 const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
3247 if (!VD)
3248 return NamedReturnInfo();
3249 if (VD->getInit() && VD->getInit()->containsErrors())
3250 return NamedReturnInfo();
3251 NamedReturnInfo Res = getNamedReturnInfo(VD);
3252 if (Res.Candidate && !E->isXValue() &&
3253 (Mode == SimplerImplicitMoveMode::ForceOn ||
3254 (Mode != SimplerImplicitMoveMode::ForceOff &&
3255 getLangOpts().CPlusPlus23))) {
3256 E = ImplicitCastExpr::Create(Context, VD->getType().getNonReferenceType(),
3257 CK_NoOp, E, nullptr, VK_XValue,
3258 FPOptionsOverride());
3259 }
3260 return Res;
3261 }
3262
getNamedReturnInfo(const VarDecl * VD)3263 Sema::NamedReturnInfo Sema::getNamedReturnInfo(const VarDecl *VD) {
3264 NamedReturnInfo Info{VD, NamedReturnInfo::MoveEligibleAndCopyElidable};
3265
3266 // C++20 [class.copy.elision]p3:
3267 // - in a return statement in a function with ...
3268 // (other than a function ... parameter)
3269 if (VD->getKind() == Decl::ParmVar)
3270 Info.S = NamedReturnInfo::MoveEligible;
3271 else if (VD->getKind() != Decl::Var)
3272 return NamedReturnInfo();
3273
3274 // (other than ... a catch-clause parameter)
3275 if (VD->isExceptionVariable())
3276 Info.S = NamedReturnInfo::MoveEligible;
3277
3278 // ...automatic...
3279 if (!VD->hasLocalStorage())
3280 return NamedReturnInfo();
3281
3282 // We don't want to implicitly move out of a __block variable during a return
3283 // because we cannot assume the variable will no longer be used.
3284 if (VD->hasAttr<BlocksAttr>())
3285 return NamedReturnInfo();
3286
3287 QualType VDType = VD->getType();
3288 if (VDType->isObjectType()) {
3289 // C++17 [class.copy.elision]p3:
3290 // ...non-volatile automatic object...
3291 if (VDType.isVolatileQualified())
3292 return NamedReturnInfo();
3293 } else if (VDType->isRValueReferenceType()) {
3294 // C++20 [class.copy.elision]p3:
3295 // ...either a non-volatile object or an rvalue reference to a non-volatile
3296 // object type...
3297 QualType VDReferencedType = VDType.getNonReferenceType();
3298 if (VDReferencedType.isVolatileQualified() ||
3299 !VDReferencedType->isObjectType())
3300 return NamedReturnInfo();
3301 Info.S = NamedReturnInfo::MoveEligible;
3302 } else {
3303 return NamedReturnInfo();
3304 }
3305
3306 // Variables with higher required alignment than their type's ABI
3307 // alignment cannot use NRVO.
3308 if (!VD->hasDependentAlignment() && !VDType->isIncompleteType() &&
3309 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VDType))
3310 Info.S = NamedReturnInfo::MoveEligible;
3311
3312 return Info;
3313 }
3314
getCopyElisionCandidate(NamedReturnInfo & Info,QualType ReturnType)3315 const VarDecl *Sema::getCopyElisionCandidate(NamedReturnInfo &Info,
3316 QualType ReturnType) {
3317 if (!Info.Candidate)
3318 return nullptr;
3319
3320 auto invalidNRVO = [&] {
3321 Info = NamedReturnInfo();
3322 return nullptr;
3323 };
3324
3325 // If we got a non-deduced auto ReturnType, we are in a dependent context and
3326 // there is no point in allowing copy elision since we won't have it deduced
3327 // by the point the VardDecl is instantiated, which is the last chance we have
3328 // of deciding if the candidate is really copy elidable.
3329 if ((ReturnType->getTypeClass() == Type::TypeClass::Auto &&
3330 ReturnType->isCanonicalUnqualified()) ||
3331 ReturnType->isSpecificBuiltinType(BuiltinType::Dependent))
3332 return invalidNRVO();
3333
3334 if (!ReturnType->isDependentType()) {
3335 // - in a return statement in a function with ...
3336 // ... a class return type ...
3337 if (!ReturnType->isRecordType())
3338 return invalidNRVO();
3339
3340 QualType VDType = Info.Candidate->getType();
3341 // ... the same cv-unqualified type as the function return type ...
3342 // When considering moving this expression out, allow dissimilar types.
3343 if (!VDType->isDependentType() &&
3344 !Context.hasSameUnqualifiedType(ReturnType, VDType))
3345 Info.S = NamedReturnInfo::MoveEligible;
3346 }
3347 return Info.isCopyElidable() ? Info.Candidate : nullptr;
3348 }
3349
3350 /// Verify that the initialization sequence that was picked for the
3351 /// first overload resolution is permissible under C++98.
3352 ///
3353 /// Reject (possibly converting) constructors not taking an rvalue reference,
3354 /// or user conversion operators which are not ref-qualified.
3355 static bool
VerifyInitializationSequenceCXX98(const Sema & S,const InitializationSequence & Seq)3356 VerifyInitializationSequenceCXX98(const Sema &S,
3357 const InitializationSequence &Seq) {
3358 const auto *Step = llvm::find_if(Seq.steps(), [](const auto &Step) {
3359 return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3360 Step.Kind == InitializationSequence::SK_UserConversion;
3361 });
3362 if (Step != Seq.step_end()) {
3363 const auto *FD = Step->Function.Function;
3364 if (isa<CXXConstructorDecl>(FD)
3365 ? !FD->getParamDecl(0)->getType()->isRValueReferenceType()
3366 : cast<CXXMethodDecl>(FD)->getRefQualifier() == RQ_None)
3367 return false;
3368 }
3369 return true;
3370 }
3371
PerformMoveOrCopyInitialization(const InitializedEntity & Entity,const NamedReturnInfo & NRInfo,Expr * Value,bool SupressSimplerImplicitMoves)3372 ExprResult Sema::PerformMoveOrCopyInitialization(
3373 const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value,
3374 bool SupressSimplerImplicitMoves) {
3375 if (getLangOpts().CPlusPlus &&
3376 (!getLangOpts().CPlusPlus23 || SupressSimplerImplicitMoves) &&
3377 NRInfo.isMoveEligible()) {
3378 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3379 CK_NoOp, Value, VK_XValue, FPOptionsOverride());
3380 Expr *InitExpr = &AsRvalue;
3381 auto Kind = InitializationKind::CreateCopy(Value->getBeginLoc(),
3382 Value->getBeginLoc());
3383 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3384 auto Res = Seq.getFailedOverloadResult();
3385 if ((Res == OR_Success || Res == OR_Deleted) &&
3386 (getLangOpts().CPlusPlus11 ||
3387 VerifyInitializationSequenceCXX98(*this, Seq))) {
3388 // Promote "AsRvalue" to the heap, since we now need this
3389 // expression node to persist.
3390 Value =
3391 ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp, Value,
3392 nullptr, VK_XValue, FPOptionsOverride());
3393 // Complete type-checking the initialization of the return type
3394 // using the constructor we found.
3395 return Seq.Perform(*this, Entity, Kind, Value);
3396 }
3397 }
3398 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3399 // above, or overload resolution failed. Either way, we need to try
3400 // (again) now with the return value expression as written.
3401 return PerformCopyInitialization(Entity, SourceLocation(), Value);
3402 }
3403
3404 /// Determine whether the declared return type of the specified function
3405 /// contains 'auto'.
hasDeducedReturnType(FunctionDecl * FD)3406 static bool hasDeducedReturnType(FunctionDecl *FD) {
3407 const FunctionProtoType *FPT =
3408 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3409 return FPT->getReturnType()->isUndeducedType();
3410 }
3411
ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,NamedReturnInfo & NRInfo,bool SupressSimplerImplicitMoves)3412 StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,
3413 Expr *RetValExp,
3414 NamedReturnInfo &NRInfo,
3415 bool SupressSimplerImplicitMoves) {
3416 // If this is the first return we've seen, infer the return type.
3417 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3418 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3419 QualType FnRetType = CurCap->ReturnType;
3420 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3421 if (CurLambda && CurLambda->CallOperator->getType().isNull())
3422 return StmtError();
3423 bool HasDeducedReturnType =
3424 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3425
3426 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3427 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3428 if (RetValExp) {
3429 ExprResult ER =
3430 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3431 if (ER.isInvalid())
3432 return StmtError();
3433 RetValExp = ER.get();
3434 }
3435 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3436 /* NRVOCandidate=*/nullptr);
3437 }
3438
3439 if (HasDeducedReturnType) {
3440 FunctionDecl *FD = CurLambda->CallOperator;
3441 // If we've already decided this lambda is invalid, e.g. because
3442 // we saw a `return` whose expression had an error, don't keep
3443 // trying to deduce its return type.
3444 if (FD->isInvalidDecl())
3445 return StmtError();
3446 // In C++1y, the return type may involve 'auto'.
3447 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3448 if (CurCap->ReturnType.isNull())
3449 CurCap->ReturnType = FD->getReturnType();
3450
3451 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3452 assert(AT && "lost auto type from lambda return type");
3453 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3454 FD->setInvalidDecl();
3455 // FIXME: preserve the ill-formed return expression.
3456 return StmtError();
3457 }
3458 CurCap->ReturnType = FnRetType = FD->getReturnType();
3459 } else if (CurCap->HasImplicitReturnType) {
3460 // For blocks/lambdas with implicit return types, we check each return
3461 // statement individually, and deduce the common return type when the block
3462 // or lambda is completed.
3463 // FIXME: Fold this into the 'auto' codepath above.
3464 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3465 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3466 if (Result.isInvalid())
3467 return StmtError();
3468 RetValExp = Result.get();
3469
3470 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3471 // when deducing a return type for a lambda-expression (or by extension
3472 // for a block). These rules differ from the stated C++11 rules only in
3473 // that they remove top-level cv-qualifiers.
3474 if (!CurContext->isDependentContext())
3475 FnRetType = RetValExp->getType().getUnqualifiedType();
3476 else
3477 FnRetType = CurCap->ReturnType = Context.DependentTy;
3478 } else {
3479 if (RetValExp) {
3480 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3481 // initializer list, because it is not an expression (even
3482 // though we represent it as one). We still deduce 'void'.
3483 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3484 << RetValExp->getSourceRange();
3485 }
3486
3487 FnRetType = Context.VoidTy;
3488 }
3489
3490 // Although we'll properly infer the type of the block once it's completed,
3491 // make sure we provide a return type now for better error recovery.
3492 if (CurCap->ReturnType.isNull())
3493 CurCap->ReturnType = FnRetType;
3494 }
3495 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
3496
3497 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3498 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
3499 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3500 return StmtError();
3501 }
3502 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3503 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3504 return StmtError();
3505 } else {
3506 assert(CurLambda && "unknown kind of captured scope");
3507 if (CurLambda->CallOperator->getType()
3508 ->castAs<FunctionType>()
3509 ->getNoReturnAttr()) {
3510 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3511 return StmtError();
3512 }
3513 }
3514
3515 // Otherwise, verify that this result type matches the previous one. We are
3516 // pickier with blocks than for normal functions because we don't have GCC
3517 // compatibility to worry about here.
3518 if (FnRetType->isDependentType()) {
3519 // Delay processing for now. TODO: there are lots of dependent
3520 // types we can conclusively prove aren't void.
3521 } else if (FnRetType->isVoidType()) {
3522 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3523 !(getLangOpts().CPlusPlus &&
3524 (RetValExp->isTypeDependent() ||
3525 RetValExp->getType()->isVoidType()))) {
3526 if (!getLangOpts().CPlusPlus &&
3527 RetValExp->getType()->isVoidType())
3528 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3529 else {
3530 Diag(ReturnLoc, diag::err_return_block_has_expr);
3531 RetValExp = nullptr;
3532 }
3533 }
3534 } else if (!RetValExp) {
3535 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3536 } else if (!RetValExp->isTypeDependent()) {
3537 // we have a non-void block with an expression, continue checking
3538
3539 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3540 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3541 // function return.
3542
3543 // In C++ the return statement is handled via a copy initialization.
3544 // the C version of which boils down to CheckSingleAssignmentConstraints.
3545 InitializedEntity Entity =
3546 InitializedEntity::InitializeResult(ReturnLoc, FnRetType);
3547 ExprResult Res = PerformMoveOrCopyInitialization(
3548 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
3549 if (Res.isInvalid()) {
3550 // FIXME: Cleanup temporaries here, anyway?
3551 return StmtError();
3552 }
3553 RetValExp = Res.get();
3554 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3555 }
3556
3557 if (RetValExp) {
3558 ExprResult ER =
3559 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3560 if (ER.isInvalid())
3561 return StmtError();
3562 RetValExp = ER.get();
3563 }
3564 auto *Result =
3565 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3566
3567 // If we need to check for the named return value optimization,
3568 // or if we need to infer the return type,
3569 // save the return statement in our scope for later processing.
3570 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3571 FunctionScopes.back()->Returns.push_back(Result);
3572
3573 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3574 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3575
3576 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap);
3577 CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
3578 RetValExp->containsErrors())
3579 CurBlock->TheDecl->setInvalidDecl();
3580
3581 return Result;
3582 }
3583
3584 namespace {
3585 /// Marks all typedefs in all local classes in a type referenced.
3586 ///
3587 /// In a function like
3588 /// auto f() {
3589 /// struct S { typedef int a; };
3590 /// return S();
3591 /// }
3592 ///
3593 /// the local type escapes and could be referenced in some TUs but not in
3594 /// others. Pretend that all local typedefs are always referenced, to not warn
3595 /// on this. This isn't necessary if f has internal linkage, or the typedef
3596 /// is private.
3597 class LocalTypedefNameReferencer
3598 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3599 public:
LocalTypedefNameReferencer(Sema & S)3600 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3601 bool VisitRecordType(const RecordType *RT);
3602 private:
3603 Sema &S;
3604 };
VisitRecordType(const RecordType * RT)3605 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3606 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3607 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3608 R->isDependentType())
3609 return true;
3610 for (auto *TmpD : R->decls())
3611 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3612 if (T->getAccess() != AS_private || R->hasFriends())
3613 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3614 return true;
3615 }
3616 }
3617
getReturnTypeLoc(FunctionDecl * FD) const3618 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3619 return FD->getTypeSourceInfo()
3620 ->getTypeLoc()
3621 .getAsAdjusted<FunctionProtoTypeLoc>()
3622 .getReturnLoc();
3623 }
3624
DeduceFunctionTypeFromReturnExpr(FunctionDecl * FD,SourceLocation ReturnLoc,Expr * RetExpr,const AutoType * AT)3625 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3626 SourceLocation ReturnLoc,
3627 Expr *RetExpr, const AutoType *AT) {
3628 // If this is the conversion function for a lambda, we choose to deduce its
3629 // type from the corresponding call operator, not from the synthesized return
3630 // statement within it. See Sema::DeduceReturnType.
3631 if (isLambdaConversionOperator(FD))
3632 return false;
3633
3634 if (isa_and_nonnull<InitListExpr>(RetExpr)) {
3635 // If the deduction is for a return statement and the initializer is
3636 // a braced-init-list, the program is ill-formed.
3637 Diag(RetExpr->getExprLoc(),
3638 getCurLambda() ? diag::err_lambda_return_init_list
3639 : diag::err_auto_fn_return_init_list)
3640 << RetExpr->getSourceRange();
3641 return true;
3642 }
3643
3644 if (FD->isDependentContext()) {
3645 // C++1y [dcl.spec.auto]p12:
3646 // Return type deduction [...] occurs when the definition is
3647 // instantiated even if the function body contains a return
3648 // statement with a non-type-dependent operand.
3649 assert(AT->isDeduced() && "should have deduced to dependent type");
3650 return false;
3651 }
3652
3653 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3654 // In the case of a return with no operand, the initializer is considered
3655 // to be void().
3656 CXXScalarValueInitExpr VoidVal(Context.VoidTy, nullptr, SourceLocation());
3657 if (!RetExpr) {
3658 // For a function with a deduced result type to return with omitted
3659 // expression, the result type as written must be 'auto' or
3660 // 'decltype(auto)', possibly cv-qualified or constrained, but not
3661 // ref-qualified.
3662 if (!OrigResultType.getType()->getAs<AutoType>()) {
3663 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3664 << OrigResultType.getType();
3665 return true;
3666 }
3667 RetExpr = &VoidVal;
3668 }
3669
3670 QualType Deduced = AT->getDeducedType();
3671 {
3672 // Otherwise, [...] deduce a value for U using the rules of template
3673 // argument deduction.
3674 auto RetExprLoc = RetExpr->getExprLoc();
3675 TemplateDeductionInfo Info(RetExprLoc);
3676 SourceLocation TemplateSpecLoc;
3677 if (RetExpr->getType() == Context.OverloadTy) {
3678 auto FindResult = OverloadExpr::find(RetExpr);
3679 if (FindResult.Expression)
3680 TemplateSpecLoc = FindResult.Expression->getNameLoc();
3681 }
3682 TemplateSpecCandidateSet FailedTSC(TemplateSpecLoc);
3683 TemplateDeductionResult Res = DeduceAutoType(
3684 OrigResultType, RetExpr, Deduced, Info, /*DependentDeduction=*/false,
3685 /*IgnoreConstraints=*/false, &FailedTSC);
3686 if (Res != TemplateDeductionResult::Success && FD->isInvalidDecl())
3687 return true;
3688 switch (Res) {
3689 case TemplateDeductionResult::Success:
3690 break;
3691 case TemplateDeductionResult::AlreadyDiagnosed:
3692 return true;
3693 case TemplateDeductionResult::Inconsistent: {
3694 // If a function with a declared return type that contains a placeholder
3695 // type has multiple return statements, the return type is deduced for
3696 // each return statement. [...] if the type deduced is not the same in
3697 // each deduction, the program is ill-formed.
3698 const LambdaScopeInfo *LambdaSI = getCurLambda();
3699 if (LambdaSI && LambdaSI->HasImplicitReturnType)
3700 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3701 << Info.SecondArg << Info.FirstArg << true /*IsLambda*/;
3702 else
3703 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3704 << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg
3705 << Info.FirstArg;
3706 return true;
3707 }
3708 default:
3709 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3710 << OrigResultType.getType() << RetExpr->getType();
3711 FailedTSC.NoteCandidates(*this, RetExprLoc);
3712 return true;
3713 }
3714 }
3715
3716 // If a local type is part of the returned type, mark its fields as
3717 // referenced.
3718 LocalTypedefNameReferencer(*this).TraverseType(RetExpr->getType());
3719
3720 // CUDA: Kernel function must have 'void' return type.
3721 if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() &&
3722 !Deduced->isVoidType()) {
3723 Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3724 << FD->getType() << FD->getSourceRange();
3725 return true;
3726 }
3727
3728 if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced)
3729 // Update all declarations of the function to have the deduced return type.
3730 Context.adjustDeducedFunctionResultType(FD, Deduced);
3731
3732 return false;
3733 }
3734
3735 StmtResult
ActOnReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,Scope * CurScope)3736 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3737 Scope *CurScope) {
3738 // Correct typos, in case the containing function returns 'auto' and
3739 // RetValExp should determine the deduced type.
3740 ExprResult RetVal = CorrectDelayedTyposInExpr(
3741 RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true);
3742 if (RetVal.isInvalid())
3743 return StmtError();
3744
3745 if (getCurScope()->isInOpenACCComputeConstructScope())
3746 return StmtError(
3747 Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct)
3748 << /*return*/ 1 << /*out of */ 0);
3749
3750 StmtResult R =
3751 BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true);
3752 if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
3753 return R;
3754
3755 VarDecl *VD =
3756 const_cast<VarDecl *>(cast<ReturnStmt>(R.get())->getNRVOCandidate());
3757
3758 CurScope->updateNRVOCandidate(VD);
3759
3760 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3761
3762 return R;
3763 }
3764
CheckSimplerImplicitMovesMSVCWorkaround(const Sema & S,const Expr * E)3765 static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S,
3766 const Expr *E) {
3767 if (!E || !S.getLangOpts().CPlusPlus23 || !S.getLangOpts().MSVCCompat)
3768 return false;
3769 const Decl *D = E->getReferencedDeclOfCallee();
3770 if (!D || !S.SourceMgr.isInSystemHeader(D->getLocation()))
3771 return false;
3772 for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
3773 if (DC->isStdNamespace())
3774 return true;
3775 }
3776 return false;
3777 }
3778
BuildReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,bool AllowRecovery)3779 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3780 bool AllowRecovery) {
3781 // Check for unexpanded parameter packs.
3782 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3783 return StmtError();
3784
3785 // HACK: We suppress simpler implicit move here in msvc compatibility mode
3786 // just as a temporary work around, as the MSVC STL has issues with
3787 // this change.
3788 bool SupressSimplerImplicitMoves =
3789 CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp);
3790 NamedReturnInfo NRInfo = getNamedReturnInfo(
3791 RetValExp, SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
3792 : SimplerImplicitMoveMode::Normal);
3793
3794 if (isa<CapturingScopeInfo>(getCurFunction()))
3795 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
3796 SupressSimplerImplicitMoves);
3797
3798 QualType FnRetType;
3799 QualType RelatedRetType;
3800 const AttrVec *Attrs = nullptr;
3801 bool isObjCMethod = false;
3802
3803 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3804 FnRetType = FD->getReturnType();
3805 if (FD->hasAttrs())
3806 Attrs = &FD->getAttrs();
3807 if (FD->isNoReturn())
3808 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD;
3809 if (FD->isMain() && RetValExp)
3810 if (isa<CXXBoolLiteralExpr>(RetValExp))
3811 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3812 << RetValExp->getSourceRange();
3813 if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
3814 if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) {
3815 if (RT->getDecl()->isOrContainsUnion())
3816 Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
3817 }
3818 }
3819 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3820 FnRetType = MD->getReturnType();
3821 isObjCMethod = true;
3822 if (MD->hasAttrs())
3823 Attrs = &MD->getAttrs();
3824 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3825 // In the implementation of a method with a related return type, the
3826 // type used to type-check the validity of return statements within the
3827 // method body is a pointer to the type of the class being implemented.
3828 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3829 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3830 }
3831 } else // If we don't have a function/method context, bail.
3832 return StmtError();
3833
3834 if (RetValExp) {
3835 const auto *ATy = dyn_cast<ArrayType>(RetValExp->getType());
3836 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
3837 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
3838 return StmtError();
3839 }
3840 }
3841
3842 // C++1z: discarded return statements are not considered when deducing a
3843 // return type.
3844 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3845 FnRetType->getContainedAutoType()) {
3846 if (RetValExp) {
3847 ExprResult ER =
3848 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3849 if (ER.isInvalid())
3850 return StmtError();
3851 RetValExp = ER.get();
3852 }
3853 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3854 /* NRVOCandidate=*/nullptr);
3855 }
3856
3857 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3858 // deduction.
3859 if (getLangOpts().CPlusPlus14) {
3860 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3861 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3862 // If we've already decided this function is invalid, e.g. because
3863 // we saw a `return` whose expression had an error, don't keep
3864 // trying to deduce its return type.
3865 // (Some return values may be needlessly wrapped in RecoveryExpr).
3866 if (FD->isInvalidDecl() ||
3867 DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3868 FD->setInvalidDecl();
3869 if (!AllowRecovery)
3870 return StmtError();
3871 // The deduction failure is diagnosed and marked, try to recover.
3872 if (RetValExp) {
3873 // Wrap return value with a recovery expression of the previous type.
3874 // If no deduction yet, use DependentTy.
3875 auto Recovery = CreateRecoveryExpr(
3876 RetValExp->getBeginLoc(), RetValExp->getEndLoc(), RetValExp,
3877 AT->isDeduced() ? FnRetType : QualType());
3878 if (Recovery.isInvalid())
3879 return StmtError();
3880 RetValExp = Recovery.get();
3881 } else {
3882 // Nothing to do: a ReturnStmt with no value is fine recovery.
3883 }
3884 } else {
3885 FnRetType = FD->getReturnType();
3886 }
3887 }
3888 }
3889 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
3890
3891 bool HasDependentReturnType = FnRetType->isDependentType();
3892
3893 ReturnStmt *Result = nullptr;
3894 if (FnRetType->isVoidType()) {
3895 if (RetValExp) {
3896 if (auto *ILE = dyn_cast<InitListExpr>(RetValExp)) {
3897 // We simply never allow init lists as the return value of void
3898 // functions. This is compatible because this was never allowed before,
3899 // so there's no legacy code to deal with.
3900 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3901 int FunctionKind = 0;
3902 if (isa<ObjCMethodDecl>(CurDecl))
3903 FunctionKind = 1;
3904 else if (isa<CXXConstructorDecl>(CurDecl))
3905 FunctionKind = 2;
3906 else if (isa<CXXDestructorDecl>(CurDecl))
3907 FunctionKind = 3;
3908
3909 Diag(ReturnLoc, diag::err_return_init_list)
3910 << CurDecl << FunctionKind << RetValExp->getSourceRange();
3911
3912 // Preserve the initializers in the AST.
3913 RetValExp = AllowRecovery
3914 ? CreateRecoveryExpr(ILE->getLBraceLoc(),
3915 ILE->getRBraceLoc(), ILE->inits())
3916 .get()
3917 : nullptr;
3918 } else if (!RetValExp->isTypeDependent()) {
3919 // C99 6.8.6.4p1 (ext_ since GCC warns)
3920 unsigned D = diag::ext_return_has_expr;
3921 if (RetValExp->getType()->isVoidType()) {
3922 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3923 if (isa<CXXConstructorDecl>(CurDecl) ||
3924 isa<CXXDestructorDecl>(CurDecl))
3925 D = diag::err_ctor_dtor_returns_void;
3926 else
3927 D = diag::ext_return_has_void_expr;
3928 }
3929 else {
3930 ExprResult Result = RetValExp;
3931 Result = IgnoredValueConversions(Result.get());
3932 if (Result.isInvalid())
3933 return StmtError();
3934 RetValExp = Result.get();
3935 RetValExp = ImpCastExprToType(RetValExp,
3936 Context.VoidTy, CK_ToVoid).get();
3937 }
3938 // return of void in constructor/destructor is illegal in C++.
3939 if (D == diag::err_ctor_dtor_returns_void) {
3940 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3941 Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl)
3942 << RetValExp->getSourceRange();
3943 }
3944 // return (some void expression); is legal in C++.
3945 else if (D != diag::ext_return_has_void_expr ||
3946 !getLangOpts().CPlusPlus) {
3947 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3948
3949 int FunctionKind = 0;
3950 if (isa<ObjCMethodDecl>(CurDecl))
3951 FunctionKind = 1;
3952 else if (isa<CXXConstructorDecl>(CurDecl))
3953 FunctionKind = 2;
3954 else if (isa<CXXDestructorDecl>(CurDecl))
3955 FunctionKind = 3;
3956
3957 Diag(ReturnLoc, D)
3958 << CurDecl << FunctionKind << RetValExp->getSourceRange();
3959 }
3960 }
3961
3962 if (RetValExp) {
3963 ExprResult ER =
3964 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3965 if (ER.isInvalid())
3966 return StmtError();
3967 RetValExp = ER.get();
3968 }
3969 }
3970
3971 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3972 /* NRVOCandidate=*/nullptr);
3973 } else if (!RetValExp && !HasDependentReturnType) {
3974 FunctionDecl *FD = getCurFunctionDecl();
3975
3976 if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) {
3977 // The intended return type might have been "void", so don't warn.
3978 } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3979 // C++11 [stmt.return]p2
3980 Diag(ReturnLoc, diag::err_constexpr_return_missing_expr)
3981 << FD << FD->isConsteval();
3982 FD->setInvalidDecl();
3983 } else {
3984 // C99 6.8.6.4p1 (ext_ since GCC warns)
3985 // C90 6.6.6.4p4
3986 unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
3987 : diag::warn_return_missing_expr;
3988 // Note that at this point one of getCurFunctionDecl() or
3989 // getCurMethodDecl() must be non-null (see above).
3990 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
3991 "Not in a FunctionDecl or ObjCMethodDecl?");
3992 bool IsMethod = FD == nullptr;
3993 const NamedDecl *ND =
3994 IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD);
3995 Diag(ReturnLoc, DiagID) << ND << IsMethod;
3996 }
3997
3998 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3999 /* NRVOCandidate=*/nullptr);
4000 } else {
4001 assert(RetValExp || HasDependentReturnType);
4002 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
4003
4004 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4005 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4006 // function return.
4007
4008 // In C++ the return statement is handled via a copy initialization,
4009 // the C version of which boils down to CheckSingleAssignmentConstraints.
4010 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
4011 // we have a non-void function with an expression, continue checking
4012 InitializedEntity Entity =
4013 InitializedEntity::InitializeResult(ReturnLoc, RetType);
4014 ExprResult Res = PerformMoveOrCopyInitialization(
4015 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
4016 if (Res.isInvalid() && AllowRecovery)
4017 Res = CreateRecoveryExpr(RetValExp->getBeginLoc(),
4018 RetValExp->getEndLoc(), RetValExp, RetType);
4019 if (Res.isInvalid()) {
4020 // FIXME: Clean up temporaries here anyway?
4021 return StmtError();
4022 }
4023 RetValExp = Res.getAs<Expr>();
4024
4025 // If we have a related result type, we need to implicitly
4026 // convert back to the formal result type. We can't pretend to
4027 // initialize the result again --- we might end double-retaining
4028 // --- so instead we initialize a notional temporary.
4029 if (!RelatedRetType.isNull()) {
4030 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
4031 FnRetType);
4032 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
4033 if (Res.isInvalid()) {
4034 // FIXME: Clean up temporaries here anyway?
4035 return StmtError();
4036 }
4037 RetValExp = Res.getAs<Expr>();
4038 }
4039
4040 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
4041 getCurFunctionDecl());
4042 }
4043
4044 if (RetValExp) {
4045 ExprResult ER =
4046 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
4047 if (ER.isInvalid())
4048 return StmtError();
4049 RetValExp = ER.get();
4050 }
4051 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
4052 }
4053
4054 // If we need to check for the named return value optimization, save the
4055 // return statement in our scope for later processing.
4056 if (Result->getNRVOCandidate())
4057 FunctionScopes.back()->Returns.push_back(Result);
4058
4059 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
4060 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
4061
4062 return Result;
4063 }
4064
4065 StmtResult
ActOnCXXCatchBlock(SourceLocation CatchLoc,Decl * ExDecl,Stmt * HandlerBlock)4066 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
4067 Stmt *HandlerBlock) {
4068 // There's nothing to test that ActOnExceptionDecl didn't already test.
4069 return new (Context)
4070 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
4071 }
4072
4073 namespace {
4074 class CatchHandlerType {
4075 QualType QT;
4076 LLVM_PREFERRED_TYPE(bool)
4077 unsigned IsPointer : 1;
4078
4079 // This is a special constructor to be used only with DenseMapInfo's
4080 // getEmptyKey() and getTombstoneKey() functions.
4081 friend struct llvm::DenseMapInfo<CatchHandlerType>;
4082 enum Unique { ForDenseMap };
CatchHandlerType(QualType QT,Unique)4083 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
4084
4085 public:
4086 /// Used when creating a CatchHandlerType from a handler type; will determine
4087 /// whether the type is a pointer or reference and will strip off the top
4088 /// level pointer and cv-qualifiers.
CatchHandlerType(QualType Q)4089 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
4090 if (QT->isPointerType())
4091 IsPointer = true;
4092
4093 QT = QT.getUnqualifiedType();
4094 if (IsPointer || QT->isReferenceType())
4095 QT = QT->getPointeeType();
4096 }
4097
4098 /// Used when creating a CatchHandlerType from a base class type; pretends the
4099 /// type passed in had the pointer qualifier, does not need to get an
4100 /// unqualified type.
CatchHandlerType(QualType QT,bool IsPointer)4101 CatchHandlerType(QualType QT, bool IsPointer)
4102 : QT(QT), IsPointer(IsPointer) {}
4103
underlying() const4104 QualType underlying() const { return QT; }
isPointer() const4105 bool isPointer() const { return IsPointer; }
4106
operator ==(const CatchHandlerType & LHS,const CatchHandlerType & RHS)4107 friend bool operator==(const CatchHandlerType &LHS,
4108 const CatchHandlerType &RHS) {
4109 // If the pointer qualification does not match, we can return early.
4110 if (LHS.IsPointer != RHS.IsPointer)
4111 return false;
4112 // Otherwise, check the underlying type without cv-qualifiers.
4113 return LHS.QT == RHS.QT;
4114 }
4115 };
4116 } // namespace
4117
4118 namespace llvm {
4119 template <> struct DenseMapInfo<CatchHandlerType> {
getEmptyKeyllvm::DenseMapInfo4120 static CatchHandlerType getEmptyKey() {
4121 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4122 CatchHandlerType::ForDenseMap);
4123 }
4124
getTombstoneKeyllvm::DenseMapInfo4125 static CatchHandlerType getTombstoneKey() {
4126 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4127 CatchHandlerType::ForDenseMap);
4128 }
4129
getHashValuellvm::DenseMapInfo4130 static unsigned getHashValue(const CatchHandlerType &Base) {
4131 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
4132 }
4133
isEqualllvm::DenseMapInfo4134 static bool isEqual(const CatchHandlerType &LHS,
4135 const CatchHandlerType &RHS) {
4136 return LHS == RHS;
4137 }
4138 };
4139 }
4140
4141 namespace {
4142 class CatchTypePublicBases {
4143 const llvm::DenseMap<QualType, CXXCatchStmt *> &TypesToCheck;
4144
4145 CXXCatchStmt *FoundHandler;
4146 QualType FoundHandlerType;
4147 QualType TestAgainstType;
4148
4149 public:
CatchTypePublicBases(const llvm::DenseMap<QualType,CXXCatchStmt * > & T,QualType QT)4150 CatchTypePublicBases(const llvm::DenseMap<QualType, CXXCatchStmt *> &T,
4151 QualType QT)
4152 : TypesToCheck(T), FoundHandler(nullptr), TestAgainstType(QT) {}
4153
getFoundHandler() const4154 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
getFoundHandlerType() const4155 QualType getFoundHandlerType() const { return FoundHandlerType; }
4156
operator ()(const CXXBaseSpecifier * S,CXXBasePath &)4157 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
4158 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
4159 QualType Check = S->getType().getCanonicalType();
4160 const auto &M = TypesToCheck;
4161 auto I = M.find(Check);
4162 if (I != M.end()) {
4163 // We're pretty sure we found what we need to find. However, we still
4164 // need to make sure that we properly compare for pointers and
4165 // references, to handle cases like:
4166 //
4167 // } catch (Base *b) {
4168 // } catch (Derived &d) {
4169 // }
4170 //
4171 // where there is a qualification mismatch that disqualifies this
4172 // handler as a potential problem.
4173 if (I->second->getCaughtType()->isPointerType() ==
4174 TestAgainstType->isPointerType()) {
4175 FoundHandler = I->second;
4176 FoundHandlerType = Check;
4177 return true;
4178 }
4179 }
4180 }
4181 return false;
4182 }
4183 };
4184 }
4185
ActOnCXXTryBlock(SourceLocation TryLoc,Stmt * TryBlock,ArrayRef<Stmt * > Handlers)4186 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4187 ArrayRef<Stmt *> Handlers) {
4188 const llvm::Triple &T = Context.getTargetInfo().getTriple();
4189 const bool IsOpenMPGPUTarget =
4190 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
4191 // Don't report an error if 'try' is used in system headers or in an OpenMP
4192 // target region compiled for a GPU architecture.
4193 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
4194 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
4195 // Delay error emission for the OpenMP device code.
4196 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4197 }
4198
4199 // In OpenMP target regions, we assume that catch is never reached on GPU
4200 // targets.
4201 if (IsOpenMPGPUTarget)
4202 targetDiag(TryLoc, diag::warn_try_not_valid_on_target) << T.str();
4203
4204 // Exceptions aren't allowed in CUDA device code.
4205 if (getLangOpts().CUDA)
4206 CUDA().DiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4207 << "try" << llvm::to_underlying(CUDA().CurrentTarget());
4208
4209 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4210 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4211
4212 sema::FunctionScopeInfo *FSI = getCurFunction();
4213
4214 // C++ try is incompatible with SEH __try.
4215 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4216 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
4217 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4218 }
4219
4220 const unsigned NumHandlers = Handlers.size();
4221 assert(!Handlers.empty() &&
4222 "The parser shouldn't call this if there are no handlers.");
4223
4224 llvm::DenseMap<QualType, CXXCatchStmt *> HandledBaseTypes;
4225 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4226 for (unsigned i = 0; i < NumHandlers; ++i) {
4227 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4228
4229 // Diagnose when the handler is a catch-all handler, but it isn't the last
4230 // handler for the try block. [except.handle]p5. Also, skip exception
4231 // declarations that are invalid, since we can't usefully report on them.
4232 if (!H->getExceptionDecl()) {
4233 if (i < NumHandlers - 1)
4234 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4235 continue;
4236 } else if (H->getExceptionDecl()->isInvalidDecl())
4237 continue;
4238
4239 // Walk the type hierarchy to diagnose when this type has already been
4240 // handled (duplication), or cannot be handled (derivation inversion). We
4241 // ignore top-level cv-qualifiers, per [except.handle]p3
4242 CatchHandlerType HandlerCHT = H->getCaughtType().getCanonicalType();
4243
4244 // We can ignore whether the type is a reference or a pointer; we need the
4245 // underlying declaration type in order to get at the underlying record
4246 // decl, if there is one.
4247 QualType Underlying = HandlerCHT.underlying();
4248 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4249 if (!RD->hasDefinition())
4250 continue;
4251 // Check that none of the public, unambiguous base classes are in the
4252 // map ([except.handle]p1). Give the base classes the same pointer
4253 // qualification as the original type we are basing off of. This allows
4254 // comparison against the handler type using the same top-level pointer
4255 // as the original type.
4256 CXXBasePaths Paths;
4257 Paths.setOrigin(RD);
4258 CatchTypePublicBases CTPB(HandledBaseTypes,
4259 H->getCaughtType().getCanonicalType());
4260 if (RD->lookupInBases(CTPB, Paths)) {
4261 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4262 if (!Paths.isAmbiguous(
4263 CanQualType::CreateUnsafe(CTPB.getFoundHandlerType()))) {
4264 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4265 diag::warn_exception_caught_by_earlier_handler)
4266 << H->getCaughtType();
4267 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4268 diag::note_previous_exception_handler)
4269 << Problem->getCaughtType();
4270 }
4271 }
4272 // Strip the qualifiers here because we're going to be comparing this
4273 // type to the base type specifiers of a class, which are ignored in a
4274 // base specifier per [class.derived.general]p2.
4275 HandledBaseTypes[Underlying.getUnqualifiedType()] = H;
4276 }
4277
4278 // Add the type the list of ones we have handled; diagnose if we've already
4279 // handled it.
4280 auto R = HandledTypes.insert(
4281 std::make_pair(H->getCaughtType().getCanonicalType(), H));
4282 if (!R.second) {
4283 const CXXCatchStmt *Problem = R.first->second;
4284 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4285 diag::warn_exception_caught_by_earlier_handler)
4286 << H->getCaughtType();
4287 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4288 diag::note_previous_exception_handler)
4289 << Problem->getCaughtType();
4290 }
4291 }
4292
4293 FSI->setHasCXXTry(TryLoc);
4294
4295 return CXXTryStmt::Create(Context, TryLoc, cast<CompoundStmt>(TryBlock),
4296 Handlers);
4297 }
4298
ActOnSEHTryBlock(bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)4299 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4300 Stmt *TryBlock, Stmt *Handler) {
4301 assert(TryBlock && Handler);
4302
4303 sema::FunctionScopeInfo *FSI = getCurFunction();
4304
4305 // SEH __try is incompatible with C++ try. Borland appears to support this,
4306 // however.
4307 if (!getLangOpts().Borland) {
4308 if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
4309 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
4310 Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here)
4311 << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX
4312 ? "'try'"
4313 : "'@try'");
4314 }
4315 }
4316
4317 FSI->setHasSEHTry(TryLoc);
4318
4319 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4320 // track if they use SEH.
4321 DeclContext *DC = CurContext;
4322 while (DC && !DC->isFunctionOrMethod())
4323 DC = DC->getParent();
4324 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4325 if (FD)
4326 FD->setUsesSEHTry(true);
4327 else
4328 Diag(TryLoc, diag::err_seh_try_outside_functions);
4329
4330 // Reject __try on unsupported targets.
4331 if (!Context.getTargetInfo().isSEHTrySupported())
4332 Diag(TryLoc, diag::err_seh_try_unsupported);
4333
4334 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4335 }
4336
ActOnSEHExceptBlock(SourceLocation Loc,Expr * FilterExpr,Stmt * Block)4337 StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
4338 Stmt *Block) {
4339 assert(FilterExpr && Block);
4340 QualType FTy = FilterExpr->getType();
4341 if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4342 return StmtError(
4343 Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4344 << FTy);
4345 }
4346 return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
4347 }
4348
ActOnStartSEHFinallyBlock()4349 void Sema::ActOnStartSEHFinallyBlock() {
4350 CurrentSEHFinally.push_back(CurScope);
4351 }
4352
ActOnAbortSEHFinallyBlock()4353 void Sema::ActOnAbortSEHFinallyBlock() {
4354 CurrentSEHFinally.pop_back();
4355 }
4356
ActOnFinishSEHFinallyBlock(SourceLocation Loc,Stmt * Block)4357 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4358 assert(Block);
4359 CurrentSEHFinally.pop_back();
4360 return SEHFinallyStmt::Create(Context, Loc, Block);
4361 }
4362
4363 StmtResult
ActOnSEHLeaveStmt(SourceLocation Loc,Scope * CurScope)4364 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4365 Scope *SEHTryParent = CurScope;
4366 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4367 SEHTryParent = SEHTryParent->getParent();
4368 if (!SEHTryParent)
4369 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4370 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4371
4372 return new (Context) SEHLeaveStmt(Loc);
4373 }
4374
BuildMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,NestedNameSpecifierLoc QualifierLoc,DeclarationNameInfo NameInfo,Stmt * Nested)4375 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4376 bool IsIfExists,
4377 NestedNameSpecifierLoc QualifierLoc,
4378 DeclarationNameInfo NameInfo,
4379 Stmt *Nested)
4380 {
4381 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4382 QualifierLoc, NameInfo,
4383 cast<CompoundStmt>(Nested));
4384 }
4385
4386
ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name,Stmt * Nested)4387 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4388 bool IsIfExists,
4389 CXXScopeSpec &SS,
4390 UnqualifiedId &Name,
4391 Stmt *Nested) {
4392 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4393 SS.getWithLocInContext(Context),
4394 GetNameFromUnqualifiedId(Name),
4395 Nested);
4396 }
4397
4398 RecordDecl*
CreateCapturedStmtRecordDecl(CapturedDecl * & CD,SourceLocation Loc,unsigned NumParams)4399 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4400 unsigned NumParams) {
4401 DeclContext *DC = CurContext;
4402 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4403 DC = DC->getParent();
4404
4405 RecordDecl *RD = nullptr;
4406 if (getLangOpts().CPlusPlus)
4407 RD = CXXRecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc,
4408 /*Id=*/nullptr);
4409 else
4410 RD = RecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc,
4411 /*Id=*/nullptr);
4412
4413 RD->setCapturedRecord();
4414 DC->addDecl(RD);
4415 RD->setImplicit();
4416 RD->startDefinition();
4417
4418 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4419 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4420 DC->addDecl(CD);
4421 return RD;
4422 }
4423
4424 static bool
buildCapturedStmtCaptureList(Sema & S,CapturedRegionScopeInfo * RSI,SmallVectorImpl<CapturedStmt::Capture> & Captures,SmallVectorImpl<Expr * > & CaptureInits)4425 buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4426 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4427 SmallVectorImpl<Expr *> &CaptureInits) {
4428 for (const sema::Capture &Cap : RSI->Captures) {
4429 if (Cap.isInvalid())
4430 continue;
4431
4432 // Form the initializer for the capture.
4433 ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4434 RSI->CapRegionKind == CR_OpenMP);
4435
4436 // FIXME: Bail out now if the capture is not used and the initializer has
4437 // no side-effects.
4438
4439 // Create a field for this capture.
4440 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4441
4442 // Add the capture to our list of captures.
4443 if (Cap.isThisCapture()) {
4444 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4445 CapturedStmt::VCK_This));
4446 } else if (Cap.isVLATypeCapture()) {
4447 Captures.push_back(
4448 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4449 } else {
4450 assert(Cap.isVariableCapture() && "unknown kind of capture");
4451
4452 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4453 S.OpenMP().setOpenMPCaptureKind(Field, Cap.getVariable(),
4454 RSI->OpenMPLevel);
4455
4456 Captures.push_back(CapturedStmt::Capture(
4457 Cap.getLocation(),
4458 Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4459 : CapturedStmt::VCK_ByCopy,
4460 cast<VarDecl>(Cap.getVariable())));
4461 }
4462 CaptureInits.push_back(Init.get());
4463 }
4464 return false;
4465 }
4466
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,unsigned NumParams)4467 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4468 CapturedRegionKind Kind,
4469 unsigned NumParams) {
4470 CapturedDecl *CD = nullptr;
4471 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4472
4473 // Build the context parameter
4474 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4475 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4476 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4477 auto *Param =
4478 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4479 ImplicitParamKind::CapturedContext);
4480 DC->addDecl(Param);
4481
4482 CD->setContextParam(0, Param);
4483
4484 // Enter the capturing scope for this captured region.
4485 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4486
4487 if (CurScope)
4488 PushDeclContext(CurScope, CD);
4489 else
4490 CurContext = CD;
4491
4492 PushExpressionEvaluationContext(
4493 ExpressionEvaluationContext::PotentiallyEvaluated);
4494 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = false;
4495 }
4496
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,ArrayRef<CapturedParamNameType> Params,unsigned OpenMPCaptureLevel)4497 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4498 CapturedRegionKind Kind,
4499 ArrayRef<CapturedParamNameType> Params,
4500 unsigned OpenMPCaptureLevel) {
4501 CapturedDecl *CD = nullptr;
4502 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4503
4504 // Build the context parameter
4505 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4506 bool ContextIsFound = false;
4507 unsigned ParamNum = 0;
4508 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4509 E = Params.end();
4510 I != E; ++I, ++ParamNum) {
4511 if (I->second.isNull()) {
4512 assert(!ContextIsFound &&
4513 "null type has been found already for '__context' parameter");
4514 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4515 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4516 .withConst()
4517 .withRestrict();
4518 auto *Param =
4519 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4520 ImplicitParamKind::CapturedContext);
4521 DC->addDecl(Param);
4522 CD->setContextParam(ParamNum, Param);
4523 ContextIsFound = true;
4524 } else {
4525 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4526 auto *Param =
4527 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4528 ImplicitParamKind::CapturedContext);
4529 DC->addDecl(Param);
4530 CD->setParam(ParamNum, Param);
4531 }
4532 }
4533 assert(ContextIsFound && "no null type for '__context' parameter");
4534 if (!ContextIsFound) {
4535 // Add __context implicitly if it is not specified.
4536 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4537 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4538 auto *Param =
4539 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4540 ImplicitParamKind::CapturedContext);
4541 DC->addDecl(Param);
4542 CD->setContextParam(ParamNum, Param);
4543 }
4544 // Enter the capturing scope for this captured region.
4545 PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
4546
4547 if (CurScope)
4548 PushDeclContext(CurScope, CD);
4549 else
4550 CurContext = CD;
4551
4552 PushExpressionEvaluationContext(
4553 ExpressionEvaluationContext::PotentiallyEvaluated);
4554 }
4555
ActOnCapturedRegionError()4556 void Sema::ActOnCapturedRegionError() {
4557 DiscardCleanupsInEvaluationContext();
4558 PopExpressionEvaluationContext();
4559 PopDeclContext();
4560 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4561 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4562
4563 RecordDecl *Record = RSI->TheRecordDecl;
4564 Record->setInvalidDecl();
4565
4566 SmallVector<Decl*, 4> Fields(Record->fields());
4567 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4568 SourceLocation(), SourceLocation(), ParsedAttributesView());
4569 }
4570
ActOnCapturedRegionEnd(Stmt * S)4571 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4572 // Leave the captured scope before we start creating captures in the
4573 // enclosing scope.
4574 DiscardCleanupsInEvaluationContext();
4575 PopExpressionEvaluationContext();
4576 PopDeclContext();
4577 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4578 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4579
4580 SmallVector<CapturedStmt::Capture, 4> Captures;
4581 SmallVector<Expr *, 4> CaptureInits;
4582 if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4583 return StmtError();
4584
4585 CapturedDecl *CD = RSI->TheCapturedDecl;
4586 RecordDecl *RD = RSI->TheRecordDecl;
4587
4588 CapturedStmt *Res = CapturedStmt::Create(
4589 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4590 Captures, CaptureInits, CD, RD);
4591
4592 CD->setBody(Res->getCapturedStmt());
4593 RD->completeDefinition();
4594
4595 return Res;
4596 }
4597