blob: 2104add400e01e8e136bb0fcbb2ea8f6466bd4db [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattneraf8d5812006-11-10 05:07:45 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for statements.
10//
11//===----------------------------------------------------------------------===//
12
Sam McCall835d67f2019-05-08 05:49:42 +000013#include "clang/Sema/Ownership.h"
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
Richard Smith50e291e2018-01-02 23:52:42 +000017#include "clang/AST/ASTLambda.h"
John McCall03318c12011-11-11 03:57:31 +000018#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000023#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000024#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000028#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000035#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000036#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000037#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000038#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000039#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000040#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000041
Chris Lattneraf8d5812006-11-10 05:07:45 +000042using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000043using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000044
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000045StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
Richard Smith945f8d32013-01-14 22:39:08 +000046 if (FE.isInvalid())
47 return StmtError();
48
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000049 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
Richard Smith945f8d32013-01-14 22:39:08 +000050 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000051 return StmtError();
52
Chris Lattner903eb512008-07-25 23:18:17 +000053 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000056
Chris Lattner903eb512008-07-25 23:18:17 +000057 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000058 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000059}
60
61
John McCalleaef89b2013-03-22 02:10:40 +000062StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
64 return StmtError();
65}
66
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000067StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000068 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000069 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000070}
71
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000072StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000074 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnercbafe8d2009-04-12 20:13:14 +000076 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000079 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000080}
Chris Lattneraf8d5812006-11-10 05:07:45 +000081
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000082void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000083 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 // If we don't have a declaration, or we have an invalid declaration,
86 // just return.
87 if (DG.isNull() || !DG.isSingleDecl())
88 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089
Douglas Gregor2eb1c572013-04-08 20:52:24 +000090 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
92 return;
93
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
96 if (!var) {
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
99 return;
100 }
John McCall31168b02011-06-15 23:02:42 +0000101
John McCalld4631322011-06-17 06:42:21 +0000102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000104 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000105
John McCalld4631322011-06-17 06:42:21 +0000106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000110 QualType type = var->getType();
111
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000119 }
120 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000121}
122
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000123/// Diagnose unused comparisons, both builtin and overloaded operators.
Richard Trieu99e1c952014-03-11 03:11:08 +0000124/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125///
126/// Adding a cast to void (or other expression wrappers) will prevent the
127/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000128static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 SourceLocation Loc;
Richard Smithc70f1d62017-12-14 15:16:18 +0000130 bool CanAssign;
131 enum { Equality, Inequality, Relational, ThreeWay } Kind;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132
133 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000134 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000135 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000136
Richard Smithc70f1d62017-12-14 15:16:18 +0000137 if (Op->getOpcode() == BO_EQ)
138 Kind = Equality;
139 else if (Op->getOpcode() == BO_NE)
140 Kind = Inequality;
141 else if (Op->getOpcode() == BO_Cmp)
142 Kind = ThreeWay;
143 else {
144 assert(Op->isRelationalOp());
145 Kind = Relational;
146 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000147 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000148 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000149 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000150 switch (Op->getOperator()) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000151 case OO_EqualEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000152 Kind = Equality;
153 break;
Richard Trieu99e1c952014-03-11 03:11:08 +0000154 case OO_ExclaimEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000155 Kind = Inequality;
Richard Trieu99e1c952014-03-11 03:11:08 +0000156 break;
157 case OO_Less:
158 case OO_Greater:
159 case OO_GreaterEqual:
160 case OO_LessEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000161 Kind = Relational;
Richard Trieu99e1c952014-03-11 03:11:08 +0000162 break;
Richard Smithc70f1d62017-12-14 15:16:18 +0000163 case OO_Spaceship:
164 Kind = ThreeWay;
165 break;
166 default:
167 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000168 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000169
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000170 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000171 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000172 } else {
173 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000174 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000175 }
176
177 // Suppress warnings when the operator, suspicious as it may be, comes from
178 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000179 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000180 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000181
Chandler Carruthe2669392011-08-17 09:34:37 +0000182 S.Diag(Loc, diag::warn_unused_comparison)
Richard Smithc70f1d62017-12-14 15:16:18 +0000183 << (unsigned)Kind << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000184
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000185 // If the LHS is a plausible entity to assign to, provide a fixit hint to
186 // correct common typos.
Richard Smithc70f1d62017-12-14 15:16:18 +0000187 if (CanAssign) {
188 if (Kind == Inequality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000189 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
190 << FixItHint::CreateReplacement(Loc, "|=");
Richard Smithc70f1d62017-12-14 15:16:18 +0000191 else if (Kind == Equality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000192 S.Diag(Loc, diag::note_equality_comparison_to_assign)
193 << FixItHint::CreateReplacement(Loc, "=");
194 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000195
196 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000197}
198
Erich Keane46441fd2019-07-25 15:10:56 +0000199static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
200 SourceLocation Loc, SourceRange R1,
201 SourceRange R2, bool IsCtor) {
202 if (!A)
203 return false;
204 StringRef Msg = A->getMessage();
205
206 if (Msg.empty()) {
207 if (IsCtor)
208 return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
209 return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
210 }
211
212 if (IsCtor)
213 return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
214 << R2;
215 return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
216}
217
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000218void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000219 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
220 return DiagnoseUnusedExprResult(Label->getSubStmt());
221
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000222 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000223 if (!E)
224 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000225
226 // If we are in an unevaluated expression context, then there can be no unused
227 // results because the results aren't expected to be used in the first place.
228 if (isUnevaluatedContext())
229 return;
230
Nico Weber0e631632015-10-27 19:47:40 +0000231 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000232 // In most cases, we don't want to warn if the expression is written in a
233 // macro body, or if the macro comes from a system header. If the offending
234 // expression is a call to a function with the warn_unused_result attribute,
235 // we warn no matter the location. Because of the order in which the various
236 // checks need to happen, we factor out the macro-related test here.
Fangrui Song6907ce22018-07-30 19:24:48 +0000237 bool ShouldSuppress =
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000238 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
239 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000240
Eli Friedmanc11535c2012-05-24 00:47:05 +0000241 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000242 SourceLocation Loc;
243 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000244 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000245 return;
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner6dc7e572012-08-31 22:39:21 +0000247 // If this is a GNU statement expression expanded from a macro, it is probably
248 // unused because it is a function-like macro that can be used as either an
249 // expression or statement. Don't warn, because it is almost certainly a
250 // false positive.
251 if (isa<StmtExpr>(E) && Loc.isMacroID())
252 return;
253
Nico Weber0e631632015-10-27 19:47:40 +0000254 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
255 // That macro is frequently used to suppress "unused parameter" warnings,
256 // but its implementation makes clang's -Wunused-value fire. Prevent this.
257 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
258 SourceLocation SpellLoc = Loc;
259 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
260 return;
261 }
262
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000263 // Okay, we have an unused result. Depending on what the base expression is,
264 // we might want to make a more specific diagnostic. Check for one of these
265 // cases now.
266 unsigned DiagID = diag::warn_unused_expr;
Bill Wendling7c44da22018-10-31 03:48:47 +0000267 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000268 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000269 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
270 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000271
Chandler Carruthe2669392011-08-17 09:34:37 +0000272 if (DiagnoseUnusedComparison(*this, E))
273 return;
274
Eli Friedmanc11535c2012-05-24 00:47:05 +0000275 E = WarnExpr;
Erich Keane46441fd2019-07-25 15:10:56 +0000276 if (const auto *Cast = dyn_cast<CastExpr>(E))
277 if (Cast->getCastKind() == CK_NoOp ||
278 Cast->getCastKind() == CK_ConstructorConversion)
279 E = Cast->getSubExpr()->IgnoreImpCasts();
280
Chris Lattner1a6babf2009-10-13 04:53:48 +0000281 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000282 if (E->getType()->isVoidType())
283 return;
284
Erich Keane46441fd2019-07-25 15:10:56 +0000285 if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
286 CE->getUnusedResultAttr(Context)),
287 Loc, R1, R2, /*isCtor=*/false))
Aaron Ballmand23e9bc2019-01-03 14:24:31 +0000288 return;
Aaron Ballmand23e9bc2019-01-03 14:24:31 +0000289
Chris Lattner1a6babf2009-10-13 04:53:48 +0000290 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000291 // a more specific message to make it clear what is happening. If the call
292 // is written in a macro body, only warn if it has the warn_unused_result
293 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000294 if (const Decl *FD = CE->getCalleeDecl()) {
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000295 if (ShouldSuppress)
296 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000297 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000298 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
299 return;
300 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000301 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000302 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
303 return;
304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305 }
Erich Keane46441fd2019-07-25 15:10:56 +0000306 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
307 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
308 const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
309 A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
310 if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
311 return;
312 }
313 } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
314 if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
315
316 if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
317 R2, /*isCtor=*/false))
318 return;
319 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000320 } else if (ShouldSuppress)
321 return;
322
Erich Keane46441fd2019-07-25 15:10:56 +0000323 E = WarnExpr;
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000324 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000325 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000326 Diag(Loc, diag::err_arc_unused_init_message) << R1;
327 return;
328 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000329 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000330 if (MD) {
Erich Keane46441fd2019-07-25 15:10:56 +0000331 if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
332 R2, /*isCtor=*/false))
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000333 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000334 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000335 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
336 const Expr *Source = POE->getSyntacticForm();
337 if (isa<ObjCSubscriptRefExpr>(Source))
338 DiagID = diag::warn_unused_container_subscript_expr;
339 else
340 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000341 } else if (const CXXFunctionalCastExpr *FC
342 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000343 const Expr *E = FC->getSubExpr();
344 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
345 E = TE->getSubExpr();
346 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000347 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000348 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
349 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
350 if (!RD->getAttr<WarnUnusedAttr>())
351 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000352 }
John McCall2351cb92010-04-06 22:24:14 +0000353 // Diagnose "(void*) blah" as a typo for "(void) blah".
354 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
355 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
356 QualType T = TI->getType();
357
358 // We really do want to use the non-canonical type here.
359 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000360 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000361
362 Diag(Loc, diag::warn_unused_voidptr)
363 << FixItHint::CreateRemoval(TL.getStarLoc());
364 return;
365 }
366 }
367
Eli Friedmanc11535c2012-05-24 00:47:05 +0000368 if (E->isGLValue() && E->getType().isVolatileQualified()) {
369 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
370 return;
371 }
372
Craig Topperc3ec1492014-05-26 06:22:03 +0000373 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000374}
375
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000376void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
377 PushCompoundScope(IsStmtExpr);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000378}
379
380void Sema::ActOnFinishOfCompoundStmt() {
381 PopCompoundScope();
382}
383
384sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
385 return getCurFunction()->CompoundScopes.back();
386}
387
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000388StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
389 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
390 const unsigned NumElts = Elts.size();
391
Chris Lattnerd864daf2007-08-27 04:29:41 +0000392 // If we're in C89 mode, check that we don't have any decls after stmts. If
393 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000394 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000395 // Note that __extension__ can be around a decl.
396 unsigned i = 0;
397 // Skip over all declarations.
398 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
399 /*empty*/;
400
401 // We found the end of the list or a statement. Scan for another declstmt.
402 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
403 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000404
Chris Lattnerd864daf2007-08-27 04:29:41 +0000405 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000406 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000407 Diag(D->getLocation(), diag::ext_mixed_decls_code);
408 }
409 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000410
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000411 // Check for suspicious empty body (null statement) in `for' and `while'
412 // statements. Don't do anything for template instantiations, this just adds
413 // noise.
414 if (NumElts != 0 && !CurrentInstantiationScope &&
415 getCurCompoundScope().HasEmptyLoopBodies) {
416 for (unsigned i = 0; i != NumElts - 1; ++i)
417 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
418 }
419
Benjamin Kramer07420902017-12-24 16:24:20 +0000420 return CompoundStmt::Create(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000421}
422
Richard Smithef6c43d2018-07-26 18:41:30 +0000423ExprResult
424Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
425 if (!Val.get())
426 return Val;
427
428 if (DiagnoseUnexpandedParameterPack(Val.get()))
429 return ExprError();
430
431 // If we're not inside a switch, let the 'case' statement handling diagnose
432 // this. Just clean up after the expression as best we can.
Richard Smith40c3d6e32019-09-19 22:00:16 +0000433 if (getCurFunction()->SwitchStack.empty())
434 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
435 getLangOpts().CPlusPlus11);
Richard Smithef6c43d2018-07-26 18:41:30 +0000436
Richard Smith40c3d6e32019-09-19 22:00:16 +0000437 Expr *CondExpr =
438 getCurFunction()->SwitchStack.back().getPointer()->getCond();
439 if (!CondExpr)
440 return ExprError();
441 QualType CondType = CondExpr->getType();
Richard Smithef6c43d2018-07-26 18:41:30 +0000442
Richard Smith40c3d6e32019-09-19 22:00:16 +0000443 auto CheckAndFinish = [&](Expr *E) {
444 if (CondType->isDependentType() || E->isTypeDependent())
445 return ExprResult(E);
Richard Smithef6c43d2018-07-26 18:41:30 +0000446
Richard Smith40c3d6e32019-09-19 22:00:16 +0000447 if (getLangOpts().CPlusPlus11) {
448 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
449 // constant expression of the promoted type of the switch condition.
450 llvm::APSInt TempVal;
451 return CheckConvertedConstantExpression(E, CondType, TempVal,
452 CCEK_CaseValue);
453 }
Richard Smithef6c43d2018-07-26 18:41:30 +0000454
Richard Smith40c3d6e32019-09-19 22:00:16 +0000455 ExprResult ER = E;
456 if (!E->isValueDependent())
457 ER = VerifyIntegerConstantExpression(E);
458 if (!ER.isInvalid())
459 ER = DefaultLvalueConversion(ER.get());
460 if (!ER.isInvalid())
461 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
462 if (!ER.isInvalid())
463 ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
464 return ER;
465 };
Richard Smithef6c43d2018-07-26 18:41:30 +0000466
Richard Smith40c3d6e32019-09-19 22:00:16 +0000467 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
468 if (Converted.get() == Val.get())
469 Converted = CheckAndFinish(Val.get());
470 return Converted;
Richard Smithef6c43d2018-07-26 18:41:30 +0000471}
472
John McCalldadc5752010-08-24 06:29:42 +0000473StmtResult
Richard Smithef6c43d2018-07-26 18:41:30 +0000474Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
475 SourceLocation DotDotDotLoc, ExprResult RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000476 SourceLocation ColonLoc) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000477 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
478 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
479 : RHSVal.isInvalid() || RHSVal.get()) &&
480 "missing RHS value");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000481
John McCallaab3e412010-08-25 08:40:02 +0000482 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000483 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000484 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000485 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000486
Richard Smithef6c43d2018-07-26 18:41:30 +0000487 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
488 getCurFunction()->SwitchStack.back().setInt(true);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000489 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000490 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000491
Bruno Ricci5b30571752018-10-28 12:30:53 +0000492 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
493 CaseLoc, DotDotDotLoc, ColonLoc);
Richard Smithef6c43d2018-07-26 18:41:30 +0000494 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000495 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000496}
497
Chris Lattner34a22092009-03-04 04:23:07 +0000498/// ActOnCaseStmtBody - This installs a statement as the body of a case.
Aaron Ballmand9141742018-12-21 21:11:36 +0000499void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
Aaron Ballmand9141742018-12-21 21:11:36 +0000500 cast<CaseStmt>(S)->setSubStmt(SubStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000501}
502
John McCalldadc5752010-08-24 06:29:42 +0000503StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000504Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000505 Stmt *SubStmt, Scope *CurScope) {
John McCallaab3e412010-08-25 08:40:02 +0000506 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000507 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000508 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000509 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000510
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000511 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Richard Smithef6c43d2018-07-26 18:41:30 +0000512 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000513 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000514}
515
John McCalldadc5752010-08-24 06:29:42 +0000516StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000517Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
518 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000519 // If the label was multiply defined, reject it now.
520 if (TheDecl->getStmt()) {
521 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
522 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000523 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000524 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000525
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000526 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000527 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
528 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000529 if (!TheDecl->isGnuLocal()) {
530 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000531 if (!TheDecl->isMSAsmLabel()) {
532 // Don't update the location of MS ASM labels. These will result in
533 // a diagnostic, and changing the location here will mess that up.
534 TheDecl->setLocation(IdentLoc);
535 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000536 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000537 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000538}
539
Richard Smithc202b282012-04-14 00:33:13 +0000540StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000541 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000542 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000543 // Fill in the declaration and return it.
544 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000545 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000546}
547
Richard Trieufaca2d82016-02-18 23:58:40 +0000548namespace {
549class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
550 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
551 Sema &SemaRef;
552public:
553 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
554 void VisitBinaryOperator(BinaryOperator *E) {
555 if (E->getOpcode() == BO_Comma)
556 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
557 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
558 }
559};
560}
561
John McCalldadc5752010-08-24 06:29:42 +0000562StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000563Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
564 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000565 Stmt *thenStmt, SourceLocation ElseLoc,
566 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000567 if (Cond.isInvalid())
568 Cond = ConditionResult(
569 *this, nullptr,
570 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
571 Context.BoolTy, VK_RValue),
572 IfLoc),
573 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000574
Richard Smithb130fe72016-06-23 19:16:49 +0000575 Expr *CondExpr = Cond.get().second;
Richard Trieuf3713802018-10-25 01:08:00 +0000576 // Only call the CommaVisitor when not C89 due to differences in scope flags.
577 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
578 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
Richard Smithb130fe72016-06-23 19:16:49 +0000579 CommaVisitor(*this).Visit(CondExpr);
580
Hans Wennborg59ad1502017-11-20 17:48:54 +0000581 if (!elseStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000582 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
Hans Wennborg95419752017-11-20 17:38:16 +0000583 diag::warn_empty_if_body);
Richard Smithb130fe72016-06-23 19:16:49 +0000584
Richard Smitha547eb22016-07-14 00:11:03 +0000585 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
586 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000587}
588
589StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000590 Stmt *InitStmt, ConditionResult Cond,
591 Stmt *thenStmt, SourceLocation ElseLoc,
592 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000593 if (Cond.isInvalid())
594 return StmtError();
595
Erik Pilkington5cd57172016-08-16 17:44:11 +0000596 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Reid Kleckner87a31802018-03-12 21:43:02 +0000597 setFunctionHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000598
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000599 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
600 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000601}
Steve Naroff86272ea2007-05-29 02:14:17 +0000602
Chris Lattner67998452007-08-23 18:29:20 +0000603namespace {
604 struct CaseCompareFunctor {
605 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
606 const llvm::APSInt &RHS) {
607 return LHS.first < RHS;
608 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000609 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
610 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
611 return LHS.first < RHS.first;
612 }
Chris Lattner67998452007-08-23 18:29:20 +0000613 bool operator()(const llvm::APSInt &LHS,
614 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
615 return LHS < RHS.first;
616 }
617 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000618}
Chris Lattner67998452007-08-23 18:29:20 +0000619
Chris Lattner4b2ff022007-09-21 18:15:22 +0000620/// CmpCaseVals - Comparison predicate for sorting case values.
621///
622static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
623 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
624 if (lhs.first < rhs.first)
625 return true;
626
627 if (lhs.first == rhs.first &&
628 lhs.second->getCaseLoc().getRawEncoding()
629 < rhs.second->getCaseLoc().getRawEncoding())
630 return true;
631 return false;
632}
633
Douglas Gregorbd6839732010-02-08 22:24:16 +0000634/// CmpEnumVals - Comparison predicate for sorting enumeration values.
635///
636static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
637 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
638{
639 return lhs.first < rhs.first;
640}
641
642/// EqEnumVals - Comparison preficate for uniqing enumeration values.
643///
644static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
645 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
646{
647 return lhs.first == rhs.first;
648}
649
Chris Lattnera96d4272009-10-16 16:45:22 +0000650/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
651/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000652static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000653 if (const auto *FE = dyn_cast<FullExpr>(E))
654 E = FE->getSubExpr();
Gabor Horvath64c32412017-08-09 08:57:09 +0000655 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
656 if (ImpCast->getCastKind() != CK_IntegralCast) break;
657 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000658 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000659 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000660}
661
Richard Smith03a4aa32016-06-23 19:02:52 +0000662ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000663 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
664 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000665
Douglas Gregore2b37442012-05-04 22:38:52 +0000666 public:
667 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000668 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
669 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000670
Craig Toppere14c0f82014-03-12 04:55:44 +0000671 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
672 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000673 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
674 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000675
Craig Toppere14c0f82014-03-12 04:55:44 +0000676 SemaDiagnosticBuilder diagnoseIncomplete(
677 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000678 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
679 << T << Cond->getSourceRange();
680 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000681
Craig Toppere14c0f82014-03-12 04:55:44 +0000682 SemaDiagnosticBuilder diagnoseExplicitConv(
683 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000684 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
685 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000686
Craig Toppere14c0f82014-03-12 04:55:44 +0000687 SemaDiagnosticBuilder noteExplicitConv(
688 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000689 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
690 << ConvTy->isEnumeralType() << ConvTy;
691 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000692
Craig Toppere14c0f82014-03-12 04:55:44 +0000693 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
694 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000695 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
696 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000697
Craig Toppere14c0f82014-03-12 04:55:44 +0000698 SemaDiagnosticBuilder noteAmbiguous(
699 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000700 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
701 << ConvTy->isEnumeralType() << ConvTy;
702 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000703
Craig Toppere14c0f82014-03-12 04:55:44 +0000704 SemaDiagnosticBuilder diagnoseConversion(
705 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000706 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000707 }
708 } SwitchDiagnoser(Cond);
709
Richard Smith03a4aa32016-06-23 19:02:52 +0000710 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000711 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000712 if (CondResult.isInvalid())
713 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Richard Smithef6c43d2018-07-26 18:41:30 +0000715 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
716 // failed and produced a diagnostic.
717 Cond = CondResult.get();
718 if (!Cond->isTypeDependent() &&
719 !Cond->getType()->isIntegralOrEnumerationType())
720 return ExprError();
721
John McCall5939b162011-08-06 07:30:58 +0000722 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smithef6c43d2018-07-26 18:41:30 +0000723 return UsualUnaryConversions(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +0000724}
John McCall5939b162011-08-06 07:30:58 +0000725
Richard Smithc7a05a92016-06-29 21:17:59 +0000726StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
727 Stmt *InitStmt, ConditionResult Cond) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000728 Expr *CondExpr = Cond.get().second;
729 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
730
731 if (CondExpr && !CondExpr->isTypeDependent()) {
732 // We have already converted the expression to an integral or enumeration
733 // type, when we parsed the switch condition. If we don't have an
734 // appropriate type now, enter the switch scope but remember that it's
735 // invalid.
736 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
737 "invalid condition type");
738 if (CondExpr->isKnownToHaveBooleanValue()) {
739 // switch(bool_expr) {...} is often a programmer error, e.g.
740 // switch(n && mask) { ... } // Doh - should be "n & mask".
741 // One can always use an if statement instead of switch(bool_expr).
742 Diag(SwitchLoc, diag::warn_bool_switch_condition)
743 << CondExpr->getSourceRange();
744 }
745 }
John McCalla95172b2010-08-01 00:26:45 +0000746
Reid Kleckner87a31802018-03-12 21:43:02 +0000747 setFunctionHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000748
Bruno Riccie2806f82018-10-29 16:12:37 +0000749 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
Richard Smithef6c43d2018-07-26 18:41:30 +0000750 getCurFunction()->SwitchStack.push_back(
751 FunctionScopeInfo::SwitchInfo(SS, false));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000752 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000753}
754
Gabor Greif16e02862010-10-01 22:05:14 +0000755static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000756 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000757 Val.setIsSigned(IsSigned);
758}
759
Richard Smith077d0832014-08-04 00:40:48 +0000760/// Check the specified case value is in range for the given unpromoted switch
761/// type.
762static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
763 unsigned UnpromotedWidth, bool UnpromotedSign) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000764 // In C++11 onwards, this is checked by the language rules.
765 if (S.getLangOpts().CPlusPlus11)
766 return;
767
Richard Smith077d0832014-08-04 00:40:48 +0000768 // If the case value was signed and negative and the switch expression is
769 // unsigned, don't bother to warn: this is implementation-defined behavior.
770 // FIXME: Introduce a second, default-ignored warning for this case?
771 if (UnpromotedWidth < Val.getBitWidth()) {
772 llvm::APSInt ConvVal(Val);
773 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
774 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
775 // FIXME: Use different diagnostics for overflow in conversion to promoted
776 // type versus "switch expression cannot have this value". Use proper
777 // IntRange checking rather than just looking at the unpromoted type here.
778 if (ConvVal != Val)
779 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
780 << ConvVal.toString(10);
781 }
782}
783
Alexis Hunt724f14e2014-11-28 00:53:20 +0000784typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
785
Dmitri Gribenko58683752013-12-05 22:52:07 +0000786/// Returns true if we should emit a diagnostic about this case expression not
787/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000788static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000789 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000790 const Expr *CaseExpr,
791 EnumValsTy::iterator &EI,
792 EnumValsTy::iterator &EIEnd,
793 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000794 if (!ED->isClosed())
795 return false;
796
Alexis Hunt724f14e2014-11-28 00:53:20 +0000797 if (const DeclRefExpr *DRE =
798 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000799 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000800 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000801 QualType EnumType = S.Context.getTypeDeclType(ED);
802 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
803 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000804 return false;
805 }
806 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000807
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000808 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000809 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000810
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000811 while (EI != EIEnd && EI->first < Val)
812 EI++;
813
814 if (EI != EIEnd && EI->first == Val)
815 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000816
Dmitri Gribenko58683752013-12-05 22:52:07 +0000817 return true;
818}
819
Gabor Horvath64c32412017-08-09 08:57:09 +0000820static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
821 const Expr *Case) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000822 QualType CondType = Cond->getType();
Gabor Horvath64c32412017-08-09 08:57:09 +0000823 QualType CaseType = Case->getType();
824
825 const EnumType *CondEnumType = CondType->getAs<EnumType>();
826 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
827 if (!CondEnumType || !CaseEnumType)
828 return;
829
Gabor Horvathb57e2642017-08-09 12:34:58 +0000830 // Ignore anonymous enums.
Richard Trieu285c9362017-09-09 00:25:05 +0000831 if (!CondEnumType->getDecl()->getIdentifier() &&
832 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000833 return;
Richard Trieu285c9362017-09-09 00:25:05 +0000834 if (!CaseEnumType->getDecl()->getIdentifier() &&
835 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000836 return;
837
Gabor Horvath64c32412017-08-09 08:57:09 +0000838 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
839 return;
840
Gabor Horvath0284a202017-08-09 20:56:43 +0000841 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000842 << CondType << CaseType << Cond->getSourceRange()
843 << Case->getSourceRange();
844}
845
John McCalldadc5752010-08-24 06:29:42 +0000846StmtResult
John McCallb268a282010-08-23 23:25:46 +0000847Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
848 Stmt *BodyStmt) {
849 SwitchStmt *SS = cast<SwitchStmt>(Switch);
Richard Smithef6c43d2018-07-26 18:41:30 +0000850 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
851 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
John McCallaab3e412010-08-25 08:40:02 +0000852 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000853
David Majnemer418ad3f2014-12-15 07:46:12 +0000854 getCurFunction()->SwitchStack.pop_back();
855
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000856 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000857 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000858
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000859 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000860 if (!CondExpr) return StmtError();
861
862 QualType CondType = CondExpr->getType();
863
Chris Lattnera96d4272009-10-16 16:45:22 +0000864 // C++ 6.4.2.p2:
865 // Integral promotions are performed (on the switch condition).
866 //
867 // A case value unrepresentable by the original switch condition
868 // type (before the promotion) doesn't make sense, even when it can
869 // be represented by the promoted type. Therefore we need to find
870 // the pre-promotion type of the switch condition.
Richard Smithef6c43d2018-07-26 18:41:30 +0000871 const Expr *CondExprBeforePromotion = CondExpr;
872 QualType CondTypeBeforePromotion =
873 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000874
Richard Smith077d0832014-08-04 00:40:48 +0000875 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000876 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000877 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000878 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000879 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
880 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
881
882 // Get the width and signedness that the condition might actually have, for
883 // warning purposes.
884 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
885 // type.
886 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000887 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000888 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000889 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000891 // Accumulate all of the case values in a vector so that we can sort them
892 // and detect duplicates. This vector contains the APInt for the case after
893 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000894 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000895 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000897 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000898 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
899 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000900
Craig Topperc3ec1492014-05-26 06:22:03 +0000901 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattner10cb5e52007-08-23 06:23:56 +0000903 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000904
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000905 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000906 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000907
Anders Carlsson51873c22007-07-22 07:07:56 +0000908 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000909 if (TheDefaultStmt) {
910 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000911 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000912
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000913 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000914 // we'll return a valid AST. This requires recursing down the AST and
915 // finding it, not something we are set up to do right now. For now,
916 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000917 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000918 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000919 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000921 } else {
922 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattnera65e1f32008-01-16 19:17:22 +0000924 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000925
Richard Smithef6c43d2018-07-26 18:41:30 +0000926 if (Lo->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000927 HasDependentValue = true;
928 break;
929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930
Richard Smithef6c43d2018-07-26 18:41:30 +0000931 // We already verified that the expression has a constant value;
932 // get that value (prior to conversions).
933 const Expr *LoBeforePromotion = Lo;
934 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
935 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000936
Richard Smith077d0832014-08-04 00:40:48 +0000937 // Check the unconverted value is within the range of possible values of
938 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000939 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
940 CondIsSignedBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000941
Richard Smithef6c43d2018-07-26 18:41:30 +0000942 // FIXME: This duplicates the check performed for warn_not_in_enum below.
943 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
944 LoBeforePromotion);
945
Richard Smith077d0832014-08-04 00:40:48 +0000946 // Convert the value to the same width/sign as the condition.
947 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000948
Chris Lattner10cb5e52007-08-23 06:23:56 +0000949 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000950 if (CS->getRHS()) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000951 if (CS->getRHS()->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000952 HasDependentValue = true;
953 break;
954 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000955 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000956 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000957 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000958 }
959 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000960
961 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000962 // If we don't have a default statement, check whether the
963 // condition is constant.
964 llvm::APSInt ConstantCondValue;
965 bool HasConstantCond = false;
Simon Pilgrim0e827222019-10-05 13:20:51 +0000966 if (!TheDefaultStmt) {
Fangrui Song407659a2018-11-30 23:41:18 +0000967 Expr::EvalResult Result;
968 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
Richard Smith077d0832014-08-04 00:40:48 +0000969 Expr::SE_AllowSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +0000970 if (Result.Val.isInt())
971 ConstantCondValue = Result.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +0000972 assert(!HasConstantCond ||
973 (ConstantCondValue.getBitWidth() == CondWidth &&
974 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000975 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000976 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000977
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000978 // Sort all the scalar case values so we can easily detect duplicates.
Fangrui Song899d1392019-04-24 14:43:05 +0000979 llvm::stable_sort(CaseVals, CmpCaseVals);
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000980
981 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000982 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
983 if (ShouldCheckConstantCond &&
984 CaseVals[i].first == ConstantCondValue)
985 ShouldCheckConstantCond = false;
986
987 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000988 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000989 // First, determine if either case value has a name
990 StringRef PrevString, CurrString;
991 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
992 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
993 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
994 PrevString = DeclRef->getDecl()->getName();
995 }
996 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
997 CurrString = DeclRef->getDecl()->getName();
998 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000999 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +00001000 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +00001001
1002 if (PrevString == CurrString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001003 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1004 diag::err_duplicate_case)
1005 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +00001006 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001007 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1008 diag::err_duplicate_case_differing_expr)
1009 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
1010 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
1011 << CaseValStr;
Douglas Gregor9841df62012-05-16 05:32:58 +00001012
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001013 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001014 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001015 // FIXME: We really want to remove the bogus case stmt from the
1016 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001017 CaseListIsErroneous = true;
1018 }
1019 }
1020 }
Mike Stump11289f42009-09-09 15:08:12 +00001021
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001022 // Detect duplicate case ranges, which usually don't exist at all in
1023 // the first place.
1024 if (!CaseRanges.empty()) {
1025 // Sort all the case ranges by their low value so we can easily detect
1026 // overlaps between ranges.
Fangrui Song899d1392019-04-24 14:43:05 +00001027 llvm::stable_sort(CaseRanges);
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001029 // Scan the ranges, computing the high values and removing empty ranges.
1030 std::vector<llvm::APSInt> HiVals;
1031 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +00001032 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001033 CaseStmt *CR = CaseRanges[i].second;
1034 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +00001035
Richard Smithef6c43d2018-07-26 18:41:30 +00001036 const Expr *HiBeforePromotion = Hi;
1037 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1038 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001039
Richard Smith077d0832014-08-04 00:40:48 +00001040 // Check the unconverted value is within the range of possible values of
1041 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001042 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
Richard Smith077d0832014-08-04 00:40:48 +00001043 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1044
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001045 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001046 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001047
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001048 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001049 if (LoVal > HiVal) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001050 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001051 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001052 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001053 --i;
1054 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001055 continue;
1056 }
John McCalld3dfbd62010-05-18 03:19:21 +00001057
1058 if (ShouldCheckConstantCond &&
1059 LoVal <= ConstantCondValue &&
1060 ConstantCondValue <= HiVal)
1061 ShouldCheckConstantCond = false;
1062
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001063 HiVals.push_back(HiVal);
1064 }
Mike Stump11289f42009-09-09 15:08:12 +00001065
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001066 // Rescan the ranges, looking for overlap with singleton values and other
1067 // ranges. Since the range list is sorted, we only need to compare case
1068 // ranges with their neighbors.
1069 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1070 llvm::APSInt &CRLo = CaseRanges[i].first;
1071 llvm::APSInt &CRHi = HiVals[i];
1072 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001074 // Check to see whether the case range overlaps with any
1075 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001076 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001077 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001079 // Find the smallest value >= the lower bound. If I is in the
1080 // case range, then we have overlap.
Fangrui Song7264a472019-07-03 08:13:17 +00001081 CaseValsTy::iterator I =
1082 llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001083 if (I != CaseVals.end() && I->first < CRHi) {
1084 OverlapVal = I->first; // Found overlap with scalar.
1085 OverlapStmt = I->second;
1086 }
Mike Stump11289f42009-09-09 15:08:12 +00001087
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001088 // Find the smallest value bigger than the upper bound.
1089 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1090 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1091 OverlapVal = (I-1)->first; // Found overlap with scalar.
1092 OverlapStmt = (I-1)->second;
1093 }
Mike Stump11289f42009-09-09 15:08:12 +00001094
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001095 // Check to see if this case stmt overlaps with the subsequent
1096 // case range.
1097 if (i && CRLo <= HiVals[i-1]) {
1098 OverlapVal = HiVals[i-1]; // Found overlap with range.
1099 OverlapStmt = CaseRanges[i-1].second;
1100 }
Mike Stump11289f42009-09-09 15:08:12 +00001101
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001102 if (OverlapStmt) {
1103 // If we have a duplicate, report it.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001104 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1105 << OverlapVal.toString(10);
1106 Diag(OverlapStmt->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001107 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001108 // FIXME: We really want to remove the bogus case stmt from the
1109 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001110 CaseListIsErroneous = true;
1111 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001112 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001113 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001114
John McCalld3dfbd62010-05-18 03:19:21 +00001115 // Complain if we have a constant condition and we didn't find a match.
Richard Smithef6c43d2018-07-26 18:41:30 +00001116 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1117 ShouldCheckConstantCond) {
John McCalld3dfbd62010-05-18 03:19:21 +00001118 // TODO: it would be nice if we printed enums as enums, chars as
1119 // chars, etc.
1120 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1121 << ConstantCondValue.toString(10)
1122 << CondExpr->getSourceRange();
1123 }
1124
1125 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001126 // values. We only issue a warning if there is not 'default:', but
1127 // we still do the analysis to preserve this information in the AST
1128 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001129 //
Chris Lattner51679082010-09-16 17:09:42 +00001130 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001131
Douglas Gregorbd6839732010-02-08 22:24:16 +00001132 // If switch has default case, then ignore it.
Richard Smithef6c43d2018-07-26 18:41:30 +00001133 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1134 ET && ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001135 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001136 EnumValsTy EnumVals;
1137
John McCalld3dfbd62010-05-18 03:19:21 +00001138 // Gather all enum values, set their type and sort them,
1139 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001140 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001141 llvm::APSInt Val = EDI->getInitVal();
1142 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001143 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001144 }
Fangrui Song899d1392019-04-24 14:43:05 +00001145 llvm::stable_sort(EnumVals, CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001146 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001147 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001148
1149 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001150 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001151 CI != CaseVals.end(); CI++) {
1152 Expr *CaseExpr = CI->second->getLHS();
1153 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1154 CI->first))
1155 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1156 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001157 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001158
David Blaikiee476f972012-01-22 02:31:55 +00001159 // See which of case ranges aren't in enum
1160 EI = EnumVals.begin();
1161 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001162 RI != CaseRanges.end(); RI++) {
1163 Expr *CaseExpr = RI->second->getLHS();
1164 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1165 RI->first))
1166 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1167 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001168
Chad Rosier02a84392012-08-10 17:56:09 +00001169 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001170 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1171 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001172
1173 CaseExpr = RI->second->getRHS();
1174 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1175 Hi))
1176 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1177 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Ted Kremenekc42f3452010-09-09 00:05:53 +00001180 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001181 auto CI = CaseVals.begin();
1182 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001183 bool hasCasesNotInSwitch = false;
1184
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001185 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186
Erik Pilkington3e4e3b12018-09-05 19:13:27 +00001187 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1188 // Don't warn about omitted unavailable EnumConstantDecls.
1189 switch (EI->second->getAvailability()) {
1190 case AR_Deprecated:
1191 // Omitting a deprecated constant is ok; it should never materialize.
1192 case AR_Unavailable:
1193 continue;
1194
1195 case AR_NotYetIntroduced:
1196 // Partially available enum constants should be present. Note that we
1197 // suppress -Wunguarded-availability diagnostics for such uses.
1198 case AR_Available:
1199 break;
1200 }
1201
David Blaikiea558ee82019-05-02 16:30:49 +00001202 if (EI->second->hasAttr<UnusedAttr>())
1203 continue;
1204
Chris Lattner51679082010-09-16 17:09:42 +00001205 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001206 while (CI != CaseVals.end() && CI->first < EI->first)
1207 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208
Douglas Gregorbd6839732010-02-08 22:24:16 +00001209 if (CI != CaseVals.end() && CI->first == EI->first)
1210 continue;
1211
Ted Kremenekc42f3452010-09-09 00:05:53 +00001212 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001213 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001214 llvm::APSInt Hi =
1215 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001216 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001217 if (EI->first <= Hi)
1218 break;
1219 }
1220
Ted Kremenekc42f3452010-09-09 00:05:53 +00001221 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001222 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001223 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001224 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001226
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001227 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001228 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001229
Chris Lattner51679082010-09-16 17:09:42 +00001230 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001231 if (!UnhandledNames.empty()) {
1232 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1233 TheDefaultStmt ? diag::warn_def_missing_case
1234 : diag::warn_missing_case)
1235 << (int)UnhandledNames.size();
1236
1237 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1238 I != E; ++I)
1239 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001240 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001241
1242 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001243 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001244 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001245 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001246
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001247 if (BodyStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001248 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001249 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001250
Mike Stump87c57ac2009-05-16 07:39:55 +00001251 // FIXME: If the case list was broken is some way, we don't have a good system
1252 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001253 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001254 return StmtError();
1255
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001256 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001257}
1258
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001259void
1260Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1261 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001262 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001263 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001264
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001265 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001266 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001267 SrcType->isIntegerType()) {
1268 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1269 SrcExpr->isIntegerConstantExpr(Context)) {
1270 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001271 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001272 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1273
1274 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001275 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001276 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001277
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001278 if (!ED->isClosed())
1279 return;
1280
Alexis Hunt724f14e2014-11-28 00:53:20 +00001281 if (ED->hasAttr<FlagEnumAttr>()) {
1282 if (!IsValueInFlagEnum(ED, RhsVal, true))
1283 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001284 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001285 } else {
1286 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1287 EnumValsTy;
1288 EnumValsTy EnumVals;
1289
1290 // Gather all enum values, set their type and sort them,
1291 // allowing easier comparison with rhs constant.
1292 for (auto *EDI : ED->enumerators()) {
1293 llvm::APSInt Val = EDI->getInitVal();
1294 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1295 EnumVals.push_back(std::make_pair(Val, EDI));
1296 }
1297 if (EnumVals.empty())
1298 return;
Fangrui Song899d1392019-04-24 14:43:05 +00001299 llvm::stable_sort(EnumVals, CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001300 EnumValsTy::iterator EIend =
1301 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1302
1303 // See which values aren't in the enum.
1304 EnumValsTy::const_iterator EI = EnumVals.begin();
1305 while (EI != EIend && EI->first < RhsVal)
1306 EI++;
1307 if (EI == EIend || EI->first != RhsVal) {
1308 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1309 << DstType.getUnqualifiedType();
1310 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001311 }
1312 }
1313 }
1314}
1315
Richard Smith03a4aa32016-06-23 19:02:52 +00001316StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1317 Stmt *Body) {
1318 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001319 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320
Richard Smith03a4aa32016-06-23 19:02:52 +00001321 auto CondVal = Cond.get();
1322 CheckBreakContinueBinding(CondVal.second);
1323
1324 if (CondVal.second &&
1325 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1326 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001327
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001328 if (isa<NullStmt>(Body))
1329 getCurCompoundScope().setHasEmptyLoopBodies();
1330
Bruno Riccibacf7512018-10-30 13:42:41 +00001331 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1332 WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001333}
1334
John McCalldadc5752010-08-24 06:29:42 +00001335StmtResult
John McCallb268a282010-08-23 23:25:46 +00001336Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001337 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001338 Expr *Cond, SourceLocation CondRParen) {
1339 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001340
Serge Pavlov09f99242014-01-23 15:05:00 +00001341 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001342 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001343 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001344 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001345 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001346
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001347 CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
John McCallb268a282010-08-23 23:25:46 +00001348 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001349 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001350 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Richard Trieuf3713802018-10-25 01:08:00 +00001352 // Only call the CommaVisitor for C89 due to differences in scope flags.
1353 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1354 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1355 CommaVisitor(*this).Visit(Cond);
1356
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001357 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001358}
1359
Richard Trieu451a5db2012-04-30 18:01:30 +00001360namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001361 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1362 using DeclSetVector =
1363 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1364 llvm::SmallPtrSet<VarDecl *, 8>>;
1365
Richard Trieu451a5db2012-04-30 18:01:30 +00001366 // This visitor will traverse a conditional statement and store all
1367 // the evaluated decls into a vector. Simple is set to true if none
1368 // of the excluded constructs are used.
1369 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001370 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001371 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001372 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001373 public:
1374 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001375
Richard Trieu5fb874a2017-06-02 04:24:46 +00001376 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001377 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001378 Inherited(S.Context),
1379 Decls(Decls),
1380 Ranges(Ranges),
1381 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001382
Richard Trieu9d228802013-05-31 22:46:45 +00001383 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001384
Richard Trieu9d228802013-05-31 22:46:45 +00001385 // Replaces the method in EvaluatedExprVisitor.
1386 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001387 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001388 }
1389
1390 // Any Stmt not whitelisted will cause the condition to be marked complex.
1391 void VisitStmt(Stmt *S) {
1392 Simple = false;
1393 }
1394
1395 void VisitBinaryOperator(BinaryOperator *E) {
1396 Visit(E->getLHS());
1397 Visit(E->getRHS());
1398 }
1399
1400 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001401 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001402 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001403
Richard Trieu9d228802013-05-31 22:46:45 +00001404 void VisitUnaryOperator(UnaryOperator *E) {
1405 // Skip checking conditionals with derefernces.
1406 if (E->getOpcode() == UO_Deref)
1407 Simple = false;
1408 else
1409 Visit(E->getSubExpr());
1410 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001411
Richard Trieu9d228802013-05-31 22:46:45 +00001412 void VisitConditionalOperator(ConditionalOperator *E) {
1413 Visit(E->getCond());
1414 Visit(E->getTrueExpr());
1415 Visit(E->getFalseExpr());
1416 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001417
Richard Trieu9d228802013-05-31 22:46:45 +00001418 void VisitParenExpr(ParenExpr *E) {
1419 Visit(E->getSubExpr());
1420 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001421
Richard Trieu9d228802013-05-31 22:46:45 +00001422 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1423 Visit(E->getOpaqueValue()->getSourceExpr());
1424 Visit(E->getFalseExpr());
1425 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001426
Richard Trieu9d228802013-05-31 22:46:45 +00001427 void VisitIntegerLiteral(IntegerLiteral *E) { }
1428 void VisitFloatingLiteral(FloatingLiteral *E) { }
1429 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1430 void VisitCharacterLiteral(CharacterLiteral *E) { }
1431 void VisitGNUNullExpr(GNUNullExpr *E) { }
1432 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001433
Richard Trieu9d228802013-05-31 22:46:45 +00001434 void VisitDeclRefExpr(DeclRefExpr *E) {
1435 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
Richard Trieu6b13e892018-10-20 02:15:58 +00001436 if (!VD) {
1437 // Don't allow unhandled Decl types.
1438 Simple = false;
1439 return;
1440 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001441
Richard Trieu9d228802013-05-31 22:46:45 +00001442 Ranges.push_back(E->getSourceRange());
1443
1444 Decls.insert(VD);
1445 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001446
1447 }; // end class DeclExtractor
1448
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001449 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001450 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001451 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001452 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001453 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001454
Richard Trieu9d228802013-05-31 22:46:45 +00001455 public:
1456 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001457
Richard Trieu5fb874a2017-06-02 04:24:46 +00001458 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001459 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1460 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001461
Richard Trieu9d228802013-05-31 22:46:45 +00001462 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001463 }
1464
Richard Trieu9d228802013-05-31 22:46:45 +00001465 void VisitReturnStmt(ReturnStmt *S) {
1466 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001467 }
1468
Richard Trieu9d228802013-05-31 22:46:45 +00001469 void VisitBreakStmt(BreakStmt *S) {
1470 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001471 }
1472
Richard Trieu9d228802013-05-31 22:46:45 +00001473 void VisitGotoStmt(GotoStmt *S) {
1474 FoundDecl = true;
1475 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001476
Richard Trieu9d228802013-05-31 22:46:45 +00001477 void VisitCastExpr(CastExpr *E) {
1478 if (E->getCastKind() == CK_LValueToRValue)
1479 CheckLValueToRValueCast(E->getSubExpr());
1480 else
1481 Visit(E->getSubExpr());
1482 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001483
Richard Trieu9d228802013-05-31 22:46:45 +00001484 void CheckLValueToRValueCast(Expr *E) {
1485 E = E->IgnoreParenImpCasts();
1486
1487 if (isa<DeclRefExpr>(E)) {
1488 return;
1489 }
1490
1491 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1492 Visit(CO->getCond());
1493 CheckLValueToRValueCast(CO->getTrueExpr());
1494 CheckLValueToRValueCast(CO->getFalseExpr());
1495 return;
1496 }
1497
1498 if (BinaryConditionalOperator *BCO =
1499 dyn_cast<BinaryConditionalOperator>(E)) {
1500 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1501 CheckLValueToRValueCast(BCO->getFalseExpr());
1502 return;
1503 }
1504
1505 Visit(E);
1506 }
1507
1508 void VisitDeclRefExpr(DeclRefExpr *E) {
1509 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1510 if (Decls.count(VD))
1511 FoundDecl = true;
1512 }
1513
Steven Wu92910f62016-03-10 02:02:48 +00001514 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1515 // Only need to visit the semantics for POE.
1516 // SyntaticForm doesn't really use the Decal.
1517 for (auto *S : POE->semantics()) {
1518 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1519 // Look past the OVE into the expression it binds.
1520 Visit(OVE->getSourceExpr());
1521 else
1522 Visit(S);
1523 }
1524 }
1525
Richard Trieu9d228802013-05-31 22:46:45 +00001526 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001527
1528 }; // end class DeclMatcher
1529
1530 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1531 Expr *Third, Stmt *Body) {
1532 // Condition is empty
1533 if (!Second) return;
1534
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001535 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001536 Second->getBeginLoc()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001537 return;
1538
1539 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001540 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001541 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001542 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001543 DE.Visit(Second);
1544
1545 // Don't analyze complex conditionals.
1546 if (!DE.isSimple()) return;
1547
1548 // No decls found.
1549 if (Decls.size() == 0) return;
1550
Richard Trieu0030f1d2012-05-04 03:01:54 +00001551 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001552 for (auto *VD : Decls)
1553 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1554 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001555
1556 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1557 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1558 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1559 return;
1560
1561 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001562 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001563 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001564 } else {
1565 PDiag << (unsigned)Decls.size();
1566 for (auto *VD : Decls)
1567 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001568 }
1569
Richard Trieu5fb874a2017-06-02 04:24:46 +00001570 for (auto Range : Ranges)
1571 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001572
1573 S.Diag(Ranges.begin()->getBegin(), PDiag);
1574 }
1575
Richard Trieu4e7c9622013-08-06 21:31:54 +00001576 // If Statement is an incemement or decrement, return true and sets the
1577 // variables Increment and DRE.
1578 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1579 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001580 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1581 if (!Cleanups->cleanupsHaveSideEffects())
1582 Statement = Cleanups->getSubExpr();
1583
Richard Trieu4e7c9622013-08-06 21:31:54 +00001584 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1585 switch (UO->getOpcode()) {
1586 default: return false;
1587 case UO_PostInc:
1588 case UO_PreInc:
1589 Increment = true;
1590 break;
1591 case UO_PostDec:
1592 case UO_PreDec:
1593 Increment = false;
1594 break;
1595 }
1596 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1597 return DRE;
1598 }
1599
1600 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1601 FunctionDecl *FD = Call->getDirectCallee();
1602 if (!FD || !FD->isOverloadedOperator()) return false;
1603 switch (FD->getOverloadedOperator()) {
1604 default: return false;
1605 case OO_PlusPlus:
1606 Increment = true;
1607 break;
1608 case OO_MinusMinus:
1609 Increment = false;
1610 break;
1611 }
1612 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1613 return DRE;
1614 }
1615
1616 return false;
1617 }
1618
Serge Pavlov09f99242014-01-23 15:05:00 +00001619 // A visitor to determine if a continue or break statement is a
1620 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001621 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001622 SourceLocation BreakLoc;
1623 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001624 bool InSwitch = false;
1625
Richard Trieu4e7c9622013-08-06 21:31:54 +00001626 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001627 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001628 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001629 Visit(Body);
1630 }
1631
Eli Friedmane91b2e62017-07-04 00:52:24 +00001632 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001633
Eli Friedmane91b2e62017-07-04 00:52:24 +00001634 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001635 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001636 }
1637
Eli Friedmane91b2e62017-07-04 00:52:24 +00001638 void VisitBreakStmt(const BreakStmt* E) {
1639 if (!InSwitch)
1640 BreakLoc = E->getBreakLoc();
1641 }
1642
1643 void VisitSwitchStmt(const SwitchStmt* S) {
1644 if (const Stmt *Init = S->getInit())
1645 Visit(Init);
1646 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1647 Visit(CondVar);
1648 if (const Stmt *Cond = S->getCond())
1649 Visit(Cond);
1650
1651 // Don't return break statements from the body of a switch.
1652 InSwitch = true;
1653 if (const Stmt *Body = S->getBody())
1654 Visit(Body);
1655 InSwitch = false;
1656 }
1657
1658 void VisitForStmt(const ForStmt *S) {
1659 // Only visit the init statement of a for loop; the body
1660 // has a different break/continue scope.
1661 if (const Stmt *Init = S->getInit())
1662 Visit(Init);
1663 }
1664
1665 void VisitWhileStmt(const WhileStmt *) {
1666 // Do nothing; the children of a while loop have a different
1667 // break/continue scope.
1668 }
1669
1670 void VisitDoStmt(const DoStmt *) {
1671 // Do nothing; the children of a while loop have a different
1672 // break/continue scope.
1673 }
1674
1675 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1676 // Only visit the initialization of a for loop; the body
1677 // has a different break/continue scope.
Richard Smith8baa5002018-09-28 18:44:09 +00001678 if (const Stmt *Init = S->getInit())
1679 Visit(Init);
Eli Friedmane91b2e62017-07-04 00:52:24 +00001680 if (const Stmt *Range = S->getRangeStmt())
1681 Visit(Range);
1682 if (const Stmt *Begin = S->getBeginStmt())
1683 Visit(Begin);
1684 if (const Stmt *End = S->getEndStmt())
1685 Visit(End);
1686 }
1687
1688 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1689 // Only visit the initialization of a for loop; the body
1690 // has a different break/continue scope.
1691 if (const Stmt *Element = S->getElement())
1692 Visit(Element);
1693 if (const Stmt *Collection = S->getCollection())
1694 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001695 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001696
Serge Pavlov09f99242014-01-23 15:05:00 +00001697 bool ContinueFound() { return ContinueLoc.isValid(); }
1698 bool BreakFound() { return BreakLoc.isValid(); }
1699 SourceLocation GetContinueLoc() { return ContinueLoc; }
1700 SourceLocation GetBreakLoc() { return BreakLoc; }
1701
1702 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001703
1704 // Emit a warning when a loop increment/decrement appears twice per loop
1705 // iteration. The conditions which trigger this warning are:
1706 // 1) The last statement in the loop body and the third expression in the
1707 // for loop are both increment or both decrement of the same variable
1708 // 2) No continue statements in the loop body.
1709 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1710 // Return when there is nothing to check.
1711 if (!Body || !Third) return;
1712
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001713 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001714 Third->getBeginLoc()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001715 return;
1716
1717 // Get the last statement from the loop body.
1718 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1719 if (!CS || CS->body_empty()) return;
1720 Stmt *LastStmt = CS->body_back();
1721 if (!LastStmt) return;
1722
1723 bool LoopIncrement, LastIncrement;
1724 DeclRefExpr *LoopDRE, *LastDRE;
1725
1726 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1727 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1728
1729 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001730 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001731 if (LoopIncrement != LastIncrement ||
1732 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1733
Serge Pavlov09f99242014-01-23 15:05:00 +00001734 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001735
1736 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1737 << LastDRE->getDecl() << LastIncrement;
1738 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1739 << LoopIncrement;
1740 }
1741
Richard Trieu451a5db2012-04-30 18:01:30 +00001742} // end namespace
1743
Serge Pavlov09f99242014-01-23 15:05:00 +00001744
1745void Sema::CheckBreakContinueBinding(Expr *E) {
1746 if (!E || getLangOpts().CPlusPlus)
1747 return;
1748 BreakContinueFinder BCFinder(*this, E);
1749 Scope *BreakParent = CurScope->getBreakParent();
1750 if (BCFinder.BreakFound() && BreakParent) {
1751 if (BreakParent->getFlags() & Scope::SwitchScope) {
1752 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1753 } else {
1754 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1755 << "break";
1756 }
1757 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1758 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1759 << "continue";
1760 }
1761}
1762
Richard Smith03a4aa32016-06-23 19:02:52 +00001763StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1764 Stmt *First, ConditionResult Second,
1765 FullExprArg third, SourceLocation RParenLoc,
1766 Stmt *Body) {
1767 if (Second.isInvalid())
1768 return StmtError();
1769
David Blaikiebbafb8a2012-03-11 07:00:24 +00001770 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001771 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001772 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1773 // declare identifiers for objects having storage class 'auto' or
1774 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001775 for (auto *DI : DS->decls()) {
1776 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001777 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001778 VD = nullptr;
1779 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001780 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1781 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001782 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001783 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001784 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001785 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001786
Richard Smith03a4aa32016-06-23 19:02:52 +00001787 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001788 CheckBreakContinueBinding(third.get());
1789
Richard Smith03a4aa32016-06-23 19:02:52 +00001790 if (!Second.get().first)
1791 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1792 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001793 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001794
Richard Smith03a4aa32016-06-23 19:02:52 +00001795 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001796 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001797 Second.get().second->getExprLoc()))
1798 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001799
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001800 Expr *Third = third.release().getAs<Expr>();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001801 if (isa<NullStmt>(Body))
1802 getCurCompoundScope().setHasEmptyLoopBodies();
1803
Richard Smith03a4aa32016-06-23 19:02:52 +00001804 return new (Context)
1805 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1806 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001807}
1808
John McCall34376a62010-12-04 03:47:34 +00001809/// In an Objective C collection iteration statement:
1810/// for (x in y)
1811/// x can be an arbitrary l-value expression. Bind it up as a
1812/// full-expression.
1813StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001814 // Reduce placeholder expressions here. Note that this rejects the
1815 // use of pseudo-object l-values in this position.
1816 ExprResult result = CheckPlaceholderExpr(E);
1817 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001818 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001819
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001820 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00001821 if (FullExpr.isInvalid())
1822 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001823 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001824}
1825
John McCall53848232011-07-27 01:07:15 +00001826ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001827Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1828 if (!collection)
1829 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001830
Kaelyn Takata15867822014-11-21 18:48:04 +00001831 ExprResult result = CorrectDelayedTyposInExpr(collection);
1832 if (!result.isUsable())
1833 return ExprError();
1834 collection = result.get();
1835
John McCall53848232011-07-27 01:07:15 +00001836 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001837 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001838
1839 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001840 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001841 if (result.isInvalid())
1842 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001843 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001844
1845 // The operand needs to have object-pointer type.
1846 // TODO: should we do a contextual conversion?
1847 const ObjCObjectPointerType *pointerType =
1848 collection->getType()->getAs<ObjCObjectPointerType>();
1849 if (!pointerType)
1850 return Diag(forLoc, diag::err_collection_expr_type)
1851 << collection->getType() << collection->getSourceRange();
1852
1853 // Check that the operand provides
1854 // - countByEnumeratingWithState:objects:count:
1855 const ObjCObjectType *objectType = pointerType->getObjectType();
1856 ObjCInterfaceDecl *iface = objectType->getInterface();
1857
1858 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001859 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001860 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001861 (getLangOpts().ObjCAutoRefCount
1862 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1863 diag::err_arc_collection_forward, collection)
1864 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001865 // Otherwise, if we have any useful type information, check that
1866 // the type declares the appropriate method.
1867 } else if (iface || !objectType->qual_empty()) {
1868 IdentifierInfo *selectorIdents[] = {
1869 &Context.Idents.get("countByEnumeratingWithState"),
1870 &Context.Idents.get("objects"),
1871 &Context.Idents.get("count")
1872 };
1873 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1874
Craig Topperc3ec1492014-05-26 06:22:03 +00001875 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001876
1877 // If there's an interface, look in both the public and private APIs.
1878 if (iface) {
1879 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001880 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001881 }
1882
1883 // Also check protocol qualifiers.
1884 if (!method)
1885 method = LookupMethodInQualifiedType(selector, pointerType,
1886 /*instance*/ true);
1887
1888 // If we didn't find it anywhere, give up.
1889 if (!method) {
1890 Diag(forLoc, diag::warn_collection_expr_type)
1891 << collection->getType() << selector << collection->getSourceRange();
1892 }
1893
1894 // TODO: check for an incompatible signature?
1895 }
1896
1897 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001898 return collection;
John McCall53848232011-07-27 01:07:15 +00001899}
1900
John McCalldadc5752010-08-24 06:29:42 +00001901StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001902Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001903 Stmt *First, Expr *collection,
1904 SourceLocation RParenLoc) {
Reid Kleckner87a31802018-03-12 21:43:02 +00001905 setFunctionHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001906
1907 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001908 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001909
Fariborz Jahanian93977672008-01-10 20:33:58 +00001910 if (First) {
1911 QualType FirstType;
1912 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001913 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001914 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1915 diag::err_toomany_element_decls));
1916
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001917 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1918 if (!D || D->isInvalidDecl())
1919 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001920
John McCall31168b02011-06-15 23:02:42 +00001921 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001922 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1923 // declare identifiers for objects having storage class 'auto' or
1924 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001925 if (!D->hasLocalStorage())
1926 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001927 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001928
1929 // If the type contained 'auto', deduce the 'auto' to 'id'.
1930 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001931 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1932 VK_RValue);
1933 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001934 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1935 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001936 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001937 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001938 D->setInvalidDecl();
1939 return StmtError();
1940 }
1941
Richard Smith061f1e22013-04-30 21:23:01 +00001942 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001943
Richard Smith51ec0cf2017-02-21 01:17:38 +00001944 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001945 SourceLocation Loc =
1946 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001947 Diag(Loc, diag::warn_auto_var_is_id)
1948 << D->getDeclName();
1949 }
1950 }
1951
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001952 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001953 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001954 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001955 return StmtError(
1956 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1957 << First->getSourceRange());
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001958
Mike Stump11289f42009-09-09 15:08:12 +00001959 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001960 if (FirstType.isConstQualified())
1961 Diag(ForLoc, diag::err_selector_element_const_type)
1962 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001963 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001964 if (!FirstType->isDependentType() &&
1965 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001966 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001967 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1968 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001969 }
Chad Rosier02a84392012-08-10 17:56:09 +00001970
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001971 if (CollectionExprResult.isInvalid())
1972 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001973
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001974 CollectionExprResult =
1975 ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00001976 if (CollectionExprResult.isInvalid())
1977 return StmtError();
1978
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001979 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1980 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001981}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001982
Richard Smith02e85f32011-04-14 22:09:26 +00001983/// Finish building a variable declaration for a for-range statement.
1984/// \return true if an error occurs.
1985static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001986 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001987 if (Decl->getType()->isUndeducedType()) {
1988 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1989 if (!Res.isUsable()) {
1990 Decl->setInvalidDecl();
1991 return true;
1992 }
1993 Init = Res.get();
1994 }
1995
Richard Smith02e85f32011-04-14 22:09:26 +00001996 // Deduce the type for the iterator variable now rather than leaving it to
1997 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001998 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001999 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00002000 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00002001 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00002002 SemaRef.Diag(Loc, DiagID) << Init->getType();
2003 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002004 Decl->setInvalidDecl();
2005 return true;
2006 }
Richard Smith061f1e22013-04-30 21:23:01 +00002007 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00002008
John McCall31168b02011-06-15 23:02:42 +00002009 // In ARC, infer lifetime.
2010 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2011 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00002012 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002013 SemaRef.inferObjCARCLifetime(Decl))
2014 Decl->setInvalidDecl();
2015
Richard Smith3beb7c62017-01-12 02:27:38 +00002016 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002017 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00002018 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00002019 return false;
2020}
2021
Sam Panzer0f384432012-08-21 00:52:01 +00002022namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00002023// An enum to represent whether something is dealing with a call to begin()
2024// or a call to end() in a range-based for loop.
2025enum BeginEndFunction {
2026 BEF_begin,
2027 BEF_end
2028};
Sam Panzer0f384432012-08-21 00:52:01 +00002029
Richard Smith02e85f32011-04-14 22:09:26 +00002030/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00002031/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00002032/// nor from the diagnostics produced when analysing the implicit expressions
2033/// required in a for-range statement.
2034void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00002035 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00002036 CallExpr *CE = dyn_cast<CallExpr>(E);
2037 if (!CE)
2038 return;
2039 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2040 if (!D)
2041 return;
2042 SourceLocation Loc = D->getLocation();
2043
2044 std::string Description;
2045 bool IsTemplate = false;
2046 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2047 Description = SemaRef.getTemplateArgumentBindingsText(
2048 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2049 IsTemplate = true;
2050 }
2051
2052 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2053 << BEF << IsTemplate << Description << E->getType();
2054}
2055
Sam Panzer0f384432012-08-21 00:52:01 +00002056/// Build a variable declaration for a for-range statement.
2057VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
Matt Davisb8402ef2018-02-14 21:22:11 +00002058 QualType Type, StringRef Name) {
Sam Panzer0f384432012-08-21 00:52:01 +00002059 DeclContext *DC = SemaRef.CurContext;
2060 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2061 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2062 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002063 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00002064 Decl->setImplicit();
2065 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00002066}
2067
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002068}
Richard Smith02e85f32011-04-14 22:09:26 +00002069
Fariborz Jahanian00213472012-07-06 19:04:04 +00002070static bool ObjCEnumerationCollection(Expr *Collection) {
2071 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00002072 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00002073}
2074
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002075/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002076///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002077/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00002078/// A range-based for statement is equivalent to
2079///
2080/// {
2081/// auto && __range = range-init;
2082/// for ( auto __begin = begin-expr,
2083/// __end = end-expr;
2084/// __begin != __end;
2085/// ++__begin ) {
2086/// for-range-declaration = *__begin;
2087/// statement
2088/// }
2089/// }
2090///
2091/// The body of the loop is not available yet, since it cannot be analysed until
2092/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00002093StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002094 SourceLocation CoawaitLoc, Stmt *InitStmt,
2095 Stmt *First, SourceLocation ColonLoc,
2096 Expr *Range, SourceLocation RParenLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +00002097 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00002098 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00002099 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002100
Richard Smith8baa5002018-09-28 18:44:09 +00002101 if (Range && ObjCEnumerationCollection(Range)) {
2102 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2103 if (InitStmt)
2104 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2105 << InitStmt->getSourceRange();
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002106 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith8baa5002018-09-28 18:44:09 +00002107 }
Richard Smith02e85f32011-04-14 22:09:26 +00002108
2109 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2110 assert(DS && "first part of for range not a decl stmt");
2111
2112 if (!DS->isSingleDecl()) {
Stephen Kellya6e43582018-08-09 21:05:56 +00002113 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
Richard Smith02e85f32011-04-14 22:09:26 +00002114 return StmtError();
2115 }
Richard Smith02e85f32011-04-14 22:09:26 +00002116
Richard Smith3249fed2013-08-21 01:40:36 +00002117 Decl *LoopVar = DS->getSingleDecl();
2118 if (LoopVar->isInvalidDecl() || !Range ||
2119 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2120 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002121 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002122 }
Richard Smith02e85f32011-04-14 22:09:26 +00002123
Eric Fiselierb936a392017-06-14 03:24:55 +00002124 // Build the coroutine state immediately and not later during template
2125 // instantiation
2126 if (!CoawaitLoc.isInvalid()) {
2127 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2128 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002129 }
2130
Richard Smith02e85f32011-04-14 22:09:26 +00002131 // Build auto && __range = range-init
Matt Davisb8402ef2018-02-14 21:22:11 +00002132 // Divide by 2, since the variables are in the inner scope (loop body).
2133 const auto DepthStr = std::to_string(S->getDepth() / 2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002134 SourceLocation RangeLoc = Range->getBeginLoc();
Richard Smith02e85f32011-04-14 22:09:26 +00002135 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2136 Context.getAutoRRefDeductType(),
Matt Davisb8402ef2018-02-14 21:22:11 +00002137 std::string("__range") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002138 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002139 diag::err_for_range_deduction_failure)) {
2140 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002141 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002142 }
Richard Smith02e85f32011-04-14 22:09:26 +00002143
2144 // Claim the type doesn't contain auto: we've already done the checking.
2145 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002146 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002147 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002148 if (RangeDecl.isInvalid()) {
2149 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002150 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002151 }
Richard Smith02e85f32011-04-14 22:09:26 +00002152
Richard Smith8baa5002018-09-28 18:44:09 +00002153 return BuildCXXForRangeStmt(
2154 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2155 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2156 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002157}
2158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002159/// Create the initialization, compare, and increment steps for
Sam Panzer0f384432012-08-21 00:52:01 +00002160/// the range-based for loop expression.
2161/// This function does not handle array-based for loops,
2162/// which are created in Sema::BuildCXXForRangeStmt.
2163///
2164/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2165/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2166/// CandidateSet and BEF are set and some non-success value is returned on
2167/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002168static Sema::ForRangeStatus
2169BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2170 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2171 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2172 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2173 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002174 DeclarationNameInfo BeginNameInfo(
2175 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2176 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2177 ColonLoc);
2178
2179 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2180 Sema::LookupMemberName);
2181 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2182
Richard Smith236ffde2018-09-24 23:17:44 +00002183 auto BuildBegin = [&] {
2184 *BEF = BEF_begin;
2185 Sema::ForRangeStatus RangeStatus =
2186 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2187 BeginMemberLookup, CandidateSet,
2188 BeginRange, BeginExpr);
2189
2190 if (RangeStatus != Sema::FRS_Success) {
2191 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2192 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2193 << ColonLoc << BEF_begin << BeginRange->getType();
2194 return RangeStatus;
2195 }
2196 if (!CoawaitLoc.isInvalid()) {
2197 // FIXME: getCurScope() should not be used during template instantiation.
2198 // We should pick up the set of unqualified lookup results for operator
2199 // co_await during the initial parse.
2200 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2201 BeginExpr->get());
2202 if (BeginExpr->isInvalid())
2203 return Sema::FRS_DiagnosticIssued;
2204 }
2205 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2206 diag::err_for_range_iter_deduction_failure)) {
2207 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2208 return Sema::FRS_DiagnosticIssued;
2209 }
2210 return Sema::FRS_Success;
2211 };
2212
2213 auto BuildEnd = [&] {
2214 *BEF = BEF_end;
2215 Sema::ForRangeStatus RangeStatus =
2216 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2217 EndMemberLookup, CandidateSet,
2218 EndRange, EndExpr);
2219 if (RangeStatus != Sema::FRS_Success) {
2220 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2221 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2222 << ColonLoc << BEF_end << EndRange->getType();
2223 return RangeStatus;
2224 }
2225 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2226 diag::err_for_range_iter_deduction_failure)) {
2227 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2228 return Sema::FRS_DiagnosticIssued;
2229 }
2230 return Sema::FRS_Success;
2231 };
2232
Sam Panzer0f384432012-08-21 00:52:01 +00002233 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2234 // - if _RangeT is a class type, the unqualified-ids begin and end are
2235 // looked up in the scope of class _RangeT as if by class member access
2236 // lookup (3.4.5), and if either (or both) finds at least one
2237 // declaration, begin-expr and end-expr are __range.begin() and
2238 // __range.end(), respectively;
2239 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002240 if (BeginMemberLookup.isAmbiguous())
2241 return Sema::FRS_DiagnosticIssued;
2242
Sam Panzer0f384432012-08-21 00:52:01 +00002243 SemaRef.LookupQualifiedName(EndMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002244 if (EndMemberLookup.isAmbiguous())
2245 return Sema::FRS_DiagnosticIssued;
Sam Panzer0f384432012-08-21 00:52:01 +00002246
2247 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
Richard Smith236ffde2018-09-24 23:17:44 +00002248 // Look up the non-member form of the member we didn't find, first.
2249 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2250 // a 'begin' but ignored it because there was no member 'end'"
2251 // diagnostic.
2252 auto BuildNonmember = [&](
2253 BeginEndFunction BEFFound, LookupResult &Found,
2254 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2255 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2256 LookupResult OldFound = std::move(Found);
2257 Found.clear();
Sam Panzer0f384432012-08-21 00:52:01 +00002258
Richard Smith236ffde2018-09-24 23:17:44 +00002259 if (Sema::ForRangeStatus Result = BuildNotFound())
2260 return Result;
2261
2262 switch (BuildFound()) {
2263 case Sema::FRS_Success:
2264 return Sema::FRS_Success;
2265
2266 case Sema::FRS_NoViableFunction:
David Blaikie5e328052019-05-03 00:44:50 +00002267 CandidateSet->NoteCandidates(
2268 PartialDiagnosticAt(BeginRange->getBeginLoc(),
2269 SemaRef.PDiag(diag::err_for_range_invalid)
2270 << BeginRange->getType() << BEFFound),
2271 SemaRef, OCD_AllCandidates, BeginRange);
Richard Smith236ffde2018-09-24 23:17:44 +00002272 LLVM_FALLTHROUGH;
2273
2274 case Sema::FRS_DiagnosticIssued:
2275 for (NamedDecl *D : OldFound) {
2276 SemaRef.Diag(D->getLocation(),
2277 diag::note_for_range_member_begin_end_ignored)
2278 << BeginRange->getType() << BEFFound;
2279 }
2280 return Sema::FRS_DiagnosticIssued;
2281 }
2282 llvm_unreachable("unexpected ForRangeStatus");
2283 };
2284 if (BeginMemberLookup.empty())
2285 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2286 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
Sam Panzer0f384432012-08-21 00:52:01 +00002287 }
2288 } else {
2289 // - otherwise, begin-expr and end-expr are begin(__range) and
2290 // end(__range), respectively, where begin and end are looked up with
2291 // argument-dependent lookup (3.4.2). For the purposes of this name
2292 // lookup, namespace std is an associated namespace.
Sam Panzer0f384432012-08-21 00:52:01 +00002293 }
2294
Richard Smith236ffde2018-09-24 23:17:44 +00002295 if (Sema::ForRangeStatus Result = BuildBegin())
2296 return Result;
2297 return BuildEnd();
Sam Panzer0f384432012-08-21 00:52:01 +00002298}
2299
2300/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002301/// If the attempt fails, this function will return a valid, null StmtResult
2302/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002303static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2304 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002305 SourceLocation CoawaitLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002306 Stmt *InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002307 Stmt *LoopVarDecl,
2308 SourceLocation ColonLoc,
2309 Expr *Range,
2310 SourceLocation RangeLoc,
2311 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002312 // Determine whether we can rebuild the for-range statement with a
2313 // dereferenced range expression.
2314 ExprResult AdjustedRange;
2315 {
2316 Sema::SFINAETrap Trap(SemaRef);
2317
2318 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2319 if (AdjustedRange.isInvalid())
2320 return StmtResult();
2321
Richard Smith9f690bd2015-10-27 06:02:45 +00002322 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002323 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2324 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002325 if (SR.isInvalid())
2326 return StmtResult();
2327 }
2328
2329 // The attempt to dereference worked well enough that it could produce a valid
2330 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2331 // case there are any other (non-fatal) problems with it.
2332 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2333 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith8baa5002018-09-28 18:44:09 +00002334 return SemaRef.ActOnCXXForRangeStmt(
2335 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2336 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002337}
2338
Richard Smith3249fed2013-08-21 01:40:36 +00002339namespace {
2340/// RAII object to automatically invalidate a declaration if an error occurs.
2341struct InvalidateOnErrorScope {
2342 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2343 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2344 ~InvalidateOnErrorScope() {
2345 if (Enabled && Trap.hasErrorOccurred())
2346 D->setInvalidDecl();
2347 }
2348
2349 DiagnosticErrorTrap Trap;
2350 Decl *D;
2351 bool Enabled;
2352};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002353}
Richard Smith3249fed2013-08-21 01:40:36 +00002354
Richard Smitha05b3b52012-09-20 21:52:32 +00002355/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith8baa5002018-09-28 18:44:09 +00002356StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2357 SourceLocation CoawaitLoc, Stmt *InitStmt,
2358 SourceLocation ColonLoc, Stmt *RangeDecl,
2359 Stmt *Begin, Stmt *End, Expr *Cond,
2360 Expr *Inc, Stmt *LoopVarDecl,
2361 SourceLocation RParenLoc,
2362 BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002363 // FIXME: This should not be used during template instantiation. We should
2364 // pick up the set of unqualified lookup results for the != and + operators
2365 // in the initial parse.
2366 //
2367 // Testcase (accepts-invalid):
2368 // template<typename T> void f() { for (auto x : T()) {} }
2369 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2370 // bool operator!=(N::X, N::X); void operator++(N::X);
2371 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002372 Scope *S = getCurScope();
2373
2374 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2375 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2376 QualType RangeVarType = RangeVar->getType();
2377
2378 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2379 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2380
Richard Smith3249fed2013-08-21 01:40:36 +00002381 // If we hit any errors, mark the loop variable as invalid if its type
2382 // contains 'auto'.
2383 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2384 LoopVar->getType()->isUndeducedType());
2385
Richard Smith01694c32016-03-20 10:33:40 +00002386 StmtResult BeginDeclStmt = Begin;
2387 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002388 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2389
Richard Smith27d807c2013-04-30 13:56:41 +00002390 if (RangeVarType->isDependentType()) {
2391 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002392 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002393
2394 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2395 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002396 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2397 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2398 for (auto *Binding : DD->bindings())
2399 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002400 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002401 }
Richard Smith01694c32016-03-20 10:33:40 +00002402 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002403 SourceLocation RangeLoc = RangeVar->getLocation();
2404
Ted Kremenekbed648e2011-10-10 22:36:28 +00002405 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2406
2407 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2408 VK_LValue, ColonLoc);
2409 if (BeginRangeRef.isInvalid())
2410 return StmtError();
2411
2412 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2413 VK_LValue, ColonLoc);
2414 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002415 return StmtError();
2416
2417 QualType AutoType = Context.getAutoDeductType();
2418 Expr *Range = RangeVar->getInit();
2419 if (!Range)
2420 return StmtError();
2421 QualType RangeType = Range->getType();
2422
2423 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002424 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002425 return StmtError();
2426
2427 // Build auto __begin = begin-expr, __end = end-expr.
Matt Davisb8402ef2018-02-14 21:22:11 +00002428 // Divide by 2, since the variables are in the inner scope (loop body).
2429 const auto DepthStr = std::to_string(S->getDepth() / 2);
Richard Smith02e85f32011-04-14 22:09:26 +00002430 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002431 std::string("__begin") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002432 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002433 std::string("__end") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002434
2435 // Build begin-expr and end-expr and attach to __begin and __end variables.
2436 ExprResult BeginExpr, EndExpr;
2437 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2438 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2439 // __range + __bound, respectively, where __bound is the array bound. If
2440 // _RangeT is an array of unknown size or an array of incomplete type,
2441 // the program is ill-formed;
2442
2443 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002444 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002445 if (!CoawaitLoc.isInvalid()) {
2446 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2447 if (BeginExpr.isInvalid())
2448 return StmtError();
2449 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002450 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002451 diag::err_for_range_iter_deduction_failure)) {
2452 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2453 return StmtError();
2454 }
2455
2456 // Find the array bound.
2457 ExprResult BoundExpr;
2458 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002459 BoundExpr = IntegerLiteral::Create(
2460 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002461 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002462 dyn_cast<VariableArrayType>(UnqAT)) {
2463 // For a variably modified type we can't just use the expression within
2464 // the array bounds, since we don't want that to be re-evaluated here.
2465 // Rather, we need to determine what it was when the array was first
2466 // created - so we resort to using sizeof(vla)/sizeof(element).
2467 // For e.g.
Fangrui Song6907ce22018-07-30 19:24:48 +00002468 // void f(int b) {
Faisal Vali1ca2d962017-05-15 01:49:19 +00002469 // int vla[b];
2470 // b = -1; <-- This should not affect the num of iterations below
2471 // for (int &c : vla) { .. }
2472 // }
2473
2474 // FIXME: This results in codegen generating IR that recalculates the
2475 // run-time number of elements (as opposed to just using the IR Value
2476 // that corresponds to the run-time value of each bound that was
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002477 // generated when the array was created.) If this proves too embarrassing
Faisal Vali1ca2d962017-05-15 01:49:19 +00002478 // even for unoptimized IR, consider passing a magic-value/cookie to
2479 // codegen that then knows to simply use that initial llvm::Value (that
2480 // corresponds to the bound at time of array creation) within
2481 // getelementptr. But be prepared to pay the price of increasing a
2482 // customized form of coupling between the two components - which could
2483 // be hard to maintain as the codebase evolves.
2484
2485 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2486 EndVar->getLocation(), UETT_SizeOf,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002487 /*IsType=*/true,
Faisal Vali1ca2d962017-05-15 01:49:19 +00002488 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2489 VAT->desugar(), RangeLoc))
2490 .getAsOpaquePtr(),
2491 EndVar->getSourceRange());
2492 if (SizeOfVLAExprR.isInvalid())
2493 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002494
Faisal Vali1ca2d962017-05-15 01:49:19 +00002495 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2496 EndVar->getLocation(), UETT_SizeOf,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002497 /*IsType=*/true,
Faisal Vali1ca2d962017-05-15 01:49:19 +00002498 CreateParsedType(VAT->desugar(),
2499 Context.getTrivialTypeSourceInfo(
2500 VAT->getElementType(), RangeLoc))
2501 .getAsOpaquePtr(),
2502 EndVar->getSourceRange());
2503 if (SizeOfEachElementExprR.isInvalid())
2504 return StmtError();
2505
2506 BoundExpr =
2507 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2508 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2509 if (BoundExpr.isInvalid())
2510 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002511
Faisal Vali1ca2d962017-05-15 01:49:19 +00002512 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002513 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2514 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002515 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002516 }
2517
2518 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002519 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002520 BoundExpr.get());
2521 if (EndExpr.isInvalid())
2522 return StmtError();
2523 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2524 diag::err_for_range_iter_deduction_failure)) {
2525 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2526 return StmtError();
2527 }
2528 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002529 OverloadCandidateSet CandidateSet(RangeLoc,
2530 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002531 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002532 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2533 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2534 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2535 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002536
Richard Smitha05b3b52012-09-20 21:52:32 +00002537 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002538 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002539 // If the range is being built from an array parameter, emit a
2540 // a diagnostic that it is being treated as a pointer.
2541 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2542 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2543 QualType ArrayTy = PVD->getOriginalType();
2544 QualType PointerTy = PVD->getType();
2545 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002546 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2547 << RangeLoc << PVD << ArrayTy << PointerTy;
Richard Trieu08254692013-10-11 22:16:04 +00002548 Diag(PVD->getLocation(), diag::note_declared_at);
2549 return StmtError();
2550 }
2551 }
2552 }
2553
2554 // If building the range failed, try dereferencing the range expression
2555 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002556 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002557 CoawaitLoc, InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002558 LoopVarDecl, ColonLoc,
2559 Range, RangeLoc,
2560 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002561 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002562 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002563 }
2564
Sam Panzer0f384432012-08-21 00:52:01 +00002565 // Otherwise, emit diagnostics if we haven't already.
2566 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002567 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
David Blaikie5e328052019-05-03 00:44:50 +00002568 CandidateSet.NoteCandidates(
2569 PartialDiagnosticAt(Range->getBeginLoc(),
2570 PDiag(diag::err_for_range_invalid)
2571 << RangeLoc << Range->getType()
2572 << BEFFailure),
2573 *this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002574 }
2575 // Return an error if no fix was discovered.
2576 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002577 return StmtError();
2578 }
2579
Sam Panzer0f384432012-08-21 00:52:01 +00002580 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2581 "invalid range expression in for loop");
2582
2583 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002584 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002585 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2586 if (!Context.hasSameType(BeginType, EndType)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002587 Diag(RangeLoc, getLangOpts().CPlusPlus17
Richard Smith01694c32016-03-20 10:33:40 +00002588 ? diag::warn_for_range_begin_end_types_differ
2589 : diag::ext_for_range_begin_end_types_differ)
2590 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002591 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2592 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2593 }
2594
Richard Smith01694c32016-03-20 10:33:40 +00002595 BeginDeclStmt =
2596 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2597 EndDeclStmt =
2598 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002599
Ted Kremenekbed648e2011-10-10 22:36:28 +00002600 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2601 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002602 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002603 if (BeginRef.isInvalid())
2604 return StmtError();
2605
Richard Smith02e85f32011-04-14 22:09:26 +00002606 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2607 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002608 if (EndRef.isInvalid())
2609 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002610
2611 // Build and check __begin != __end expression.
2612 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2613 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002614 if (!NotEqExpr.isInvalid())
2615 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2616 if (!NotEqExpr.isInvalid())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002617 NotEqExpr =
2618 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002619 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002620 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2621 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002622 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2623 if (!Context.hasSameType(BeginType, EndType))
2624 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2625 return StmtError();
2626 }
2627
2628 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002629 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2630 VK_LValue, ColonLoc);
2631 if (BeginRef.isInvalid())
2632 return StmtError();
2633
Richard Smith02e85f32011-04-14 22:09:26 +00002634 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002635 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002636 // FIXME: getCurScope() should not be used during template instantiation.
2637 // We should pick up the set of unqualified lookup results for operator
2638 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002639 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002640 if (!IncrExpr.isInvalid())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002641 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002642 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002643 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2644 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002645 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2646 return StmtError();
2647 }
2648
2649 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002650 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2651 VK_LValue, ColonLoc);
2652 if (BeginRef.isInvalid())
2653 return StmtError();
2654
Richard Smith02e85f32011-04-14 22:09:26 +00002655 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2656 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002657 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2658 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002659 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2660 return StmtError();
2661 }
2662
Richard Smitha05b3b52012-09-20 21:52:32 +00002663 // Attach *__begin as initializer for VD. Don't touch it if we're just
2664 // trying to determine whether this would be a valid range.
2665 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002666 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002667 if (LoopVar->isInvalidDecl())
2668 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2669 }
2670 }
2671
Richard Smitha05b3b52012-09-20 21:52:32 +00002672 // Don't bother to actually allocate the result if we're just trying to
2673 // determine whether it would be valid.
2674 if (Kind == BFRK_Check)
2675 return StmtResult();
2676
Alexey Bataevbef93a92019-10-07 18:54:57 +00002677 // In OpenMP loop region loop control variable must be private. Perform
2678 // analysis of first part (if any).
2679 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
2680 ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
2681
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002682 return new (Context) CXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002683 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
Richard Smith01694c32016-03-20 10:33:40 +00002684 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002685 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2686 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002687}
2688
Chad Rosier02a84392012-08-10 17:56:09 +00002689/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002690/// statement.
2691StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2692 if (!S || !B)
2693 return StmtError();
2694 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002695
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002696 ForStmt->setBody(B);
2697 return S;
2698}
2699
Richard Trieu3e1d4832015-04-13 22:08:55 +00002700// Warn when the loop variable is a const reference that creates a copy.
2701// Suggest using the non-reference type for copies. If a copy can be prevented
2702// suggest the const reference type that would do so.
2703// For instance, given "for (const &Foo : Range)", suggest
2704// "for (const Foo : Range)" to denote a copy is made for the loop. If
2705// possible, also suggest "for (const &Bar : Range)" if this type prevents
2706// the copy altogether.
2707static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2708 const VarDecl *VD,
2709 QualType RangeInitType) {
2710 const Expr *InitExpr = VD->getInit();
2711 if (!InitExpr)
2712 return;
2713
2714 QualType VariableType = VD->getType();
2715
Tim Shen4a05bb82016-06-21 20:29:17 +00002716 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2717 if (!Cleanups->cleanupsHaveSideEffects())
2718 InitExpr = Cleanups->getSubExpr();
2719
Richard Trieu3e1d4832015-04-13 22:08:55 +00002720 const MaterializeTemporaryExpr *MTE =
2721 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2722
2723 // No copy made.
2724 if (!MTE)
2725 return;
2726
Tykerb0561b32019-11-17 11:41:55 +01002727 const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
Richard Trieu3e1d4832015-04-13 22:08:55 +00002728
2729 // Searching for either UnaryOperator for dereference of a pointer or
2730 // CXXOperatorCallExpr for handling iterators.
2731 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2732 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2733 E = CCE->getArg(0);
2734 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2735 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2736 E = ME->getBase();
2737 } else {
2738 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
Tykerb0561b32019-11-17 11:41:55 +01002739 E = MTE->getSubExpr();
Richard Trieu3e1d4832015-04-13 22:08:55 +00002740 }
2741 E = E->IgnoreImpCasts();
2742 }
2743
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002744 QualType ReferenceReturnType;
Richard Trieu3e1d4832015-04-13 22:08:55 +00002745 if (isa<UnaryOperator>(E)) {
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002746 ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
Richard Trieu3e1d4832015-04-13 22:08:55 +00002747 } else {
2748 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2749 const FunctionDecl *FD = Call->getDirectCallee();
2750 QualType ReturnType = FD->getReturnType();
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002751 if (ReturnType->isReferenceType())
2752 ReferenceReturnType = ReturnType;
Richard Trieu3e1d4832015-04-13 22:08:55 +00002753 }
2754
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002755 if (!ReferenceReturnType.isNull()) {
Richard Trieu3e1d4832015-04-13 22:08:55 +00002756 // Loop variable creates a temporary. Suggest either to go with
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002757 // non-reference loop variable to indicate a copy is made, or
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002758 // the correct type to bind a const reference.
2759 SemaRef.Diag(VD->getLocation(),
2760 diag::warn_for_range_const_ref_binds_temp_built_from_ref)
2761 << VD << VariableType << ReferenceReturnType;
Richard Trieu3e1d4832015-04-13 22:08:55 +00002762 QualType NonReferenceType = VariableType.getNonReferenceType();
2763 NonReferenceType.removeLocalConst();
2764 QualType NewReferenceType =
2765 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002766 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
Mark de Weverf022a5a2020-01-01 17:23:19 +01002767 << NonReferenceType << NewReferenceType << VD->getSourceRange()
2768 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
Mark de Wevere5ab1e42020-01-01 17:23:20 +01002769 } else if (!VariableType->isRValueReferenceType()) {
Richard Trieu3e1d4832015-04-13 22:08:55 +00002770 // The range always returns a copy, so a temporary is always created.
2771 // Suggest removing the reference from the loop variable.
Mark de Wevere5ab1e42020-01-01 17:23:20 +01002772 // If the type is a rvalue reference do not warn since that changes the
2773 // semantic of the code.
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002774 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002775 << VD << RangeInitType;
2776 QualType NonReferenceType = VariableType.getNonReferenceType();
2777 NonReferenceType.removeLocalConst();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002778 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
Mark de Weverf022a5a2020-01-01 17:23:19 +01002779 << NonReferenceType << VD->getSourceRange()
2780 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
Richard Trieu3e1d4832015-04-13 22:08:55 +00002781 }
2782}
2783
Mark de Wever9c74fb42020-01-11 10:16:40 +01002784/// Determines whether the @p VariableType's declaration is a record with the
2785/// clang::trivial_abi attribute.
2786static bool hasTrivialABIAttr(QualType VariableType) {
2787 if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
2788 return RD->hasAttr<TrivialABIAttr>();
2789
2790 return false;
2791}
2792
Richard Trieu3e1d4832015-04-13 22:08:55 +00002793// Warns when the loop variable can be changed to a reference type to
2794// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2795// "for (const Foo &x : Range)" if this form does not make a copy.
2796static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2797 const VarDecl *VD) {
2798 const Expr *InitExpr = VD->getInit();
2799 if (!InitExpr)
2800 return;
2801
2802 QualType VariableType = VD->getType();
2803
2804 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2805 if (!CE->getConstructor()->isCopyConstructor())
2806 return;
2807 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2808 if (CE->getCastKind() != CK_LValueToRValue)
2809 return;
2810 } else {
2811 return;
2812 }
2813
Mark de Wever9c74fb42020-01-11 10:16:40 +01002814 // Small trivially copyable types are cheap to copy. Do not emit the
2815 // diagnostic for these instances. 64 bytes is a common size of a cache line.
2816 // (The function `getTypeSize` returns the size in bits.)
2817 ASTContext &Ctx = SemaRef.Context;
2818 if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
2819 (VariableType.isTriviallyCopyableType(Ctx) ||
2820 hasTrivialABIAttr(VariableType)))
Richard Trieu3e1d4832015-04-13 22:08:55 +00002821 return;
2822
2823 // Suggest changing from a const variable to a const reference variable
2824 // if doing so will prevent a copy.
2825 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002826 << VD << VariableType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002827 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002828 << SemaRef.Context.getLValueReferenceType(VariableType)
Mark de Weverf022a5a2020-01-01 17:23:19 +01002829 << VD->getSourceRange()
2830 << FixItHint::CreateInsertion(VD->getLocation(), "&");
Richard Trieu3e1d4832015-04-13 22:08:55 +00002831}
2832
2833/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2834/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2835/// using "const foo x" to show that a copy is made
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002836/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
Richard Trieu3e1d4832015-04-13 22:08:55 +00002837/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2838/// prevent the copy.
2839/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2840/// Suggest "const foo &x" to prevent the copy.
2841static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2842 const CXXForRangeStmt *ForStmt) {
Mark de Wever41fcd172020-01-19 17:01:12 +01002843 if (SemaRef.inTemplateInstantiation())
2844 return;
2845
Aaron Puchert33bb32b2020-03-06 14:56:47 +01002846 if (SemaRef.Diags.isIgnored(
2847 diag::warn_for_range_const_ref_binds_temp_built_from_ref,
2848 ForStmt->getBeginLoc()) &&
2849 SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002850 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002851 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002852 ForStmt->getBeginLoc())) {
Richard Trieu3e1d4832015-04-13 22:08:55 +00002853 return;
2854 }
2855
2856 const VarDecl *VD = ForStmt->getLoopVariable();
2857 if (!VD)
2858 return;
2859
2860 QualType VariableType = VD->getType();
2861
2862 if (VariableType->isIncompleteType())
2863 return;
2864
2865 const Expr *InitExpr = VD->getInit();
2866 if (!InitExpr)
2867 return;
2868
Mark de Wever41fcd172020-01-19 17:01:12 +01002869 if (InitExpr->getExprLoc().isMacroID())
2870 return;
2871
Richard Trieu3e1d4832015-04-13 22:08:55 +00002872 if (VariableType->isReferenceType()) {
2873 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2874 ForStmt->getRangeInit()->getType());
2875 } else if (VariableType.isConstQualified()) {
2876 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2877 }
2878}
2879
Richard Smith02e85f32011-04-14 22:09:26 +00002880/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2881/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2882/// body cannot be performed until after the type of the range variable is
2883/// determined.
2884StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2885 if (!S || !B)
2886 return StmtError();
2887
Fariborz Jahanian00213472012-07-06 19:04:04 +00002888 if (isa<ObjCForCollectionStmt>(S))
2889 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002890
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002891 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2892 ForStmt->setBody(B);
2893
2894 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2895 diag::warn_empty_range_based_for_body);
2896
Richard Trieu3e1d4832015-04-13 22:08:55 +00002897 DiagnoseForRangeVariableCopies(*this, ForStmt);
2898
Richard Smith02e85f32011-04-14 22:09:26 +00002899 return S;
2900}
2901
Chris Lattnercab02a62011-02-17 20:34:02 +00002902StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2903 SourceLocation LabelLoc,
2904 LabelDecl *TheDecl) {
Reid Kleckner87a31802018-03-12 21:43:02 +00002905 setFunctionHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002906 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002907 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002908}
Chris Lattner1c310502007-05-31 06:00:00 +00002909
John McCalldadc5752010-08-24 06:29:42 +00002910StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002911Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002912 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002913 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002914 if (!E->isTypeDependent()) {
2915 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002916 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002917 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002918 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002919 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2920 if (ExprRes.isInvalid())
2921 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002922 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002923 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002924 return StmtError();
2925 }
John McCalla95172b2010-08-01 00:26:45 +00002926
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002927 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00002928 if (ExprRes.isInvalid())
2929 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002930 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002931
Reid Kleckner87a31802018-03-12 21:43:02 +00002932 setFunctionHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002933
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002934 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002935}
2936
Nico Weberd64657f2015-03-09 02:47:59 +00002937static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2938 const Scope &DestScope) {
2939 if (!S.CurrentSEHFinally.empty() &&
2940 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2941 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2942 }
2943}
2944
John McCalldadc5752010-08-24 06:29:42 +00002945StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002946Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002947 Scope *S = CurScope->getContinueParent();
2948 if (!S) {
2949 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002950 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002951 }
Nico Weberd64657f2015-03-09 02:47:59 +00002952 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002953
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002954 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002955}
2956
John McCalldadc5752010-08-24 06:29:42 +00002957StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002958Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002959 Scope *S = CurScope->getBreakParent();
2960 if (!S) {
2961 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002962 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002963 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002964 if (S->isOpenMPLoopScope())
2965 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2966 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002967 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002968
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002969 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002970}
2971
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002972/// Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002973/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002974///
Douglas Gregor5d369002011-01-21 18:05:27 +00002975/// \param ReturnType If we're determining the copy elision candidate for
2976/// a return statement, this is the return type of the function. If we're
2977/// determining the copy elision candidate for a throw expression, this will
2978/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002979///
Douglas Gregor5d369002011-01-21 18:05:27 +00002980/// \param E The expression being returned from the function or block, or
2981/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002982///
Richard Trieu09c163b2018-03-15 03:00:55 +00002983/// \param CESK Whether we allow function parameters or
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002984/// id-expressions that could be moved out of the function to be considered NRVO
2985/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2986/// determine whether we should try to move as part of a return or throw (which
2987/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002988///
2989/// \returns The NRVO candidate variable, if the return statement may use the
2990/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002991VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
Richard Trieu09c163b2018-03-15 03:00:55 +00002992 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002993 // - in a return statement in a function [where] ...
2994 // ... the expression is the name of a non-volatile automatic object ...
2995 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002996 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002997 return nullptr;
2998 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2999 if (!VD)
3000 return nullptr;
3001
Richard Trieu09c163b2018-03-15 03:00:55 +00003002 if (isCopyElisionCandidate(ReturnType, VD, CESK))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003003 return VD;
3004 return nullptr;
3005}
3006
3007bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Richard Trieu09c163b2018-03-15 03:00:55 +00003008 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003009 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003010 // - in a return statement in a function with ...
3011 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003012 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00003013 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003014 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00003015 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003016 // When considering moving this expression out, allow dissimilar types.
Richard Trieu09c163b2018-03-15 03:00:55 +00003017 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003018 !Context.hasSameUnqualifiedType(ReturnType, VDType))
3019 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00003020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
John McCall03318c12011-11-11 03:57:31 +00003022 // ...object (other than a function or catch-clause parameter)...
3023 if (VD->getKind() != Decl::Var &&
Richard Trieu09c163b2018-03-15 03:00:55 +00003024 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003025 return false;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003026 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
3027 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003028
John McCall03318c12011-11-11 03:57:31 +00003029 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003030 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00003031
Akira Hatanaka6697eff2017-02-15 05:15:28 +00003032 // Return false if VD is a __block variable. We don't want to implicitly move
3033 // out of a __block variable during a return because we cannot assume the
3034 // variable will no longer be used.
3035 if (VD->hasAttr<BlocksAttr>()) return false;
3036
Richard Trieu09c163b2018-03-15 03:00:55 +00003037 if (CESK & CES_AllowDifferentTypes)
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003038 return true;
3039
John McCall03318c12011-11-11 03:57:31 +00003040 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003041 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00003042
John McCall03318c12011-11-11 03:57:31 +00003043 // Variables with higher required alignment than their type's ABI
3044 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003045 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00003046 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003047 return false;
John McCall03318c12011-11-11 03:57:31 +00003048
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003049 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003050}
3051
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003052/// Try to perform the initialization of a potentially-movable value,
Richard Trieu09c163b2018-03-15 03:00:55 +00003053/// which is the operand to a return or throw statement.
3054///
3055/// This routine implements C++14 [class.copy]p32, which attempts to treat
3056/// returned lvalues as rvalues in certain cases (to prefer move construction),
3057/// then falls back to treating them as lvalues if that failed.
3058///
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003059/// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
3060/// resolutions that find non-constructors, such as derived-to-base conversions
3061/// or `operator T()&&` member functions. If false, do consider such
3062/// conversion sequences.
3063///
Richard Trieu09c163b2018-03-15 03:00:55 +00003064/// \param Res We will fill this in if move-initialization was possible.
3065/// If move-initialization is not possible, such that we must fall back to
3066/// treating the operand as an lvalue, we will leave Res in its original
3067/// invalid state.
3068static void TryMoveInitialization(Sema& S,
3069 const InitializedEntity &Entity,
3070 const VarDecl *NRVOCandidate,
3071 QualType ResultType,
3072 Expr *&Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003073 bool ConvertingConstructorsOnly,
Richard Trieu09c163b2018-03-15 03:00:55 +00003074 ExprResult &Res) {
3075 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3076 CK_NoOp, Value, VK_XValue);
3077
3078 Expr *InitExpr = &AsRvalue;
3079
3080 InitializationKind Kind = InitializationKind::CreateCopy(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003081 Value->getBeginLoc(), Value->getBeginLoc());
Richard Trieu09c163b2018-03-15 03:00:55 +00003082
3083 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3084
3085 if (!Seq)
3086 return;
3087
3088 for (const InitializationSequence::Step &Step : Seq.steps()) {
3089 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3090 Step.Kind != InitializationSequence::SK_UserConversion)
3091 continue;
3092
3093 FunctionDecl *FD = Step.Function.Function;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003094 if (ConvertingConstructorsOnly) {
3095 if (isa<CXXConstructorDecl>(FD)) {
3096 // C++14 [class.copy]p32:
3097 // [...] If the first overload resolution fails or was not performed,
3098 // or if the type of the first parameter of the selected constructor
3099 // is not an rvalue reference to the object's type (possibly
3100 // cv-qualified), overload resolution is performed again, considering
3101 // the object as an lvalue.
3102 const RValueReferenceType *RRefType =
3103 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3104 if (!RRefType)
3105 break;
3106 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3107 NRVOCandidate->getType()))
3108 break;
3109 } else {
3110 continue;
3111 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003112 } else {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003113 if (isa<CXXConstructorDecl>(FD)) {
3114 // Check that overload resolution selected a constructor taking an
3115 // rvalue reference. If it selected an lvalue reference, then we
3116 // didn't need to cast this thing to an rvalue in the first place.
3117 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3118 break;
3119 } else if (isa<CXXMethodDecl>(FD)) {
3120 // Check that overload resolution selected a conversion operator
3121 // taking an rvalue reference.
3122 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3123 break;
3124 } else {
3125 continue;
3126 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003127 }
3128
3129 // Promote "AsRvalue" to the heap, since we now need this
3130 // expression node to persist.
3131 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3132 Value, nullptr, VK_XValue);
3133
3134 // Complete type-checking the initialization of the return type
3135 // using the constructor we found.
3136 Res = Seq.Perform(S, Entity, Kind, Value);
3137 }
3138}
3139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003140/// Perform the initialization of a potentially-movable value, which
Douglas Gregor626fbed2011-01-21 21:08:57 +00003141/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00003142///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003143/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00003144/// returned lvalues as rvalues in certain cases (to prefer move construction),
3145/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00003147Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3148 const VarDecl *NRVOCandidate,
3149 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00003150 Expr *Value,
3151 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003152 // C++14 [class.copy]p32:
3153 // When the criteria for elision of a copy/move operation are met, but not for
3154 // an exception-declaration, and the object to be copied is designated by an
3155 // lvalue, or when the expression in a return statement is a (possibly
3156 // parenthesized) id-expression that names an object with automatic storage
3157 // duration declared in the body or parameter-declaration-clause of the
3158 // innermost enclosing function or lambda-expression, overload resolution to
3159 // select the constructor for the copy is first performed as if the object
3160 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00003161 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003162
Richard Trieu09c163b2018-03-15 03:00:55 +00003163 if (AllowNRVO) {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003164 bool AffectedByCWG1579 = false;
3165
Richard Trieu09c163b2018-03-15 03:00:55 +00003166 if (!NRVOCandidate) {
3167 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003168 if (NRVOCandidate &&
3169 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3170 Value->getExprLoc())) {
3171 const VarDecl *NRVOCandidateInCXX11 =
3172 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3173 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3174 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003175 }
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003176
Richard Trieu09c163b2018-03-15 03:00:55 +00003177 if (NRVOCandidate) {
3178 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003179 true, Res);
3180 }
3181
3182 if (!Res.isInvalid() && AffectedByCWG1579) {
3183 QualType QT = NRVOCandidate->getType();
3184 if (QT.getNonReferenceType()
3185 .getUnqualifiedType()
3186 .isTriviallyCopyableType(Context)) {
3187 // Adding 'std::move' around a trivially copyable variable is probably
3188 // pointless. Don't suggest it.
3189 } else {
3190 // Common cases for this are returning unique_ptr<Derived> from a
3191 // function of return type unique_ptr<Base>, or returning T from a
3192 // function of return type Expected<T>. This is totally fine in a
3193 // post-CWG1579 world, but was not fine before.
3194 assert(!ResultType.isNull());
3195 SmallString<32> Str;
3196 Str += "std::move(";
3197 Str += NRVOCandidate->getDeclName().getAsString();
3198 Str += ")";
3199 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3200 << Value->getSourceRange()
3201 << NRVOCandidate->getDeclName() << ResultType << QT;
3202 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3203 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3204 }
3205 } else if (Res.isInvalid() &&
3206 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3207 Value->getExprLoc())) {
3208 const VarDecl *FakeNRVOCandidate =
3209 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3210 if (FakeNRVOCandidate) {
3211 QualType QT = FakeNRVOCandidate->getType();
3212 if (QT->isLValueReferenceType()) {
3213 // Adding 'std::move' around an lvalue reference variable's name is
3214 // dangerous. Don't suggest it.
3215 } else if (QT.getNonReferenceType()
3216 .getUnqualifiedType()
3217 .isTriviallyCopyableType(Context)) {
3218 // Adding 'std::move' around a trivially copyable variable is probably
3219 // pointless. Don't suggest it.
3220 } else {
3221 ExprResult FakeRes = ExprError();
3222 Expr *FakeValue = Value;
3223 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3224 FakeValue, false, FakeRes);
3225 if (!FakeRes.isInvalid()) {
3226 bool IsThrow =
3227 (Entity.getKind() == InitializedEntity::EK_Exception);
3228 SmallString<32> Str;
3229 Str += "std::move(";
3230 Str += FakeNRVOCandidate->getDeclName().getAsString();
3231 Str += ")";
3232 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3233 << Value->getSourceRange()
3234 << FakeNRVOCandidate->getDeclName() << IsThrow;
3235 Diag(Value->getExprLoc(), diag::note_add_std_move)
3236 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3237 }
3238 }
3239 }
Douglas Gregorf282a762011-01-21 19:38:21 +00003240 }
3241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242
Douglas Gregorf282a762011-01-21 19:38:21 +00003243 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00003245 // (again) now with the return value expression as written.
3246 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00003247 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Douglas Gregorf282a762011-01-21 19:38:21 +00003249 return Res;
3250}
3251
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003252/// Determine whether the declared return type of the specified function
Richard Smith4db51c22013-09-25 05:02:54 +00003253/// contains 'auto'.
3254static bool hasDeducedReturnType(FunctionDecl *FD) {
3255 const FunctionProtoType *FPT =
3256 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003257 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003258}
3259
Eli Friedman34b49062012-01-26 03:00:14 +00003260/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3261/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003262///
John McCalldadc5752010-08-24 06:29:42 +00003263StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003264Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3265 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003266 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003267 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003268 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003269 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003270 bool HasDeducedReturnType =
3271 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003272
Faisal Valid143a0c2017-04-01 21:30:49 +00003273 if (ExprEvalContexts.back().Context ==
3274 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003275 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3276 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003277 ExprResult ER =
3278 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smithb130fe72016-06-23 19:16:49 +00003279 if (ER.isInvalid())
3280 return StmtError();
3281 RetValExp = ER.get();
3282 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003283 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3284 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003285 }
3286
3287 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003288 // In C++1y, the return type may involve 'auto'.
3289 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3290 FunctionDecl *FD = CurLambda->CallOperator;
3291 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003292 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003293
3294 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3295 assert(AT && "lost auto type from lambda return type");
3296 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3297 FD->setInvalidDecl();
3298 return StmtError();
3299 }
Alp Toker314cc812014-01-25 16:55:45 +00003300 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003301 } else if (CurCap->HasImplicitReturnType) {
3302 // For blocks/lambdas with implicit return types, we check each return
3303 // statement individually, and deduce the common return type when the block
3304 // or lambda is completed.
3305 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003306 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003307 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3308 if (Result.isInvalid())
3309 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003310 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003311
Richard Smith5a0e50c2014-12-19 22:10:51 +00003312 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3313 // when deducing a return type for a lambda-expression (or by extension
3314 // for a block). These rules differ from the stated C++11 rules only in
3315 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003316 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003317 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003318 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003319 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003320 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003321 if (RetValExp) {
3322 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3323 // initializer list, because it is not an expression (even
3324 // though we represent it as one). We still deduce 'void'.
3325 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3326 << RetValExp->getSourceRange();
3327 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003328
Jordan Rosed39e5f12012-07-02 21:19:23 +00003329 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003330 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003331
3332 // Although we'll properly infer the type of the block once it's completed,
3333 // make sure we provide a return type now for better error recovery.
3334 if (CurCap->ReturnType.isNull())
3335 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003336 }
Eli Friedman34b49062012-01-26 03:00:14 +00003337 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003338
Simon Pilgrim20692a02019-10-05 13:20:42 +00003339 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3340 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
Eli Friedman34b49062012-01-26 03:00:14 +00003341 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3342 return StmtError();
3343 }
Simon Pilgrim20692a02019-10-05 13:20:42 +00003344 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003345 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3346 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003347 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003348 assert(CurLambda && "unknown kind of captured scope");
Simon Pilgrim20692a02019-10-05 13:20:42 +00003349 if (CurLambda->CallOperator->getType()
3350 ->castAs<FunctionType>()
Richard Smith4db51c22013-09-25 05:02:54 +00003351 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003352 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3353 return StmtError();
3354 }
3355 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003356
Steve Naroffc540d662008-09-03 18:15:37 +00003357 // Otherwise, verify that this result type matches the previous one. We are
3358 // pickier with blocks than for normal functions because we don't have GCC
3359 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003360 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003361 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003362 // Delay processing for now. TODO: there are lots of dependent
3363 // types we can conclusively prove aren't void.
3364 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003365 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003366 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003367 (RetValExp->isTypeDependent() ||
3368 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003369 if (!getLangOpts().CPlusPlus &&
3370 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003371 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003372 else {
3373 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003374 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003375 }
Steve Naroffc540d662008-09-03 18:15:37 +00003376 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003377 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003378 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3379 } else if (!RetValExp->isTypeDependent()) {
3380 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003381
John McCall5500ef22011-08-17 22:09:46 +00003382 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3383 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3384 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003385
John McCall5500ef22011-08-17 22:09:46 +00003386 // In C++ the return statement is handled via a copy initialization.
3387 // the C version of which boils down to CheckSingleAssignmentConstraints.
Richard Trieu09c163b2018-03-15 03:00:55 +00003388 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
John McCall5500ef22011-08-17 22:09:46 +00003389 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3390 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003391 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003392 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3393 FnRetType, RetValExp);
3394 if (Res.isInvalid()) {
3395 // FIXME: Cleanup temporaries here, anyway?
3396 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003397 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003398 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003399 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003400 } else {
Richard Trieu09c163b2018-03-15 03:00:55 +00003401 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Steve Naroffc540d662008-09-03 18:15:37 +00003402 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003403
John McCall75f92b52011-08-17 21:34:14 +00003404 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003405 ExprResult ER =
3406 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003407 if (ER.isInvalid())
3408 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003409 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003410 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003411 auto *Result =
3412 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003413
Jordan Rosed39e5f12012-07-02 21:19:23 +00003414 // If we need to check for the named return value optimization,
3415 // or if we need to infer the return type,
3416 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003417 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003418 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Richard Smith9f690bd2015-10-27 06:02:45 +00003420 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3421 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3422
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003423 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003424}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003425
Nico Weber72889432014-09-06 01:25:55 +00003426namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003427/// Marks all typedefs in all local classes in a type referenced.
Nico Weber72889432014-09-06 01:25:55 +00003428///
3429/// In a function like
3430/// auto f() {
3431/// struct S { typedef int a; };
3432/// return S();
3433/// }
3434///
3435/// the local type escapes and could be referenced in some TUs but not in
3436/// others. Pretend that all local typedefs are always referenced, to not warn
3437/// on this. This isn't necessary if f has internal linkage, or the typedef
3438/// is private.
3439class LocalTypedefNameReferencer
3440 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3441public:
3442 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3443 bool VisitRecordType(const RecordType *RT);
3444private:
3445 Sema &S;
3446};
3447bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3448 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3449 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3450 R->isDependentType())
3451 return true;
3452 for (auto *TmpD : R->decls())
3453 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3454 if (T->getAccess() != AS_private || R->hasFriends())
3455 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3456 return true;
3457}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003458}
Nico Weber72889432014-09-06 01:25:55 +00003459
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003460TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Leonard Chanc72aaf62019-05-07 03:20:17 +00003461 return FD->getTypeSourceInfo()
3462 ->getTypeLoc()
3463 .getAsAdjusted<FunctionProtoTypeLoc>()
3464 .getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003465}
3466
Richard Smith2a7d4812013-05-04 07:00:32 +00003467/// Deduce the return type for a function from a returned expression, per
3468/// C++1y [dcl.spec.auto]p6.
3469bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3470 SourceLocation ReturnLoc,
3471 Expr *&RetExpr,
3472 AutoType *AT) {
Richard Smith50e291e2018-01-02 23:52:42 +00003473 // If this is the conversion function for a lambda, we choose to deduce it
3474 // type from the corresponding call operator, not from the synthesized return
3475 // statement within it. See Sema::DeduceReturnType.
3476 if (isLambdaConversionOperator(FD))
3477 return false;
3478
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003479 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003480 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003481
Richard Smithc58f38f2013-08-14 20:16:31 +00003482 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3483 // If the deduction is for a return statement and the initializer is
3484 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003485 Diag(RetExpr->getExprLoc(),
3486 getCurLambda() ? diag::err_lambda_return_init_list
3487 : diag::err_auto_fn_return_init_list)
3488 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003489 return true;
3490 }
3491
3492 if (FD->isDependentContext()) {
3493 // C++1y [dcl.spec.auto]p12:
3494 // Return type deduction [...] occurs when the definition is
3495 // instantiated even if the function body contains a return
3496 // statement with a non-type-dependent operand.
3497 assert(AT->isDeduced() && "should have deduced to dependent type");
3498 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003499 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003500
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003501 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003502 // Otherwise, [...] deduce a value for U using the rules of template
3503 // argument deduction.
3504 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3505
3506 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3507 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3508 << OrigResultType.getType() << RetExpr->getType();
3509
3510 if (DAR != DAR_Succeeded)
3511 return true;
Nico Weber72889432014-09-06 01:25:55 +00003512
3513 // If a local type is part of the returned type, mark its fields as
3514 // referenced.
3515 LocalTypedefNameReferencer Referencer(*this);
3516 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003517 } else {
3518 // In the case of a return with no operand, the initializer is considered
3519 // to be void().
3520 //
3521 // Deduction here can only succeed if the return type is exactly 'cv auto'
3522 // or 'decltype(auto)', so just check for that case directly.
3523 if (!OrigResultType.getType()->getAs<AutoType>()) {
3524 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3525 << OrigResultType.getType();
3526 return true;
3527 }
3528 // We always deduce U = void in this case.
3529 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3530 if (Deduced.isNull())
3531 return true;
3532 }
3533
Michael Liao24337db2019-09-25 16:51:45 +00003534 // CUDA: Kernel function must have 'void' return type.
3535 if (getLangOpts().CUDA)
3536 if (FD->hasAttr<CUDAGlobalAttr>() && !Deduced->isVoidType()) {
3537 Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3538 << FD->getType() << FD->getSourceRange();
3539 return true;
3540 }
3541
Richard Smith2a7d4812013-05-04 07:00:32 +00003542 // If a function with a declared return type that contains a placeholder type
3543 // has multiple return statements, the return type is deduced for each return
3544 // statement. [...] if the type deduced is not the same in each deduction,
3545 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003546 QualType DeducedT = AT->getDeducedType();
3547 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003548 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003549 // It is possible that NewAT->getDeducedType() is null. When that happens,
3550 // we should not crash, instead we ignore this deduction.
3551 if (NewAT->getDeducedType().isNull())
3552 return false;
3553
Douglas Gregora602a152015-10-01 20:20:47 +00003554 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003555 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003556 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3557 NewAT->getDeducedType());
3558 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003559 const LambdaScopeInfo *LambdaSI = getCurLambda();
3560 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3561 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003562 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003563 << true /*IsLambda*/;
3564 } else {
3565 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3566 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003567 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003568 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003569 return true;
3570 }
3571 } else if (!FD->isInvalidDecl()) {
3572 // Update all declarations of the function to have the deduced return type.
3573 Context.adjustDeducedFunctionResultType(FD, Deduced);
3574 }
3575
3576 return false;
3577}
3578
John McCalldadc5752010-08-24 06:29:42 +00003579StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003580Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3581 Scope *CurScope) {
Sam McCall835d67f2019-05-08 05:49:42 +00003582 // Correct typos, in case the containing function returns 'auto' and
3583 // RetValExp should determine the deduced type.
3584 ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
3585 if (RetVal.isInvalid())
3586 return StmtError();
3587 StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
Faisal Valid143a0c2017-04-01 21:30:49 +00003588 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3589 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003590 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003591
Taiju Tsuiki3be68e12018-06-19 05:35:30 +00003592 if (VarDecl *VD =
3593 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3594 CurScope->addNRVOCandidate(VD);
3595 } else {
3596 CurScope->setNoNRVO();
3597 }
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003598
Nico Weberd64657f2015-03-09 02:47:59 +00003599 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3600
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003601 return R;
3602}
3603
3604StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003605 // Check for unexpanded parameter packs.
3606 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3607 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003608
Eli Friedman34b49062012-01-26 03:00:14 +00003609 if (isa<CapturingScopeInfo>(getCurFunction()))
3610 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003611
Chris Lattner79413952008-12-04 23:50:19 +00003612 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003613 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003614 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003615 bool isObjCMethod = false;
3616
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003617 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003618 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003619 if (FD->hasAttrs())
3620 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003621 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003622 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003623 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003624 if (FD->isMain() && RetValExp)
3625 if (isa<CXXBoolLiteralExpr>(RetValExp))
3626 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3627 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003628 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003629 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003630 isObjCMethod = true;
3631 if (MD->hasAttrs())
3632 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003633 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3634 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003635 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003636 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003637 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3638 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003639 }
3640 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003641 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003642
Richard Smithb130fe72016-06-23 19:16:49 +00003643 // C++1z: discarded return statements are not considered when deducing a
3644 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003645 if (ExprEvalContexts.back().Context ==
3646 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003647 FnRetType->getContainedAutoType()) {
3648 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003649 ExprResult ER =
3650 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smithb130fe72016-06-23 19:16:49 +00003651 if (ER.isInvalid())
3652 return StmtError();
3653 RetValExp = ER.get();
3654 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003655 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3656 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003657 }
3658
Richard Smith2a7d4812013-05-04 07:00:32 +00003659 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3660 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003661 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003662 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3663 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003664 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003665 FD->setInvalidDecl();
3666 return StmtError();
3667 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003668 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003669 }
3670 }
3671 }
3672
Richard Smithc58f38f2013-08-14 20:16:31 +00003673 bool HasDependentReturnType = FnRetType->isDependentType();
3674
Craig Topperc3ec1492014-05-26 06:22:03 +00003675 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003676 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003677 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003678 if (isa<InitListExpr>(RetValExp)) {
3679 // We simply never allow init lists as the return value of void
3680 // functions. This is compatible because this was never allowed before,
3681 // so there's no legacy code to deal with.
3682 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3683 int FunctionKind = 0;
3684 if (isa<ObjCMethodDecl>(CurDecl))
3685 FunctionKind = 1;
3686 else if (isa<CXXConstructorDecl>(CurDecl))
3687 FunctionKind = 2;
3688 else if (isa<CXXDestructorDecl>(CurDecl))
3689 FunctionKind = 3;
3690
3691 Diag(ReturnLoc, diag::err_return_init_list)
3692 << CurDecl->getDeclName() << FunctionKind
3693 << RetValExp->getSourceRange();
3694
3695 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003696 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003697 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003698 // C99 6.8.6.4p1 (ext_ since GCC warns)
3699 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003700 if (RetValExp->getType()->isVoidType()) {
3701 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3702 if (isa<CXXConstructorDecl>(CurDecl) ||
3703 isa<CXXDestructorDecl>(CurDecl))
3704 D = diag::err_ctor_dtor_returns_void;
3705 else
3706 D = diag::ext_return_has_void_expr;
3707 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003708 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003709 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003710 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003711 if (Result.isInvalid())
3712 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003713 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003714 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003715 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003716 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003717 // return of void in constructor/destructor is illegal in C++.
3718 if (D == diag::err_ctor_dtor_returns_void) {
3719 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3720 Diag(ReturnLoc, D)
3721 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3722 << RetValExp->getSourceRange();
3723 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003724 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003725 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003726 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003727 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003728
3729 int FunctionKind = 0;
3730 if (isa<ObjCMethodDecl>(CurDecl))
3731 FunctionKind = 1;
3732 else if (isa<CXXConstructorDecl>(CurDecl))
3733 FunctionKind = 2;
3734 else if (isa<CXXDestructorDecl>(CurDecl))
3735 FunctionKind = 3;
3736
Nick Lewycky1be750a2011-06-01 07:44:31 +00003737 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003738 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003739 << RetValExp->getSourceRange();
3740 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003741 }
Mike Stump11289f42009-09-09 15:08:12 +00003742
Sebastian Redleef474c2012-02-22 10:50:08 +00003743 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003744 ExprResult ER =
3745 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003746 if (ER.isInvalid())
3747 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003748 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003749 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751
Bruno Ricci023b1d12018-10-30 14:40:49 +00003752 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3753 /* NRVOCandidate=*/nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003754 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003755 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003756
David Majnemer2887ad32014-12-13 08:12:56 +00003757 unsigned DiagID;
3758 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3759 // C++11 [stmt.return]p2
3760 DiagID = diag::err_constexpr_return_missing_expr;
3761 FD->setInvalidDecl();
3762 } else if (getLangOpts().C99) {
3763 // C99 6.8.6.4p1 (ext_ since GCC warns)
3764 DiagID = diag::ext_return_missing_expr;
3765 } else {
3766 // C90 6.6.6.4p4
3767 DiagID = diag::warn_return_missing_expr;
3768 }
3769
3770 if (FD)
Gauthier Harnisch796ed032019-06-14 08:56:20 +00003771 Diag(ReturnLoc, DiagID)
3772 << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003773 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003774 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003775
Bruno Ricci023b1d12018-10-30 14:40:49 +00003776 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3777 /* NRVOCandidate=*/nullptr);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003778 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003779 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003780 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003781
3782 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3783
3784 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3785 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3786 // function return.
3787
3788 // In C++ the return statement is handled via a copy initialization,
3789 // the C version of which boils down to CheckSingleAssignmentConstraints.
3790 if (RetValExp)
Richard Trieu09c163b2018-03-15 03:00:55 +00003791 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Richard Smith2a7d4812013-05-04 07:00:32 +00003792 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003793 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003795 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003796 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003798 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003799 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003800 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003801 return StmtError();
3802 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003803 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003804
3805 // If we have a related result type, we need to implicitly
3806 // convert back to the formal result type. We can't pretend to
3807 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003808 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003809 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003810 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3811 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003812 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3813 if (Res.isInvalid()) {
3814 // FIXME: Clean up temporaries here anyway?
3815 return StmtError();
3816 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003817 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003818 }
3819
Artyom Skrobov9f213442014-01-24 11:10:39 +00003820 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3821 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823
John McCallacf0ee52010-10-08 02:01:28 +00003824 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003825 ExprResult ER =
3826 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003827 if (ER.isInvalid())
3828 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003829 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003830 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003831 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833
3834 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003835 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003836 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003837 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003838
Richard Smith9f690bd2015-10-27 06:02:45 +00003839 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3840 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3841
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003842 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003843}
3844
John McCalldadc5752010-08-24 06:29:42 +00003845StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003846Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003847 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003848 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003849 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003850 if (Var && Var->isInvalidDecl())
3851 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003852
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003853 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003854}
3855
John McCalldadc5752010-08-24 06:29:42 +00003856StmtResult
John McCallb268a282010-08-23 23:25:46 +00003857Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003858 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003859}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003860
John McCalldadc5752010-08-24 06:29:42 +00003861StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003862Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003863 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003864 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003865 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3866
Reid Kleckner87a31802018-03-12 21:43:02 +00003867 setFunctionHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003868 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003869 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3870 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003871}
3872
John McCall0bd3e402012-05-08 21:41:25 +00003873StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003874 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003875 ExprResult Result = DefaultLvalueConversion(Throw);
3876 if (Result.isInvalid())
3877 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003878
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003879 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003880 if (Result.isInvalid())
3881 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003882 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003883
Douglas Gregor2900c162010-04-22 21:44:01 +00003884 QualType ThrowType = Throw->getType();
3885 // Make sure the expression type is an ObjC pointer or "void *".
3886 if (!ThrowType->isDependentType() &&
3887 !ThrowType->isObjCObjectPointerType()) {
3888 const PointerType *PT = ThrowType->getAs<PointerType>();
3889 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003890 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003891 << Throw->getType() << Throw->getSourceRange());
3892 }
3893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003895 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003896}
3897
John McCalldadc5752010-08-24 06:29:42 +00003898StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003899Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003900 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003901 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003902 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3903
John McCallb268a282010-08-23 23:25:46 +00003904 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003905 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003906 // in the context of an @catch clause).
3907 Scope *AtCatchParent = CurScope;
3908 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3909 AtCatchParent = AtCatchParent->getParent();
3910 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003911 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912 }
John McCallb268a282010-08-23 23:25:46 +00003913 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003914}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003915
John McCalld9bb7432011-07-27 21:50:02 +00003916ExprResult
3917Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3918 ExprResult result = DefaultLvalueConversion(operand);
3919 if (result.isInvalid())
3920 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003921 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003922
3923 // Make sure the expression type is an ObjC pointer or "void *".
3924 QualType type = operand->getType();
3925 if (!type->isDependentType() &&
3926 !type->isObjCObjectPointerType()) {
3927 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003928 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3929 if (getLangOpts().CPlusPlus) {
3930 if (RequireCompleteType(atLoc, type,
3931 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003932 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003933 << type << operand->getSourceRange();
3934
3935 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003936 if (result.isInvalid())
3937 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003938 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003939 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003940 << type << operand->getSourceRange();
3941
3942 operand = result.get();
3943 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003944 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003945 << type << operand->getSourceRange();
3946 }
3947 }
John McCalld9bb7432011-07-27 21:50:02 +00003948 }
3949
3950 // The operand to @synchronized is a full-expression.
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003951 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
John McCalld9bb7432011-07-27 21:50:02 +00003952}
3953
John McCalldadc5752010-08-24 06:29:42 +00003954StmtResult
John McCallb268a282010-08-23 23:25:46 +00003955Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3956 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003957 // We can't jump into or indirect-jump out of a @synchronized block.
Reid Kleckner87a31802018-03-12 21:43:02 +00003958 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003959 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003960}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003961
3962/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3963/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003964StmtResult
John McCall48871652010-08-21 09:40:31 +00003965Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003966 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003967 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003968 return new (Context)
3969 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003970}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003971
John McCall31168b02011-06-15 23:02:42 +00003972StmtResult
3973Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
Reid Kleckner87a31802018-03-12 21:43:02 +00003974 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003975 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003976}
3977
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003978namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003979class CatchHandlerType {
3980 QualType QT;
3981 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003982
Aaron Ballman8aee642902015-04-08 00:05:29 +00003983 // This is a special constructor to be used only with DenseMapInfo's
3984 // getEmptyKey() and getTombstoneKey() functions.
3985 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3986 enum Unique { ForDenseMap };
3987 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3988
Sebastian Redl63c4da02009-07-29 17:15:45 +00003989public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003990 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003991 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003992 /// level pointer and cv-qualifiers.
3993 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3994 if (QT->isPointerType())
3995 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003996
Aaron Ballman8aee642902015-04-08 00:05:29 +00003997 if (IsPointer || QT->isReferenceType())
3998 QT = QT->getPointeeType();
3999 QT = QT.getUnqualifiedType();
4000 }
4001
4002 /// Used when creating a CatchHandlerType from a base class type; pretends the
4003 /// type passed in had the pointer qualifier, does not need to get an
4004 /// unqualified type.
4005 CatchHandlerType(QualType QT, bool IsPointer)
4006 : QT(QT), IsPointer(IsPointer) {}
4007
4008 QualType underlying() const { return QT; }
4009 bool isPointer() const { return IsPointer; }
4010
4011 friend bool operator==(const CatchHandlerType &LHS,
4012 const CatchHandlerType &RHS) {
4013 // If the pointer qualification does not match, we can return early.
4014 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00004015 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00004016 // Otherwise, check the underlying type without cv-qualifiers.
4017 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00004018 }
4019};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00004020} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00004021
Aaron Ballman8aee642902015-04-08 00:05:29 +00004022namespace llvm {
4023template <> struct DenseMapInfo<CatchHandlerType> {
4024 static CatchHandlerType getEmptyKey() {
4025 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4026 CatchHandlerType::ForDenseMap);
4027 }
4028
4029 static CatchHandlerType getTombstoneKey() {
4030 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4031 CatchHandlerType::ForDenseMap);
4032 }
4033
4034 static unsigned getHashValue(const CatchHandlerType &Base) {
4035 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
4036 }
4037
4038 static bool isEqual(const CatchHandlerType &LHS,
4039 const CatchHandlerType &RHS) {
4040 return LHS == RHS;
4041 }
4042};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004043}
Aaron Ballman8aee642902015-04-08 00:05:29 +00004044
4045namespace {
4046class CatchTypePublicBases {
4047 ASTContext &Ctx;
4048 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
4049 const bool CheckAgainstPointer;
4050
4051 CXXCatchStmt *FoundHandler;
4052 CanQualType FoundHandlerType;
4053
4054public:
4055 CatchTypePublicBases(
4056 ASTContext &Ctx,
4057 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
4058 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
4059 FoundHandler(nullptr) {}
4060
4061 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
4062 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
4063
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004064 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004065 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004066 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00004067 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00004068 auto I = M.find(Check);
4069 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004070 FoundHandler = I->second;
4071 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00004072 return true;
4073 }
4074 }
4075 return false;
4076 }
4077};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004078}
Dan Gohman28ade552010-07-26 21:25:24 +00004079
Sebastian Redl9b244a82008-12-22 21:35:02 +00004080/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4081/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00004082StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4083 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00004084 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004085 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +00004086 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +00004087 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +00004088 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
Alexey Bataevc416e642019-02-08 18:02:25 +00004089 }
Anders Carlsson68b36af2011-02-19 19:26:44 +00004090
Justin Lebar2a8db342016-09-28 22:45:54 +00004091 // Exceptions aren't allowed in CUDA device code.
4092 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00004093 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4094 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00004095
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004096 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4097 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4098
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004099 sema::FunctionScopeInfo *FSI = getCurFunction();
4100
Reid Klecknere7175912015-02-02 22:15:31 +00004101 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004102 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00004103 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004104 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00004105 }
4106
Robert Wilhelmcafda822013-08-22 09:20:03 +00004107 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00004108 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00004109 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00004110
Aaron Ballman8aee642902015-04-08 00:05:29 +00004111 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004112 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004113 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004114
Aaron Ballman8aee642902015-04-08 00:05:29 +00004115 // Diagnose when the handler is a catch-all handler, but it isn't the last
4116 // handler for the try block. [except.handle]p5. Also, skip exception
4117 // declarations that are invalid, since we can't usefully report on them.
4118 if (!H->getExceptionDecl()) {
4119 if (i < NumHandlers - 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004120 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00004121 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00004122 } else if (H->getExceptionDecl()->isInvalidDecl())
4123 continue;
4124
4125 // Walk the type hierarchy to diagnose when this type has already been
4126 // handled (duplication), or cannot be handled (derivation inversion). We
4127 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00004128 CatchHandlerType HandlerCHT =
4129 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00004130
4131 // We can ignore whether the type is a reference or a pointer; we need the
4132 // underlying declaration type in order to get at the underlying record
4133 // decl, if there is one.
4134 QualType Underlying = HandlerCHT.underlying();
4135 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4136 if (!RD->hasDefinition())
4137 continue;
4138 // Check that none of the public, unambiguous base classes are in the
4139 // map ([except.handle]p1). Give the base classes the same pointer
4140 // qualification as the original type we are basing off of. This allows
4141 // comparison against the handler type using the same top-level pointer
4142 // as the original type.
4143 CXXBasePaths Paths;
4144 Paths.setOrigin(RD);
4145 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004146 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004147 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4148 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4149 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4150 diag::warn_exception_caught_by_earlier_handler)
4151 << H->getCaughtType();
4152 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4153 diag::note_previous_exception_handler)
4154 << Problem->getCaughtType();
4155 }
4156 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00004157 }
Mike Stump11289f42009-09-09 15:08:12 +00004158
Aaron Ballman8aee642902015-04-08 00:05:29 +00004159 // Add the type the list of ones we have handled; diagnose if we've already
4160 // handled it.
4161 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4162 if (!R.second) {
4163 const CXXCatchStmt *Problem = R.first->second;
4164 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4165 diag::warn_exception_caught_by_earlier_handler)
4166 << H->getCaughtType();
4167 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4168 diag::note_previous_exception_handler)
4169 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00004170 }
4171 }
Mike Stump11289f42009-09-09 15:08:12 +00004172
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004173 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00004174
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004175 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00004176}
John Wiegley1c0675e2011-04-28 01:08:34 +00004177
Reid Klecknere7175912015-02-02 22:15:31 +00004178StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4179 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004180 assert(TryBlock && Handler);
4181
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004182 sema::FunctionScopeInfo *FSI = getCurFunction();
4183
Reid Klecknere7175912015-02-02 22:15:31 +00004184 // SEH __try is incompatible with C++ try. Borland appears to support this,
4185 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004186 if (!getLangOpts().Borland) {
4187 if (FSI->FirstCXXTryLoc.isValid()) {
4188 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4189 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4190 }
Reid Klecknere7175912015-02-02 22:15:31 +00004191 }
John Wiegley1c0675e2011-04-28 01:08:34 +00004192
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004193 FSI->setHasSEHTry(TryLoc);
4194
4195 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4196 // track if they use SEH.
4197 DeclContext *DC = CurContext;
4198 while (DC && !DC->isFunctionOrMethod())
4199 DC = DC->getParent();
4200 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4201 if (FD)
4202 FD->setUsesSEHTry(true);
4203 else
4204 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00004205
Reid Kleckner8819a402015-07-10 00:16:25 +00004206 // Reject __try on unsupported targets.
4207 if (!Context.getTargetInfo().isSEHTrySupported())
4208 Diag(TryLoc, diag::err_seh_try_unsupported);
4209
Reid Klecknere7175912015-02-02 22:15:31 +00004210 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00004211}
4212
Reid Kleckner7177ce92019-11-07 14:13:26 -08004213StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
4214 Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004215 assert(FilterExpr && Block);
Reid Kleckner7177ce92019-11-07 14:13:26 -08004216 QualType FTy = FilterExpr->getType();
4217 if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4218 return StmtError(
4219 Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4220 << FTy);
John Wiegley1c0675e2011-04-28 01:08:34 +00004221 }
Reid Kleckner7177ce92019-11-07 14:13:26 -08004222 return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004223}
4224
Nico Weberd64657f2015-03-09 02:47:59 +00004225void Sema::ActOnStartSEHFinallyBlock() {
4226 CurrentSEHFinally.push_back(CurScope);
4227}
4228
Nico Weberce903292015-03-09 03:17:15 +00004229void Sema::ActOnAbortSEHFinallyBlock() {
4230 CurrentSEHFinally.pop_back();
4231}
4232
Nico Weberd64657f2015-03-09 02:47:59 +00004233StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004234 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00004235 CurrentSEHFinally.pop_back();
4236 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004237}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004238
Nico Weberc7d05962014-07-06 22:32:59 +00004239StmtResult
4240Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00004241 Scope *SEHTryParent = CurScope;
4242 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4243 SEHTryParent = SEHTryParent->getParent();
4244 if (!SEHTryParent)
4245 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00004246 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00004247
Nico Weber9b982072014-07-07 00:12:30 +00004248 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00004249}
4250
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004251StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4252 bool IsIfExists,
4253 NestedNameSpecifierLoc QualifierLoc,
4254 DeclarationNameInfo NameInfo,
4255 Stmt *Nested)
4256{
4257 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004258 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004259 cast<CompoundStmt>(Nested));
4260}
4261
4262
Chad Rosier02a84392012-08-10 17:56:09 +00004263StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004264 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004265 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004266 UnqualifiedId &Name,
4267 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00004268 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004269 SS.getWithLocInContext(Context),
4270 GetNameFromUnqualifiedId(Name),
4271 Nested);
4272}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004273
4274RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00004275Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4276 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004277 DeclContext *DC = CurContext;
4278 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4279 DC = DC->getParent();
4280
Craig Topperc3ec1492014-05-26 06:22:03 +00004281 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004282 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004283 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4284 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004285 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004286 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004287
Alexey Bataev330de032014-10-29 12:21:55 +00004288 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004289 DC->addDecl(RD);
4290 RD->setImplicit();
4291 RD->startDefinition();
4292
Alexey Bataev9959db52014-05-06 10:08:46 +00004293 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004294 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004295 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004296 return RD;
4297}
4298
Richard Smith0621a8f2019-05-31 00:45:10 +00004299static bool
Richard Smith30116532019-05-28 23:09:46 +00004300buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4301 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4302 SmallVectorImpl<Expr *> &CaptureInits) {
4303 for (const sema::Capture &Cap : RSI->Captures) {
Richard Smith8cb63232019-05-28 23:09:44 +00004304 if (Cap.isInvalid())
4305 continue;
4306
Richard Smithe5182352019-06-02 04:00:43 +00004307 // Form the initializer for the capture.
4308 ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4309 RSI->CapRegionKind == CR_OpenMP);
4310
4311 // FIXME: Bail out now if the capture is not used and the initializer has
4312 // no side-effects.
4313
Richard Smith30116532019-05-28 23:09:46 +00004314 // Create a field for this capture.
4315 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4316
Richard Smithe5182352019-06-02 04:00:43 +00004317 // Add the capture to our list of captures.
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004318 if (Cap.isThisCapture()) {
4319 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004320 CapturedStmt::VCK_This));
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004321 } else if (Cap.isVLATypeCapture()) {
Alexey Bataev330de032014-10-29 12:21:55 +00004322 Captures.push_back(
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004323 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
Richard Smithe5182352019-06-02 04:00:43 +00004324 } else {
4325 assert(Cap.isVariableCapture() && "unknown kind of capture");
4326
4327 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4328 S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
4329
4330 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4331 Cap.isReferenceCapture()
4332 ? CapturedStmt::VCK_ByRef
4333 : CapturedStmt::VCK_ByCopy,
4334 Cap.getVariable()));
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004335 }
Richard Smith0621a8f2019-05-31 00:45:10 +00004336 CaptureInits.push_back(Init.get());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004337 }
Richard Smith0621a8f2019-05-31 00:45:10 +00004338 return false;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004339}
4340
4341void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004342 CapturedRegionKind Kind,
4343 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004344 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004345 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004346
Alexey Bataev9959db52014-05-06 10:08:46 +00004347 // Build the context parameter
4348 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4349 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4350 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004351 auto *Param =
4352 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4353 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004354 DC->addDecl(Param);
4355
4356 CD->setContextParam(0, Param);
4357
4358 // Enter the capturing scope for this captured region.
4359 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4360
4361 if (CurScope)
4362 PushDeclContext(CurScope, CD);
4363 else
4364 CurContext = CD;
4365
Faisal Valid143a0c2017-04-01 21:30:49 +00004366 PushExpressionEvaluationContext(
4367 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004368}
4369
4370void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4371 CapturedRegionKind Kind,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00004372 ArrayRef<CapturedParamNameType> Params,
4373 unsigned OpenMPCaptureLevel) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004374 CapturedDecl *CD = nullptr;
4375 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4376
4377 // Build the context parameter
4378 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4379 bool ContextIsFound = false;
4380 unsigned ParamNum = 0;
4381 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4382 E = Params.end();
4383 I != E; ++I, ++ParamNum) {
4384 if (I->second.isNull()) {
4385 assert(!ContextIsFound &&
4386 "null type has been found already for '__context' parameter");
4387 IdentifierInfo *ParamName = &Context.Idents.get("__context");
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004388 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4389 .withConst()
4390 .withRestrict();
Alexey Bataev56223232017-06-09 13:40:18 +00004391 auto *Param =
4392 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4393 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004394 DC->addDecl(Param);
4395 CD->setContextParam(ParamNum, Param);
4396 ContextIsFound = true;
4397 } else {
4398 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004399 auto *Param =
4400 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4401 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004402 DC->addDecl(Param);
4403 CD->setParam(ParamNum, Param);
4404 }
4405 }
4406 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004407 if (!ContextIsFound) {
4408 // Add __context implicitly if it is not specified.
4409 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4410 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004411 auto *Param =
4412 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4413 ImplicitParamDecl::CapturedContext);
Alexey Bataev301a2d92014-05-14 10:40:54 +00004414 DC->addDecl(Param);
4415 CD->setContextParam(ParamNum, Param);
4416 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004417 // Enter the capturing scope for this captured region.
Joel E. Denny7d5bc552019-08-22 03:34:30 +00004418 PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004419
4420 if (CurScope)
4421 PushDeclContext(CurScope, CD);
4422 else
4423 CurContext = CD;
4424
Faisal Valid143a0c2017-04-01 21:30:49 +00004425 PushExpressionEvaluationContext(
4426 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004427}
4428
Wei Pan17fbf6e2013-05-04 03:59:06 +00004429void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004430 DiscardCleanupsInEvaluationContext();
4431 PopExpressionEvaluationContext();
Richard Smith0621a8f2019-05-31 00:45:10 +00004432 PopDeclContext();
4433 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4434 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004435
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004436 RecordDecl *Record = RSI->TheRecordDecl;
4437 Record->setInvalidDecl();
4438
Aaron Ballman62e47c42014-03-10 13:43:55 +00004439 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004440 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00004441 SourceLocation(), SourceLocation(), ParsedAttributesView());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004442}
4443
4444StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
Richard Smith0621a8f2019-05-31 00:45:10 +00004445 // Leave the captured scope before we start creating captures in the
4446 // enclosing scope.
4447 DiscardCleanupsInEvaluationContext();
4448 PopExpressionEvaluationContext();
4449 PopDeclContext();
4450 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4451 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004452
4453 SmallVector<CapturedStmt::Capture, 4> Captures;
4454 SmallVector<Expr *, 4> CaptureInits;
Richard Smith0621a8f2019-05-31 00:45:10 +00004455 if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4456 return StmtError();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004457
4458 CapturedDecl *CD = RSI->TheCapturedDecl;
4459 RecordDecl *RD = RSI->TheRecordDecl;
4460
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004461 CapturedStmt *Res = CapturedStmt::Create(
4462 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4463 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004464
4465 CD->setBody(Res->getCapturedStmt());
4466 RD->completeDefinition();
4467
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004468 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004469}