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