blob: 357e257abe096c3b2d5b47d03b0d7d7b444a9ddf [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
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000199void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000200 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
201 return DiagnoseUnusedExprResult(Label->getSubStmt());
202
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000203 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000204 if (!E)
205 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000206
207 // If we are in an unevaluated expression context, then there can be no unused
208 // results because the results aren't expected to be used in the first place.
209 if (isUnevaluatedContext())
210 return;
211
Nico Weber0e631632015-10-27 19:47:40 +0000212 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000213 // In most cases, we don't want to warn if the expression is written in a
214 // macro body, or if the macro comes from a system header. If the offending
215 // expression is a call to a function with the warn_unused_result attribute,
216 // we warn no matter the location. Because of the order in which the various
217 // checks need to happen, we factor out the macro-related test here.
Fangrui Song6907ce22018-07-30 19:24:48 +0000218 bool ShouldSuppress =
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000219 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
220 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000221
Eli Friedmanc11535c2012-05-24 00:47:05 +0000222 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000223 SourceLocation Loc;
224 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000225 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000226 return;
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner6dc7e572012-08-31 22:39:21 +0000228 // If this is a GNU statement expression expanded from a macro, it is probably
229 // unused because it is a function-like macro that can be used as either an
230 // expression or statement. Don't warn, because it is almost certainly a
231 // false positive.
232 if (isa<StmtExpr>(E) && Loc.isMacroID())
233 return;
234
Nico Weber0e631632015-10-27 19:47:40 +0000235 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
236 // That macro is frequently used to suppress "unused parameter" warnings,
237 // but its implementation makes clang's -Wunused-value fire. Prevent this.
238 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
239 SourceLocation SpellLoc = Loc;
240 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
241 return;
242 }
243
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000244 // Okay, we have an unused result. Depending on what the base expression is,
245 // we might want to make a more specific diagnostic. Check for one of these
246 // cases now.
247 unsigned DiagID = diag::warn_unused_expr;
Bill Wendling7c44da22018-10-31 03:48:47 +0000248 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000249 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000250 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
251 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000252
Chandler Carruthe2669392011-08-17 09:34:37 +0000253 if (DiagnoseUnusedComparison(*this, E))
254 return;
255
Eli Friedmanc11535c2012-05-24 00:47:05 +0000256 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000257 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000258 if (E->getType()->isVoidType())
259 return;
260
Aaron Ballmand23e9bc2019-01-03 14:24:31 +0000261 if (const Attr *A = CE->getUnusedResultAttr(Context)) {
262 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
263 return;
264 }
265
Chris Lattner1a6babf2009-10-13 04:53:48 +0000266 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000267 // a more specific message to make it clear what is happening. If the call
268 // is written in a macro body, only warn if it has the warn_unused_result
269 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000270 if (const Decl *FD = CE->getCalleeDecl()) {
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000271 if (ShouldSuppress)
272 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000273 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000274 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
275 return;
276 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000277 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000278 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
279 return;
280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000282 } else if (ShouldSuppress)
283 return;
284
285 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000286 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000287 Diag(Loc, diag::err_arc_unused_init_message) << R1;
288 return;
289 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000290 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000291 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000292 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
293 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000294 return;
295 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000296 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000297 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
298 const Expr *Source = POE->getSyntacticForm();
299 if (isa<ObjCSubscriptRefExpr>(Source))
300 DiagID = diag::warn_unused_container_subscript_expr;
301 else
302 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000303 } else if (const CXXFunctionalCastExpr *FC
304 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000305 const Expr *E = FC->getSubExpr();
306 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
307 E = TE->getSubExpr();
308 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000309 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000310 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
311 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
312 if (!RD->getAttr<WarnUnusedAttr>())
313 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000314 }
John McCall2351cb92010-04-06 22:24:14 +0000315 // Diagnose "(void*) blah" as a typo for "(void) blah".
316 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
317 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
318 QualType T = TI->getType();
319
320 // We really do want to use the non-canonical type here.
321 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000322 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000323
324 Diag(Loc, diag::warn_unused_voidptr)
325 << FixItHint::CreateRemoval(TL.getStarLoc());
326 return;
327 }
328 }
329
Eli Friedmanc11535c2012-05-24 00:47:05 +0000330 if (E->isGLValue() && E->getType().isVolatileQualified()) {
331 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
332 return;
333 }
334
Craig Topperc3ec1492014-05-26 06:22:03 +0000335 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000336}
337
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000338void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
339 PushCompoundScope(IsStmtExpr);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000340}
341
342void Sema::ActOnFinishOfCompoundStmt() {
343 PopCompoundScope();
344}
345
346sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
347 return getCurFunction()->CompoundScopes.back();
348}
349
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000350StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
351 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
352 const unsigned NumElts = Elts.size();
353
Chris Lattnerd864daf2007-08-27 04:29:41 +0000354 // If we're in C89 mode, check that we don't have any decls after stmts. If
355 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000356 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000357 // Note that __extension__ can be around a decl.
358 unsigned i = 0;
359 // Skip over all declarations.
360 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
361 /*empty*/;
362
363 // We found the end of the list or a statement. Scan for another declstmt.
364 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
365 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000366
Chris Lattnerd864daf2007-08-27 04:29:41 +0000367 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000368 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000369 Diag(D->getLocation(), diag::ext_mixed_decls_code);
370 }
371 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000372
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000373 // Check for suspicious empty body (null statement) in `for' and `while'
374 // statements. Don't do anything for template instantiations, this just adds
375 // noise.
376 if (NumElts != 0 && !CurrentInstantiationScope &&
377 getCurCompoundScope().HasEmptyLoopBodies) {
378 for (unsigned i = 0; i != NumElts - 1; ++i)
379 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
380 }
381
Benjamin Kramer07420902017-12-24 16:24:20 +0000382 return CompoundStmt::Create(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000383}
384
Richard Smithef6c43d2018-07-26 18:41:30 +0000385ExprResult
386Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
387 if (!Val.get())
388 return Val;
389
390 if (DiagnoseUnexpandedParameterPack(Val.get()))
391 return ExprError();
392
393 // If we're not inside a switch, let the 'case' statement handling diagnose
394 // this. Just clean up after the expression as best we can.
395 if (!getCurFunction()->SwitchStack.empty()) {
396 Expr *CondExpr =
397 getCurFunction()->SwitchStack.back().getPointer()->getCond();
398 if (!CondExpr)
399 return ExprError();
400 QualType CondType = CondExpr->getType();
401
402 auto CheckAndFinish = [&](Expr *E) {
403 if (CondType->isDependentType() || E->isTypeDependent())
404 return ExprResult(E);
405
406 if (getLangOpts().CPlusPlus11) {
407 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
408 // constant expression of the promoted type of the switch condition.
409 llvm::APSInt TempVal;
410 return CheckConvertedConstantExpression(E, CondType, TempVal,
411 CCEK_CaseValue);
412 }
413
414 ExprResult ER = E;
415 if (!E->isValueDependent())
416 ER = VerifyIntegerConstantExpression(E);
417 if (!ER.isInvalid())
418 ER = DefaultLvalueConversion(ER.get());
419 if (!ER.isInvalid())
420 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
421 return ER;
422 };
423
424 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
425 if (Converted.get() == Val.get())
426 Converted = CheckAndFinish(Val.get());
427 if (Converted.isInvalid())
428 return ExprError();
429 Val = Converted;
430 }
431
432 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
433 getLangOpts().CPlusPlus11);
434}
435
John McCalldadc5752010-08-24 06:29:42 +0000436StmtResult
Richard Smithef6c43d2018-07-26 18:41:30 +0000437Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
438 SourceLocation DotDotDotLoc, ExprResult RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000439 SourceLocation ColonLoc) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000440 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
441 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
442 : RHSVal.isInvalid() || RHSVal.get()) &&
443 "missing RHS value");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000444
John McCallaab3e412010-08-25 08:40:02 +0000445 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000446 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000447 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000448 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000449
Richard Smithef6c43d2018-07-26 18:41:30 +0000450 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
451 getCurFunction()->SwitchStack.back().setInt(true);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000452 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000453 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000454
Bruno Ricci5b30571752018-10-28 12:30:53 +0000455 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
456 CaseLoc, DotDotDotLoc, ColonLoc);
Richard Smithef6c43d2018-07-26 18:41:30 +0000457 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000458 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000459}
460
Chris Lattner34a22092009-03-04 04:23:07 +0000461/// ActOnCaseStmtBody - This installs a statement as the body of a case.
Aaron Ballmand9141742018-12-21 21:11:36 +0000462void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
Aaron Ballmand9141742018-12-21 21:11:36 +0000463 cast<CaseStmt>(S)->setSubStmt(SubStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000464}
465
John McCalldadc5752010-08-24 06:29:42 +0000466StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000467Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000468 Stmt *SubStmt, Scope *CurScope) {
John McCallaab3e412010-08-25 08:40:02 +0000469 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000470 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000471 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000472 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000473
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000474 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Richard Smithef6c43d2018-07-26 18:41:30 +0000475 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000476 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000477}
478
John McCalldadc5752010-08-24 06:29:42 +0000479StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000480Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
481 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000482 // If the label was multiply defined, reject it now.
483 if (TheDecl->getStmt()) {
484 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
485 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000486 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000487 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000488
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000489 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000490 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
491 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000492 if (!TheDecl->isGnuLocal()) {
493 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000494 if (!TheDecl->isMSAsmLabel()) {
495 // Don't update the location of MS ASM labels. These will result in
496 // a diagnostic, and changing the location here will mess that up.
497 TheDecl->setLocation(IdentLoc);
498 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000499 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000500 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000501}
502
Richard Smithc202b282012-04-14 00:33:13 +0000503StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000504 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000505 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000506 // Fill in the declaration and return it.
507 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000508 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000509}
510
Richard Trieufaca2d82016-02-18 23:58:40 +0000511namespace {
512class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
513 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
514 Sema &SemaRef;
515public:
516 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
517 void VisitBinaryOperator(BinaryOperator *E) {
518 if (E->getOpcode() == BO_Comma)
519 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
520 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
521 }
522};
523}
524
John McCalldadc5752010-08-24 06:29:42 +0000525StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000526Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
527 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000528 Stmt *thenStmt, SourceLocation ElseLoc,
529 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000530 if (Cond.isInvalid())
531 Cond = ConditionResult(
532 *this, nullptr,
533 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
534 Context.BoolTy, VK_RValue),
535 IfLoc),
536 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000537
Richard Smithb130fe72016-06-23 19:16:49 +0000538 Expr *CondExpr = Cond.get().second;
Richard Trieuf3713802018-10-25 01:08:00 +0000539 // Only call the CommaVisitor when not C89 due to differences in scope flags.
540 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
541 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
Richard Smithb130fe72016-06-23 19:16:49 +0000542 CommaVisitor(*this).Visit(CondExpr);
543
Hans Wennborg59ad1502017-11-20 17:48:54 +0000544 if (!elseStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000545 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
Hans Wennborg95419752017-11-20 17:38:16 +0000546 diag::warn_empty_if_body);
Richard Smithb130fe72016-06-23 19:16:49 +0000547
Richard Smitha547eb22016-07-14 00:11:03 +0000548 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
549 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000550}
551
552StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000553 Stmt *InitStmt, ConditionResult Cond,
554 Stmt *thenStmt, SourceLocation ElseLoc,
555 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000556 if (Cond.isInvalid())
557 return StmtError();
558
Erik Pilkington5cd57172016-08-16 17:44:11 +0000559 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Reid Kleckner87a31802018-03-12 21:43:02 +0000560 setFunctionHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000561
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000562 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
563 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000564}
Steve Naroff86272ea2007-05-29 02:14:17 +0000565
Chris Lattner67998452007-08-23 18:29:20 +0000566namespace {
567 struct CaseCompareFunctor {
568 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
569 const llvm::APSInt &RHS) {
570 return LHS.first < RHS;
571 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000572 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
573 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
574 return LHS.first < RHS.first;
575 }
Chris Lattner67998452007-08-23 18:29:20 +0000576 bool operator()(const llvm::APSInt &LHS,
577 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
578 return LHS < RHS.first;
579 }
580 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
Chris Lattner67998452007-08-23 18:29:20 +0000582
Chris Lattner4b2ff022007-09-21 18:15:22 +0000583/// CmpCaseVals - Comparison predicate for sorting case values.
584///
585static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
586 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
587 if (lhs.first < rhs.first)
588 return true;
589
590 if (lhs.first == rhs.first &&
591 lhs.second->getCaseLoc().getRawEncoding()
592 < rhs.second->getCaseLoc().getRawEncoding())
593 return true;
594 return false;
595}
596
Douglas Gregorbd6839732010-02-08 22:24:16 +0000597/// CmpEnumVals - Comparison predicate for sorting enumeration values.
598///
599static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
600 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
601{
602 return lhs.first < rhs.first;
603}
604
605/// EqEnumVals - Comparison preficate for uniqing enumeration values.
606///
607static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
608 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
609{
610 return lhs.first == rhs.first;
611}
612
Chris Lattnera96d4272009-10-16 16:45:22 +0000613/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
614/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000615static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000616 if (const auto *FE = dyn_cast<FullExpr>(E))
617 E = FE->getSubExpr();
Gabor Horvath64c32412017-08-09 08:57:09 +0000618 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
619 if (ImpCast->getCastKind() != CK_IntegralCast) break;
620 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000621 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000622 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000623}
624
Richard Smith03a4aa32016-06-23 19:02:52 +0000625ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000626 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
627 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000628
Douglas Gregore2b37442012-05-04 22:38:52 +0000629 public:
630 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000631 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
632 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000633
Craig Toppere14c0f82014-03-12 04:55:44 +0000634 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
635 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000636 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
637 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000638
Craig Toppere14c0f82014-03-12 04:55:44 +0000639 SemaDiagnosticBuilder diagnoseIncomplete(
640 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000641 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
642 << T << Cond->getSourceRange();
643 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000644
Craig Toppere14c0f82014-03-12 04:55:44 +0000645 SemaDiagnosticBuilder diagnoseExplicitConv(
646 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000647 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
648 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000649
Craig Toppere14c0f82014-03-12 04:55:44 +0000650 SemaDiagnosticBuilder noteExplicitConv(
651 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000652 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
653 << ConvTy->isEnumeralType() << ConvTy;
654 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000655
Craig Toppere14c0f82014-03-12 04:55:44 +0000656 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
657 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000658 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
659 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000660
Craig Toppere14c0f82014-03-12 04:55:44 +0000661 SemaDiagnosticBuilder noteAmbiguous(
662 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000663 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
664 << ConvTy->isEnumeralType() << ConvTy;
665 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000666
Craig Toppere14c0f82014-03-12 04:55:44 +0000667 SemaDiagnosticBuilder diagnoseConversion(
668 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000669 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000670 }
671 } SwitchDiagnoser(Cond);
672
Richard Smith03a4aa32016-06-23 19:02:52 +0000673 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000674 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000675 if (CondResult.isInvalid())
676 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677
Richard Smithef6c43d2018-07-26 18:41:30 +0000678 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
679 // failed and produced a diagnostic.
680 Cond = CondResult.get();
681 if (!Cond->isTypeDependent() &&
682 !Cond->getType()->isIntegralOrEnumerationType())
683 return ExprError();
684
John McCall5939b162011-08-06 07:30:58 +0000685 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smithef6c43d2018-07-26 18:41:30 +0000686 return UsualUnaryConversions(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +0000687}
John McCall5939b162011-08-06 07:30:58 +0000688
Richard Smithc7a05a92016-06-29 21:17:59 +0000689StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
690 Stmt *InitStmt, ConditionResult Cond) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000691 Expr *CondExpr = Cond.get().second;
692 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
693
694 if (CondExpr && !CondExpr->isTypeDependent()) {
695 // We have already converted the expression to an integral or enumeration
696 // type, when we parsed the switch condition. If we don't have an
697 // appropriate type now, enter the switch scope but remember that it's
698 // invalid.
699 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
700 "invalid condition type");
701 if (CondExpr->isKnownToHaveBooleanValue()) {
702 // switch(bool_expr) {...} is often a programmer error, e.g.
703 // switch(n && mask) { ... } // Doh - should be "n & mask".
704 // One can always use an if statement instead of switch(bool_expr).
705 Diag(SwitchLoc, diag::warn_bool_switch_condition)
706 << CondExpr->getSourceRange();
707 }
708 }
John McCalla95172b2010-08-01 00:26:45 +0000709
Reid Kleckner87a31802018-03-12 21:43:02 +0000710 setFunctionHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711
Bruno Riccie2806f82018-10-29 16:12:37 +0000712 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
Richard Smithef6c43d2018-07-26 18:41:30 +0000713 getCurFunction()->SwitchStack.push_back(
714 FunctionScopeInfo::SwitchInfo(SS, false));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000715 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000716}
717
Gabor Greif16e02862010-10-01 22:05:14 +0000718static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000719 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000720 Val.setIsSigned(IsSigned);
721}
722
Richard Smith077d0832014-08-04 00:40:48 +0000723/// Check the specified case value is in range for the given unpromoted switch
724/// type.
725static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
726 unsigned UnpromotedWidth, bool UnpromotedSign) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000727 // In C++11 onwards, this is checked by the language rules.
728 if (S.getLangOpts().CPlusPlus11)
729 return;
730
Richard Smith077d0832014-08-04 00:40:48 +0000731 // If the case value was signed and negative and the switch expression is
732 // unsigned, don't bother to warn: this is implementation-defined behavior.
733 // FIXME: Introduce a second, default-ignored warning for this case?
734 if (UnpromotedWidth < Val.getBitWidth()) {
735 llvm::APSInt ConvVal(Val);
736 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
737 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
738 // FIXME: Use different diagnostics for overflow in conversion to promoted
739 // type versus "switch expression cannot have this value". Use proper
740 // IntRange checking rather than just looking at the unpromoted type here.
741 if (ConvVal != Val)
742 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
743 << ConvVal.toString(10);
744 }
745}
746
Alexis Hunt724f14e2014-11-28 00:53:20 +0000747typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
748
Dmitri Gribenko58683752013-12-05 22:52:07 +0000749/// Returns true if we should emit a diagnostic about this case expression not
750/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000751static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000752 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000753 const Expr *CaseExpr,
754 EnumValsTy::iterator &EI,
755 EnumValsTy::iterator &EIEnd,
756 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000757 if (!ED->isClosed())
758 return false;
759
Alexis Hunt724f14e2014-11-28 00:53:20 +0000760 if (const DeclRefExpr *DRE =
761 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000762 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000763 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000764 QualType EnumType = S.Context.getTypeDeclType(ED);
765 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
766 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000767 return false;
768 }
769 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000770
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000771 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000772 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000773
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000774 while (EI != EIEnd && EI->first < Val)
775 EI++;
776
777 if (EI != EIEnd && EI->first == Val)
778 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000779
Dmitri Gribenko58683752013-12-05 22:52:07 +0000780 return true;
781}
782
Gabor Horvath64c32412017-08-09 08:57:09 +0000783static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
784 const Expr *Case) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000785 QualType CondType = Cond->getType();
Gabor Horvath64c32412017-08-09 08:57:09 +0000786 QualType CaseType = Case->getType();
787
788 const EnumType *CondEnumType = CondType->getAs<EnumType>();
789 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
790 if (!CondEnumType || !CaseEnumType)
791 return;
792
Gabor Horvathb57e2642017-08-09 12:34:58 +0000793 // Ignore anonymous enums.
Richard Trieu285c9362017-09-09 00:25:05 +0000794 if (!CondEnumType->getDecl()->getIdentifier() &&
795 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000796 return;
Richard Trieu285c9362017-09-09 00:25:05 +0000797 if (!CaseEnumType->getDecl()->getIdentifier() &&
798 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000799 return;
800
Gabor Horvath64c32412017-08-09 08:57:09 +0000801 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
802 return;
803
Gabor Horvath0284a202017-08-09 20:56:43 +0000804 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000805 << CondType << CaseType << Cond->getSourceRange()
806 << Case->getSourceRange();
807}
808
John McCalldadc5752010-08-24 06:29:42 +0000809StmtResult
John McCallb268a282010-08-23 23:25:46 +0000810Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
811 Stmt *BodyStmt) {
812 SwitchStmt *SS = cast<SwitchStmt>(Switch);
Richard Smithef6c43d2018-07-26 18:41:30 +0000813 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
814 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
John McCallaab3e412010-08-25 08:40:02 +0000815 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000816
David Majnemer418ad3f2014-12-15 07:46:12 +0000817 getCurFunction()->SwitchStack.pop_back();
818
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000819 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000820 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000821
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000822 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000823 if (!CondExpr) return StmtError();
824
825 QualType CondType = CondExpr->getType();
826
Chris Lattnera96d4272009-10-16 16:45:22 +0000827 // C++ 6.4.2.p2:
828 // Integral promotions are performed (on the switch condition).
829 //
830 // A case value unrepresentable by the original switch condition
831 // type (before the promotion) doesn't make sense, even when it can
832 // be represented by the promoted type. Therefore we need to find
833 // the pre-promotion type of the switch condition.
Richard Smithef6c43d2018-07-26 18:41:30 +0000834 const Expr *CondExprBeforePromotion = CondExpr;
835 QualType CondTypeBeforePromotion =
836 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000837
Richard Smith077d0832014-08-04 00:40:48 +0000838 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000839 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000840 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000841 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000842 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
843 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
844
845 // Get the width and signedness that the condition might actually have, for
846 // warning purposes.
847 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
848 // type.
849 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000850 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000851 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000852 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000853
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000854 // Accumulate all of the case values in a vector so that we can sort them
855 // and detect duplicates. This vector contains the APInt for the case after
856 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000857 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000858 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000860 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000861 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
862 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000863
Craig Topperc3ec1492014-05-26 06:22:03 +0000864 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000865
Chris Lattner10cb5e52007-08-23 06:23:56 +0000866 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000867
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000868 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000869 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000870
Anders Carlsson51873c22007-07-22 07:07:56 +0000871 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000872 if (TheDefaultStmt) {
873 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000874 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000875
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000876 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000877 // we'll return a valid AST. This requires recursing down the AST and
878 // finding it, not something we are set up to do right now. For now,
879 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000880 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000881 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000882 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000884 } else {
885 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattnera65e1f32008-01-16 19:17:22 +0000887 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000888
Richard Smithef6c43d2018-07-26 18:41:30 +0000889 if (Lo->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000890 HasDependentValue = true;
891 break;
892 }
Mike Stump11289f42009-09-09 15:08:12 +0000893
Richard Smithef6c43d2018-07-26 18:41:30 +0000894 // We already verified that the expression has a constant value;
895 // get that value (prior to conversions).
896 const Expr *LoBeforePromotion = Lo;
897 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
898 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000899
Richard Smith077d0832014-08-04 00:40:48 +0000900 // Check the unconverted value is within the range of possible values of
901 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000902 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
903 CondIsSignedBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000904
Richard Smithef6c43d2018-07-26 18:41:30 +0000905 // FIXME: This duplicates the check performed for warn_not_in_enum below.
906 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
907 LoBeforePromotion);
908
Richard Smith077d0832014-08-04 00:40:48 +0000909 // Convert the value to the same width/sign as the condition.
910 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000911
Chris Lattner10cb5e52007-08-23 06:23:56 +0000912 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000913 if (CS->getRHS()) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000914 if (CS->getRHS()->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000915 HasDependentValue = true;
916 break;
917 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000918 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000919 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000920 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000921 }
922 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000923
924 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000925 // If we don't have a default statement, check whether the
926 // condition is constant.
927 llvm::APSInt ConstantCondValue;
928 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000929 if (!HasDependentValue && !TheDefaultStmt) {
Fangrui Song407659a2018-11-30 23:41:18 +0000930 Expr::EvalResult Result;
931 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
Richard Smith077d0832014-08-04 00:40:48 +0000932 Expr::SE_AllowSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +0000933 if (Result.Val.isInt())
934 ConstantCondValue = Result.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +0000935 assert(!HasConstantCond ||
936 (ConstantCondValue.getBitWidth() == CondWidth &&
937 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000938 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000939 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000940
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000941 // Sort all the scalar case values so we can easily detect duplicates.
Fangrui Song899d1392019-04-24 14:43:05 +0000942 llvm::stable_sort(CaseVals, CmpCaseVals);
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000943
944 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000945 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
946 if (ShouldCheckConstantCond &&
947 CaseVals[i].first == ConstantCondValue)
948 ShouldCheckConstantCond = false;
949
950 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000951 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000952 // First, determine if either case value has a name
953 StringRef PrevString, CurrString;
954 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
955 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
956 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
957 PrevString = DeclRef->getDecl()->getName();
958 }
959 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
960 CurrString = DeclRef->getDecl()->getName();
961 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000962 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000963 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000964
965 if (PrevString == CurrString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000966 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
967 diag::err_duplicate_case)
968 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000969 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000970 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
971 diag::err_duplicate_case_differing_expr)
972 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
973 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
974 << CaseValStr;
Douglas Gregor9841df62012-05-16 05:32:58 +0000975
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000976 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000977 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000978 // FIXME: We really want to remove the bogus case stmt from the
979 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000980 CaseListIsErroneous = true;
981 }
982 }
983 }
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000985 // Detect duplicate case ranges, which usually don't exist at all in
986 // the first place.
987 if (!CaseRanges.empty()) {
988 // Sort all the case ranges by their low value so we can easily detect
989 // overlaps between ranges.
Fangrui Song899d1392019-04-24 14:43:05 +0000990 llvm::stable_sort(CaseRanges);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 // Scan the ranges, computing the high values and removing empty ranges.
993 std::vector<llvm::APSInt> HiVals;
994 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000995 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000996 CaseStmt *CR = CaseRanges[i].second;
997 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000998
Richard Smithef6c43d2018-07-26 18:41:30 +0000999 const Expr *HiBeforePromotion = Hi;
1000 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1001 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001002
Richard Smith077d0832014-08-04 00:40:48 +00001003 // Check the unconverted value is within the range of possible values of
1004 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001005 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
Richard Smith077d0832014-08-04 00:40:48 +00001006 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1007
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001008 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001009 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001010
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001011 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001012 if (LoVal > HiVal) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001013 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001014 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001015 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001016 --i;
1017 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001018 continue;
1019 }
John McCalld3dfbd62010-05-18 03:19:21 +00001020
1021 if (ShouldCheckConstantCond &&
1022 LoVal <= ConstantCondValue &&
1023 ConstantCondValue <= HiVal)
1024 ShouldCheckConstantCond = false;
1025
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001026 HiVals.push_back(HiVal);
1027 }
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001029 // Rescan the ranges, looking for overlap with singleton values and other
1030 // ranges. Since the range list is sorted, we only need to compare case
1031 // ranges with their neighbors.
1032 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1033 llvm::APSInt &CRLo = CaseRanges[i].first;
1034 llvm::APSInt &CRHi = HiVals[i];
1035 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001036
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001037 // Check to see whether the case range overlaps with any
1038 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001039 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001040 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001041
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001042 // Find the smallest value >= the lower bound. If I is in the
1043 // case range, then we have overlap.
1044 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1045 CaseVals.end(), CRLo,
1046 CaseCompareFunctor());
1047 if (I != CaseVals.end() && I->first < CRHi) {
1048 OverlapVal = I->first; // Found overlap with scalar.
1049 OverlapStmt = I->second;
1050 }
Mike Stump11289f42009-09-09 15:08:12 +00001051
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001052 // Find the smallest value bigger than the upper bound.
1053 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1054 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1055 OverlapVal = (I-1)->first; // Found overlap with scalar.
1056 OverlapStmt = (I-1)->second;
1057 }
Mike Stump11289f42009-09-09 15:08:12 +00001058
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001059 // Check to see if this case stmt overlaps with the subsequent
1060 // case range.
1061 if (i && CRLo <= HiVals[i-1]) {
1062 OverlapVal = HiVals[i-1]; // Found overlap with range.
1063 OverlapStmt = CaseRanges[i-1].second;
1064 }
Mike Stump11289f42009-09-09 15:08:12 +00001065
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001066 if (OverlapStmt) {
1067 // If we have a duplicate, report it.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001068 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1069 << OverlapVal.toString(10);
1070 Diag(OverlapStmt->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001071 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001072 // FIXME: We really want to remove the bogus case stmt from the
1073 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001074 CaseListIsErroneous = true;
1075 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001076 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001077 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001078
John McCalld3dfbd62010-05-18 03:19:21 +00001079 // Complain if we have a constant condition and we didn't find a match.
Richard Smithef6c43d2018-07-26 18:41:30 +00001080 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1081 ShouldCheckConstantCond) {
John McCalld3dfbd62010-05-18 03:19:21 +00001082 // TODO: it would be nice if we printed enums as enums, chars as
1083 // chars, etc.
1084 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1085 << ConstantCondValue.toString(10)
1086 << CondExpr->getSourceRange();
1087 }
1088
1089 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001090 // values. We only issue a warning if there is not 'default:', but
1091 // we still do the analysis to preserve this information in the AST
1092 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001093 //
Chris Lattner51679082010-09-16 17:09:42 +00001094 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001095
Douglas Gregorbd6839732010-02-08 22:24:16 +00001096 // If switch has default case, then ignore it.
Richard Smithef6c43d2018-07-26 18:41:30 +00001097 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1098 ET && ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001099 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001100 EnumValsTy EnumVals;
1101
John McCalld3dfbd62010-05-18 03:19:21 +00001102 // Gather all enum values, set their type and sort them,
1103 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001104 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001105 llvm::APSInt Val = EDI->getInitVal();
1106 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001107 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001108 }
Fangrui Song899d1392019-04-24 14:43:05 +00001109 llvm::stable_sort(EnumVals, CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001110 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001111 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001112
1113 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001114 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001115 CI != CaseVals.end(); CI++) {
1116 Expr *CaseExpr = CI->second->getLHS();
1117 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1118 CI->first))
1119 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1120 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001121 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001122
David Blaikiee476f972012-01-22 02:31:55 +00001123 // See which of case ranges aren't in enum
1124 EI = EnumVals.begin();
1125 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001126 RI != CaseRanges.end(); RI++) {
1127 Expr *CaseExpr = RI->second->getLHS();
1128 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1129 RI->first))
1130 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1131 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001132
Chad Rosier02a84392012-08-10 17:56:09 +00001133 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001134 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1135 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001136
1137 CaseExpr = RI->second->getRHS();
1138 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1139 Hi))
1140 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1141 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
Ted Kremenekc42f3452010-09-09 00:05:53 +00001144 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001145 auto CI = CaseVals.begin();
1146 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001147 bool hasCasesNotInSwitch = false;
1148
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001149 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001150
Erik Pilkington3e4e3b12018-09-05 19:13:27 +00001151 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1152 // Don't warn about omitted unavailable EnumConstantDecls.
1153 switch (EI->second->getAvailability()) {
1154 case AR_Deprecated:
1155 // Omitting a deprecated constant is ok; it should never materialize.
1156 case AR_Unavailable:
1157 continue;
1158
1159 case AR_NotYetIntroduced:
1160 // Partially available enum constants should be present. Note that we
1161 // suppress -Wunguarded-availability diagnostics for such uses.
1162 case AR_Available:
1163 break;
1164 }
1165
David Blaikiea558ee82019-05-02 16:30:49 +00001166 if (EI->second->hasAttr<UnusedAttr>())
1167 continue;
1168
Chris Lattner51679082010-09-16 17:09:42 +00001169 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001170 while (CI != CaseVals.end() && CI->first < EI->first)
1171 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172
Douglas Gregorbd6839732010-02-08 22:24:16 +00001173 if (CI != CaseVals.end() && CI->first == EI->first)
1174 continue;
1175
Ted Kremenekc42f3452010-09-09 00:05:53 +00001176 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001177 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001178 llvm::APSInt Hi =
1179 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001180 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001181 if (EI->first <= Hi)
1182 break;
1183 }
1184
Ted Kremenekc42f3452010-09-09 00:05:53 +00001185 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001186 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001187 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001188 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001190
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001191 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001192 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001193
Chris Lattner51679082010-09-16 17:09:42 +00001194 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001195 if (!UnhandledNames.empty()) {
1196 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1197 TheDefaultStmt ? diag::warn_def_missing_case
1198 : diag::warn_missing_case)
1199 << (int)UnhandledNames.size();
1200
1201 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1202 I != E; ++I)
1203 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001204 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001205
1206 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001207 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001208 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001209 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001210
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001211 if (BodyStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001212 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001213 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001214
Mike Stump87c57ac2009-05-16 07:39:55 +00001215 // FIXME: If the case list was broken is some way, we don't have a good system
1216 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001217 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001218 return StmtError();
1219
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001220 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001221}
1222
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001223void
1224Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1225 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001226 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001227 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001228
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001229 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001230 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001231 SrcType->isIntegerType()) {
1232 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1233 SrcExpr->isIntegerConstantExpr(Context)) {
1234 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001235 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001236 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1237
1238 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001239 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001240 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001241
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001242 if (!ED->isClosed())
1243 return;
1244
Alexis Hunt724f14e2014-11-28 00:53:20 +00001245 if (ED->hasAttr<FlagEnumAttr>()) {
1246 if (!IsValueInFlagEnum(ED, RhsVal, true))
1247 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001248 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001249 } else {
1250 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1251 EnumValsTy;
1252 EnumValsTy EnumVals;
1253
1254 // Gather all enum values, set their type and sort them,
1255 // allowing easier comparison with rhs constant.
1256 for (auto *EDI : ED->enumerators()) {
1257 llvm::APSInt Val = EDI->getInitVal();
1258 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1259 EnumVals.push_back(std::make_pair(Val, EDI));
1260 }
1261 if (EnumVals.empty())
1262 return;
Fangrui Song899d1392019-04-24 14:43:05 +00001263 llvm::stable_sort(EnumVals, CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001264 EnumValsTy::iterator EIend =
1265 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1266
1267 // See which values aren't in the enum.
1268 EnumValsTy::const_iterator EI = EnumVals.begin();
1269 while (EI != EIend && EI->first < RhsVal)
1270 EI++;
1271 if (EI == EIend || EI->first != RhsVal) {
1272 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1273 << DstType.getUnqualifiedType();
1274 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001275 }
1276 }
1277 }
1278}
1279
Richard Smith03a4aa32016-06-23 19:02:52 +00001280StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1281 Stmt *Body) {
1282 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001283 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284
Richard Smith03a4aa32016-06-23 19:02:52 +00001285 auto CondVal = Cond.get();
1286 CheckBreakContinueBinding(CondVal.second);
1287
1288 if (CondVal.second &&
1289 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1290 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001291
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001292 if (isa<NullStmt>(Body))
1293 getCurCompoundScope().setHasEmptyLoopBodies();
1294
Bruno Riccibacf7512018-10-30 13:42:41 +00001295 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1296 WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001297}
1298
John McCalldadc5752010-08-24 06:29:42 +00001299StmtResult
John McCallb268a282010-08-23 23:25:46 +00001300Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001301 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001302 Expr *Cond, SourceLocation CondRParen) {
1303 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001304
Serge Pavlov09f99242014-01-23 15:05:00 +00001305 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001306 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001307 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001308 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001309 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001310
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001311 CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
John McCallb268a282010-08-23 23:25:46 +00001312 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001313 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001314 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315
Richard Trieuf3713802018-10-25 01:08:00 +00001316 // Only call the CommaVisitor for C89 due to differences in scope flags.
1317 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1318 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1319 CommaVisitor(*this).Visit(Cond);
1320
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001321 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001322}
1323
Richard Trieu451a5db2012-04-30 18:01:30 +00001324namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001325 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1326 using DeclSetVector =
1327 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1328 llvm::SmallPtrSet<VarDecl *, 8>>;
1329
Richard Trieu451a5db2012-04-30 18:01:30 +00001330 // This visitor will traverse a conditional statement and store all
1331 // the evaluated decls into a vector. Simple is set to true if none
1332 // of the excluded constructs are used.
1333 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001334 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001335 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001336 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001337 public:
1338 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001339
Richard Trieu5fb874a2017-06-02 04:24:46 +00001340 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001341 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001342 Inherited(S.Context),
1343 Decls(Decls),
1344 Ranges(Ranges),
1345 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001348
Richard Trieu9d228802013-05-31 22:46:45 +00001349 // Replaces the method in EvaluatedExprVisitor.
1350 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001351 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001352 }
1353
1354 // Any Stmt not whitelisted will cause the condition to be marked complex.
1355 void VisitStmt(Stmt *S) {
1356 Simple = false;
1357 }
1358
1359 void VisitBinaryOperator(BinaryOperator *E) {
1360 Visit(E->getLHS());
1361 Visit(E->getRHS());
1362 }
1363
1364 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001365 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001366 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001367
Richard Trieu9d228802013-05-31 22:46:45 +00001368 void VisitUnaryOperator(UnaryOperator *E) {
1369 // Skip checking conditionals with derefernces.
1370 if (E->getOpcode() == UO_Deref)
1371 Simple = false;
1372 else
1373 Visit(E->getSubExpr());
1374 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001375
Richard Trieu9d228802013-05-31 22:46:45 +00001376 void VisitConditionalOperator(ConditionalOperator *E) {
1377 Visit(E->getCond());
1378 Visit(E->getTrueExpr());
1379 Visit(E->getFalseExpr());
1380 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001381
Richard Trieu9d228802013-05-31 22:46:45 +00001382 void VisitParenExpr(ParenExpr *E) {
1383 Visit(E->getSubExpr());
1384 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001385
Richard Trieu9d228802013-05-31 22:46:45 +00001386 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1387 Visit(E->getOpaqueValue()->getSourceExpr());
1388 Visit(E->getFalseExpr());
1389 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001390
Richard Trieu9d228802013-05-31 22:46:45 +00001391 void VisitIntegerLiteral(IntegerLiteral *E) { }
1392 void VisitFloatingLiteral(FloatingLiteral *E) { }
1393 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1394 void VisitCharacterLiteral(CharacterLiteral *E) { }
1395 void VisitGNUNullExpr(GNUNullExpr *E) { }
1396 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001397
Richard Trieu9d228802013-05-31 22:46:45 +00001398 void VisitDeclRefExpr(DeclRefExpr *E) {
1399 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
Richard Trieu6b13e892018-10-20 02:15:58 +00001400 if (!VD) {
1401 // Don't allow unhandled Decl types.
1402 Simple = false;
1403 return;
1404 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001405
Richard Trieu9d228802013-05-31 22:46:45 +00001406 Ranges.push_back(E->getSourceRange());
1407
1408 Decls.insert(VD);
1409 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001410
1411 }; // end class DeclExtractor
1412
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001413 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001414 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001415 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001416 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001417 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001418
Richard Trieu9d228802013-05-31 22:46:45 +00001419 public:
1420 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001421
Richard Trieu5fb874a2017-06-02 04:24:46 +00001422 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001423 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1424 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001425
Richard Trieu9d228802013-05-31 22:46:45 +00001426 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001427 }
1428
Richard Trieu9d228802013-05-31 22:46:45 +00001429 void VisitReturnStmt(ReturnStmt *S) {
1430 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001431 }
1432
Richard Trieu9d228802013-05-31 22:46:45 +00001433 void VisitBreakStmt(BreakStmt *S) {
1434 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001435 }
1436
Richard Trieu9d228802013-05-31 22:46:45 +00001437 void VisitGotoStmt(GotoStmt *S) {
1438 FoundDecl = true;
1439 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001440
Richard Trieu9d228802013-05-31 22:46:45 +00001441 void VisitCastExpr(CastExpr *E) {
1442 if (E->getCastKind() == CK_LValueToRValue)
1443 CheckLValueToRValueCast(E->getSubExpr());
1444 else
1445 Visit(E->getSubExpr());
1446 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001447
Richard Trieu9d228802013-05-31 22:46:45 +00001448 void CheckLValueToRValueCast(Expr *E) {
1449 E = E->IgnoreParenImpCasts();
1450
1451 if (isa<DeclRefExpr>(E)) {
1452 return;
1453 }
1454
1455 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1456 Visit(CO->getCond());
1457 CheckLValueToRValueCast(CO->getTrueExpr());
1458 CheckLValueToRValueCast(CO->getFalseExpr());
1459 return;
1460 }
1461
1462 if (BinaryConditionalOperator *BCO =
1463 dyn_cast<BinaryConditionalOperator>(E)) {
1464 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1465 CheckLValueToRValueCast(BCO->getFalseExpr());
1466 return;
1467 }
1468
1469 Visit(E);
1470 }
1471
1472 void VisitDeclRefExpr(DeclRefExpr *E) {
1473 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1474 if (Decls.count(VD))
1475 FoundDecl = true;
1476 }
1477
Steven Wu92910f62016-03-10 02:02:48 +00001478 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1479 // Only need to visit the semantics for POE.
1480 // SyntaticForm doesn't really use the Decal.
1481 for (auto *S : POE->semantics()) {
1482 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1483 // Look past the OVE into the expression it binds.
1484 Visit(OVE->getSourceExpr());
1485 else
1486 Visit(S);
1487 }
1488 }
1489
Richard Trieu9d228802013-05-31 22:46:45 +00001490 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001491
1492 }; // end class DeclMatcher
1493
1494 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1495 Expr *Third, Stmt *Body) {
1496 // Condition is empty
1497 if (!Second) return;
1498
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001499 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001500 Second->getBeginLoc()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001501 return;
1502
1503 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001504 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001505 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001506 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001507 DE.Visit(Second);
1508
1509 // Don't analyze complex conditionals.
1510 if (!DE.isSimple()) return;
1511
1512 // No decls found.
1513 if (Decls.size() == 0) return;
1514
Richard Trieu0030f1d2012-05-04 03:01:54 +00001515 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001516 for (auto *VD : Decls)
1517 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1518 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001519
1520 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1521 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1522 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1523 return;
1524
1525 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001526 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001527 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001528 } else {
1529 PDiag << (unsigned)Decls.size();
1530 for (auto *VD : Decls)
1531 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001532 }
1533
Richard Trieu5fb874a2017-06-02 04:24:46 +00001534 for (auto Range : Ranges)
1535 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001536
1537 S.Diag(Ranges.begin()->getBegin(), PDiag);
1538 }
1539
Richard Trieu4e7c9622013-08-06 21:31:54 +00001540 // If Statement is an incemement or decrement, return true and sets the
1541 // variables Increment and DRE.
1542 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1543 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001544 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1545 if (!Cleanups->cleanupsHaveSideEffects())
1546 Statement = Cleanups->getSubExpr();
1547
Richard Trieu4e7c9622013-08-06 21:31:54 +00001548 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1549 switch (UO->getOpcode()) {
1550 default: return false;
1551 case UO_PostInc:
1552 case UO_PreInc:
1553 Increment = true;
1554 break;
1555 case UO_PostDec:
1556 case UO_PreDec:
1557 Increment = false;
1558 break;
1559 }
1560 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1561 return DRE;
1562 }
1563
1564 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1565 FunctionDecl *FD = Call->getDirectCallee();
1566 if (!FD || !FD->isOverloadedOperator()) return false;
1567 switch (FD->getOverloadedOperator()) {
1568 default: return false;
1569 case OO_PlusPlus:
1570 Increment = true;
1571 break;
1572 case OO_MinusMinus:
1573 Increment = false;
1574 break;
1575 }
1576 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1577 return DRE;
1578 }
1579
1580 return false;
1581 }
1582
Serge Pavlov09f99242014-01-23 15:05:00 +00001583 // A visitor to determine if a continue or break statement is a
1584 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001585 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001586 SourceLocation BreakLoc;
1587 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001588 bool InSwitch = false;
1589
Richard Trieu4e7c9622013-08-06 21:31:54 +00001590 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001591 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001592 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001593 Visit(Body);
1594 }
1595
Eli Friedmane91b2e62017-07-04 00:52:24 +00001596 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001597
Eli Friedmane91b2e62017-07-04 00:52:24 +00001598 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001599 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001600 }
1601
Eli Friedmane91b2e62017-07-04 00:52:24 +00001602 void VisitBreakStmt(const BreakStmt* E) {
1603 if (!InSwitch)
1604 BreakLoc = E->getBreakLoc();
1605 }
1606
1607 void VisitSwitchStmt(const SwitchStmt* S) {
1608 if (const Stmt *Init = S->getInit())
1609 Visit(Init);
1610 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1611 Visit(CondVar);
1612 if (const Stmt *Cond = S->getCond())
1613 Visit(Cond);
1614
1615 // Don't return break statements from the body of a switch.
1616 InSwitch = true;
1617 if (const Stmt *Body = S->getBody())
1618 Visit(Body);
1619 InSwitch = false;
1620 }
1621
1622 void VisitForStmt(const ForStmt *S) {
1623 // Only visit the init statement of a for loop; the body
1624 // has a different break/continue scope.
1625 if (const Stmt *Init = S->getInit())
1626 Visit(Init);
1627 }
1628
1629 void VisitWhileStmt(const WhileStmt *) {
1630 // Do nothing; the children of a while loop have a different
1631 // break/continue scope.
1632 }
1633
1634 void VisitDoStmt(const DoStmt *) {
1635 // Do nothing; the children of a while loop have a different
1636 // break/continue scope.
1637 }
1638
1639 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1640 // Only visit the initialization of a for loop; the body
1641 // has a different break/continue scope.
Richard Smith8baa5002018-09-28 18:44:09 +00001642 if (const Stmt *Init = S->getInit())
1643 Visit(Init);
Eli Friedmane91b2e62017-07-04 00:52:24 +00001644 if (const Stmt *Range = S->getRangeStmt())
1645 Visit(Range);
1646 if (const Stmt *Begin = S->getBeginStmt())
1647 Visit(Begin);
1648 if (const Stmt *End = S->getEndStmt())
1649 Visit(End);
1650 }
1651
1652 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1653 // Only visit the initialization of a for loop; the body
1654 // has a different break/continue scope.
1655 if (const Stmt *Element = S->getElement())
1656 Visit(Element);
1657 if (const Stmt *Collection = S->getCollection())
1658 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001659 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001660
Serge Pavlov09f99242014-01-23 15:05:00 +00001661 bool ContinueFound() { return ContinueLoc.isValid(); }
1662 bool BreakFound() { return BreakLoc.isValid(); }
1663 SourceLocation GetContinueLoc() { return ContinueLoc; }
1664 SourceLocation GetBreakLoc() { return BreakLoc; }
1665
1666 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001667
1668 // Emit a warning when a loop increment/decrement appears twice per loop
1669 // iteration. The conditions which trigger this warning are:
1670 // 1) The last statement in the loop body and the third expression in the
1671 // for loop are both increment or both decrement of the same variable
1672 // 2) No continue statements in the loop body.
1673 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1674 // Return when there is nothing to check.
1675 if (!Body || !Third) return;
1676
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001677 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001678 Third->getBeginLoc()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001679 return;
1680
1681 // Get the last statement from the loop body.
1682 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1683 if (!CS || CS->body_empty()) return;
1684 Stmt *LastStmt = CS->body_back();
1685 if (!LastStmt) return;
1686
1687 bool LoopIncrement, LastIncrement;
1688 DeclRefExpr *LoopDRE, *LastDRE;
1689
1690 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1691 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1692
1693 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001694 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001695 if (LoopIncrement != LastIncrement ||
1696 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1697
Serge Pavlov09f99242014-01-23 15:05:00 +00001698 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001699
1700 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1701 << LastDRE->getDecl() << LastIncrement;
1702 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1703 << LoopIncrement;
1704 }
1705
Richard Trieu451a5db2012-04-30 18:01:30 +00001706} // end namespace
1707
Serge Pavlov09f99242014-01-23 15:05:00 +00001708
1709void Sema::CheckBreakContinueBinding(Expr *E) {
1710 if (!E || getLangOpts().CPlusPlus)
1711 return;
1712 BreakContinueFinder BCFinder(*this, E);
1713 Scope *BreakParent = CurScope->getBreakParent();
1714 if (BCFinder.BreakFound() && BreakParent) {
1715 if (BreakParent->getFlags() & Scope::SwitchScope) {
1716 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1717 } else {
1718 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1719 << "break";
1720 }
1721 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1722 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1723 << "continue";
1724 }
1725}
1726
Richard Smith03a4aa32016-06-23 19:02:52 +00001727StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1728 Stmt *First, ConditionResult Second,
1729 FullExprArg third, SourceLocation RParenLoc,
1730 Stmt *Body) {
1731 if (Second.isInvalid())
1732 return StmtError();
1733
David Blaikiebbafb8a2012-03-11 07:00:24 +00001734 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001735 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001736 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1737 // declare identifiers for objects having storage class 'auto' or
1738 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001739 for (auto *DI : DS->decls()) {
1740 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001741 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001742 VD = nullptr;
1743 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001744 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1745 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001746 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001747 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001748 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001749 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001750
Richard Smith03a4aa32016-06-23 19:02:52 +00001751 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001752 CheckBreakContinueBinding(third.get());
1753
Richard Smith03a4aa32016-06-23 19:02:52 +00001754 if (!Second.get().first)
1755 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1756 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001757 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001758
Richard Smith03a4aa32016-06-23 19:02:52 +00001759 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001760 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001761 Second.get().second->getExprLoc()))
1762 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001763
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001764 Expr *Third = third.release().getAs<Expr>();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001765 if (isa<NullStmt>(Body))
1766 getCurCompoundScope().setHasEmptyLoopBodies();
1767
Richard Smith03a4aa32016-06-23 19:02:52 +00001768 return new (Context)
1769 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1770 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001771}
1772
John McCall34376a62010-12-04 03:47:34 +00001773/// In an Objective C collection iteration statement:
1774/// for (x in y)
1775/// x can be an arbitrary l-value expression. Bind it up as a
1776/// full-expression.
1777StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001778 // Reduce placeholder expressions here. Note that this rejects the
1779 // use of pseudo-object l-values in this position.
1780 ExprResult result = CheckPlaceholderExpr(E);
1781 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001782 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001783
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001784 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00001785 if (FullExpr.isInvalid())
1786 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001787 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001788}
1789
John McCall53848232011-07-27 01:07:15 +00001790ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001791Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1792 if (!collection)
1793 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001794
Kaelyn Takata15867822014-11-21 18:48:04 +00001795 ExprResult result = CorrectDelayedTyposInExpr(collection);
1796 if (!result.isUsable())
1797 return ExprError();
1798 collection = result.get();
1799
John McCall53848232011-07-27 01:07:15 +00001800 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001801 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001802
1803 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001804 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001805 if (result.isInvalid())
1806 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001807 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001808
1809 // The operand needs to have object-pointer type.
1810 // TODO: should we do a contextual conversion?
1811 const ObjCObjectPointerType *pointerType =
1812 collection->getType()->getAs<ObjCObjectPointerType>();
1813 if (!pointerType)
1814 return Diag(forLoc, diag::err_collection_expr_type)
1815 << collection->getType() << collection->getSourceRange();
1816
1817 // Check that the operand provides
1818 // - countByEnumeratingWithState:objects:count:
1819 const ObjCObjectType *objectType = pointerType->getObjectType();
1820 ObjCInterfaceDecl *iface = objectType->getInterface();
1821
1822 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001823 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001824 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001825 (getLangOpts().ObjCAutoRefCount
1826 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1827 diag::err_arc_collection_forward, collection)
1828 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001829 // Otherwise, if we have any useful type information, check that
1830 // the type declares the appropriate method.
1831 } else if (iface || !objectType->qual_empty()) {
1832 IdentifierInfo *selectorIdents[] = {
1833 &Context.Idents.get("countByEnumeratingWithState"),
1834 &Context.Idents.get("objects"),
1835 &Context.Idents.get("count")
1836 };
1837 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1838
Craig Topperc3ec1492014-05-26 06:22:03 +00001839 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001840
1841 // If there's an interface, look in both the public and private APIs.
1842 if (iface) {
1843 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001844 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001845 }
1846
1847 // Also check protocol qualifiers.
1848 if (!method)
1849 method = LookupMethodInQualifiedType(selector, pointerType,
1850 /*instance*/ true);
1851
1852 // If we didn't find it anywhere, give up.
1853 if (!method) {
1854 Diag(forLoc, diag::warn_collection_expr_type)
1855 << collection->getType() << selector << collection->getSourceRange();
1856 }
1857
1858 // TODO: check for an incompatible signature?
1859 }
1860
1861 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001862 return collection;
John McCall53848232011-07-27 01:07:15 +00001863}
1864
John McCalldadc5752010-08-24 06:29:42 +00001865StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001866Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001867 Stmt *First, Expr *collection,
1868 SourceLocation RParenLoc) {
Reid Kleckner87a31802018-03-12 21:43:02 +00001869 setFunctionHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001870
1871 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001872 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001873
Fariborz Jahanian93977672008-01-10 20:33:58 +00001874 if (First) {
1875 QualType FirstType;
1876 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001877 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001878 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1879 diag::err_toomany_element_decls));
1880
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001881 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1882 if (!D || D->isInvalidDecl())
1883 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001884
John McCall31168b02011-06-15 23:02:42 +00001885 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001886 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1887 // declare identifiers for objects having storage class 'auto' or
1888 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001889 if (!D->hasLocalStorage())
1890 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001891 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001892
1893 // If the type contained 'auto', deduce the 'auto' to 'id'.
1894 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001895 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1896 VK_RValue);
1897 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001898 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1899 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001900 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001901 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001902 D->setInvalidDecl();
1903 return StmtError();
1904 }
1905
Richard Smith061f1e22013-04-30 21:23:01 +00001906 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001907
Richard Smith51ec0cf2017-02-21 01:17:38 +00001908 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001909 SourceLocation Loc =
1910 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001911 Diag(Loc, diag::warn_auto_var_is_id)
1912 << D->getDeclName();
1913 }
1914 }
1915
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001916 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001917 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001918 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001919 return StmtError(
1920 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1921 << First->getSourceRange());
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001922
Mike Stump11289f42009-09-09 15:08:12 +00001923 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001924 if (FirstType.isConstQualified())
1925 Diag(ForLoc, diag::err_selector_element_const_type)
1926 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001927 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001928 if (!FirstType->isDependentType() &&
1929 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001930 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001931 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1932 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001933 }
Chad Rosier02a84392012-08-10 17:56:09 +00001934
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001935 if (CollectionExprResult.isInvalid())
1936 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001937
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001938 CollectionExprResult =
1939 ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00001940 if (CollectionExprResult.isInvalid())
1941 return StmtError();
1942
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001943 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1944 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001945}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001946
Richard Smith02e85f32011-04-14 22:09:26 +00001947/// Finish building a variable declaration for a for-range statement.
1948/// \return true if an error occurs.
1949static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001950 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001951 if (Decl->getType()->isUndeducedType()) {
1952 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1953 if (!Res.isUsable()) {
1954 Decl->setInvalidDecl();
1955 return true;
1956 }
1957 Init = Res.get();
1958 }
1959
Richard Smith02e85f32011-04-14 22:09:26 +00001960 // Deduce the type for the iterator variable now rather than leaving it to
1961 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001962 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001963 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001964 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001965 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001966 SemaRef.Diag(Loc, DiagID) << Init->getType();
1967 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001968 Decl->setInvalidDecl();
1969 return true;
1970 }
Richard Smith061f1e22013-04-30 21:23:01 +00001971 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001972
John McCall31168b02011-06-15 23:02:42 +00001973 // In ARC, infer lifetime.
1974 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1975 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001976 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001977 SemaRef.inferObjCARCLifetime(Decl))
1978 Decl->setInvalidDecl();
1979
Richard Smith3beb7c62017-01-12 02:27:38 +00001980 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001981 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001982 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001983 return false;
1984}
1985
Sam Panzer0f384432012-08-21 00:52:01 +00001986namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001987// An enum to represent whether something is dealing with a call to begin()
1988// or a call to end() in a range-based for loop.
1989enum BeginEndFunction {
1990 BEF_begin,
1991 BEF_end
1992};
Sam Panzer0f384432012-08-21 00:52:01 +00001993
Richard Smith02e85f32011-04-14 22:09:26 +00001994/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001995/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001996/// nor from the diagnostics produced when analysing the implicit expressions
1997/// required in a for-range statement.
1998void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001999 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00002000 CallExpr *CE = dyn_cast<CallExpr>(E);
2001 if (!CE)
2002 return;
2003 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2004 if (!D)
2005 return;
2006 SourceLocation Loc = D->getLocation();
2007
2008 std::string Description;
2009 bool IsTemplate = false;
2010 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2011 Description = SemaRef.getTemplateArgumentBindingsText(
2012 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2013 IsTemplate = true;
2014 }
2015
2016 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2017 << BEF << IsTemplate << Description << E->getType();
2018}
2019
Sam Panzer0f384432012-08-21 00:52:01 +00002020/// Build a variable declaration for a for-range statement.
2021VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
Matt Davisb8402ef2018-02-14 21:22:11 +00002022 QualType Type, StringRef Name) {
Sam Panzer0f384432012-08-21 00:52:01 +00002023 DeclContext *DC = SemaRef.CurContext;
2024 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2025 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2026 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002027 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00002028 Decl->setImplicit();
2029 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00002030}
2031
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002032}
Richard Smith02e85f32011-04-14 22:09:26 +00002033
Fariborz Jahanian00213472012-07-06 19:04:04 +00002034static bool ObjCEnumerationCollection(Expr *Collection) {
2035 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00002036 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00002037}
2038
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002039/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002040///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002041/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00002042/// A range-based for statement is equivalent to
2043///
2044/// {
2045/// auto && __range = range-init;
2046/// for ( auto __begin = begin-expr,
2047/// __end = end-expr;
2048/// __begin != __end;
2049/// ++__begin ) {
2050/// for-range-declaration = *__begin;
2051/// statement
2052/// }
2053/// }
2054///
2055/// The body of the loop is not available yet, since it cannot be analysed until
2056/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00002057StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002058 SourceLocation CoawaitLoc, Stmt *InitStmt,
2059 Stmt *First, SourceLocation ColonLoc,
2060 Expr *Range, SourceLocation RParenLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +00002061 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00002062 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00002063 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002064
Richard Smith8baa5002018-09-28 18:44:09 +00002065 if (Range && ObjCEnumerationCollection(Range)) {
2066 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2067 if (InitStmt)
2068 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2069 << InitStmt->getSourceRange();
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002070 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith8baa5002018-09-28 18:44:09 +00002071 }
Richard Smith02e85f32011-04-14 22:09:26 +00002072
2073 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2074 assert(DS && "first part of for range not a decl stmt");
2075
2076 if (!DS->isSingleDecl()) {
Stephen Kellya6e43582018-08-09 21:05:56 +00002077 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
Richard Smith02e85f32011-04-14 22:09:26 +00002078 return StmtError();
2079 }
Richard Smith02e85f32011-04-14 22:09:26 +00002080
Richard Smith3249fed2013-08-21 01:40:36 +00002081 Decl *LoopVar = DS->getSingleDecl();
2082 if (LoopVar->isInvalidDecl() || !Range ||
2083 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2084 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002085 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002086 }
Richard Smith02e85f32011-04-14 22:09:26 +00002087
Eric Fiselierb936a392017-06-14 03:24:55 +00002088 // Build the coroutine state immediately and not later during template
2089 // instantiation
2090 if (!CoawaitLoc.isInvalid()) {
2091 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2092 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002093 }
2094
Richard Smith02e85f32011-04-14 22:09:26 +00002095 // Build auto && __range = range-init
Matt Davisb8402ef2018-02-14 21:22:11 +00002096 // Divide by 2, since the variables are in the inner scope (loop body).
2097 const auto DepthStr = std::to_string(S->getDepth() / 2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002098 SourceLocation RangeLoc = Range->getBeginLoc();
Richard Smith02e85f32011-04-14 22:09:26 +00002099 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2100 Context.getAutoRRefDeductType(),
Matt Davisb8402ef2018-02-14 21:22:11 +00002101 std::string("__range") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002102 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002103 diag::err_for_range_deduction_failure)) {
2104 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002105 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002106 }
Richard Smith02e85f32011-04-14 22:09:26 +00002107
2108 // Claim the type doesn't contain auto: we've already done the checking.
2109 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002110 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002111 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002112 if (RangeDecl.isInvalid()) {
2113 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002114 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002115 }
Richard Smith02e85f32011-04-14 22:09:26 +00002116
Richard Smith8baa5002018-09-28 18:44:09 +00002117 return BuildCXXForRangeStmt(
2118 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2119 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2120 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002121}
2122
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002123/// Create the initialization, compare, and increment steps for
Sam Panzer0f384432012-08-21 00:52:01 +00002124/// the range-based for loop expression.
2125/// This function does not handle array-based for loops,
2126/// which are created in Sema::BuildCXXForRangeStmt.
2127///
2128/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2129/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2130/// CandidateSet and BEF are set and some non-success value is returned on
2131/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002132static Sema::ForRangeStatus
2133BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2134 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2135 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2136 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2137 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002138 DeclarationNameInfo BeginNameInfo(
2139 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2140 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2141 ColonLoc);
2142
2143 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2144 Sema::LookupMemberName);
2145 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2146
Richard Smith236ffde2018-09-24 23:17:44 +00002147 auto BuildBegin = [&] {
2148 *BEF = BEF_begin;
2149 Sema::ForRangeStatus RangeStatus =
2150 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2151 BeginMemberLookup, CandidateSet,
2152 BeginRange, BeginExpr);
2153
2154 if (RangeStatus != Sema::FRS_Success) {
2155 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2156 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2157 << ColonLoc << BEF_begin << BeginRange->getType();
2158 return RangeStatus;
2159 }
2160 if (!CoawaitLoc.isInvalid()) {
2161 // FIXME: getCurScope() should not be used during template instantiation.
2162 // We should pick up the set of unqualified lookup results for operator
2163 // co_await during the initial parse.
2164 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2165 BeginExpr->get());
2166 if (BeginExpr->isInvalid())
2167 return Sema::FRS_DiagnosticIssued;
2168 }
2169 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2170 diag::err_for_range_iter_deduction_failure)) {
2171 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2172 return Sema::FRS_DiagnosticIssued;
2173 }
2174 return Sema::FRS_Success;
2175 };
2176
2177 auto BuildEnd = [&] {
2178 *BEF = BEF_end;
2179 Sema::ForRangeStatus RangeStatus =
2180 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2181 EndMemberLookup, CandidateSet,
2182 EndRange, EndExpr);
2183 if (RangeStatus != Sema::FRS_Success) {
2184 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2185 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2186 << ColonLoc << BEF_end << EndRange->getType();
2187 return RangeStatus;
2188 }
2189 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2190 diag::err_for_range_iter_deduction_failure)) {
2191 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2192 return Sema::FRS_DiagnosticIssued;
2193 }
2194 return Sema::FRS_Success;
2195 };
2196
Sam Panzer0f384432012-08-21 00:52:01 +00002197 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2198 // - if _RangeT is a class type, the unqualified-ids begin and end are
2199 // looked up in the scope of class _RangeT as if by class member access
2200 // lookup (3.4.5), and if either (or both) finds at least one
2201 // declaration, begin-expr and end-expr are __range.begin() and
2202 // __range.end(), respectively;
2203 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002204 if (BeginMemberLookup.isAmbiguous())
2205 return Sema::FRS_DiagnosticIssued;
2206
Sam Panzer0f384432012-08-21 00:52:01 +00002207 SemaRef.LookupQualifiedName(EndMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002208 if (EndMemberLookup.isAmbiguous())
2209 return Sema::FRS_DiagnosticIssued;
Sam Panzer0f384432012-08-21 00:52:01 +00002210
2211 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
Richard Smith236ffde2018-09-24 23:17:44 +00002212 // Look up the non-member form of the member we didn't find, first.
2213 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2214 // a 'begin' but ignored it because there was no member 'end'"
2215 // diagnostic.
2216 auto BuildNonmember = [&](
2217 BeginEndFunction BEFFound, LookupResult &Found,
2218 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2219 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2220 LookupResult OldFound = std::move(Found);
2221 Found.clear();
Sam Panzer0f384432012-08-21 00:52:01 +00002222
Richard Smith236ffde2018-09-24 23:17:44 +00002223 if (Sema::ForRangeStatus Result = BuildNotFound())
2224 return Result;
2225
2226 switch (BuildFound()) {
2227 case Sema::FRS_Success:
2228 return Sema::FRS_Success;
2229
2230 case Sema::FRS_NoViableFunction:
David Blaikie5e328052019-05-03 00:44:50 +00002231 CandidateSet->NoteCandidates(
2232 PartialDiagnosticAt(BeginRange->getBeginLoc(),
2233 SemaRef.PDiag(diag::err_for_range_invalid)
2234 << BeginRange->getType() << BEFFound),
2235 SemaRef, OCD_AllCandidates, BeginRange);
Richard Smith236ffde2018-09-24 23:17:44 +00002236 LLVM_FALLTHROUGH;
2237
2238 case Sema::FRS_DiagnosticIssued:
2239 for (NamedDecl *D : OldFound) {
2240 SemaRef.Diag(D->getLocation(),
2241 diag::note_for_range_member_begin_end_ignored)
2242 << BeginRange->getType() << BEFFound;
2243 }
2244 return Sema::FRS_DiagnosticIssued;
2245 }
2246 llvm_unreachable("unexpected ForRangeStatus");
2247 };
2248 if (BeginMemberLookup.empty())
2249 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2250 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
Sam Panzer0f384432012-08-21 00:52:01 +00002251 }
2252 } else {
2253 // - otherwise, begin-expr and end-expr are begin(__range) and
2254 // end(__range), respectively, where begin and end are looked up with
2255 // argument-dependent lookup (3.4.2). For the purposes of this name
2256 // lookup, namespace std is an associated namespace.
Sam Panzer0f384432012-08-21 00:52:01 +00002257 }
2258
Richard Smith236ffde2018-09-24 23:17:44 +00002259 if (Sema::ForRangeStatus Result = BuildBegin())
2260 return Result;
2261 return BuildEnd();
Sam Panzer0f384432012-08-21 00:52:01 +00002262}
2263
2264/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002265/// If the attempt fails, this function will return a valid, null StmtResult
2266/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002267static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2268 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002269 SourceLocation CoawaitLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002270 Stmt *InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002271 Stmt *LoopVarDecl,
2272 SourceLocation ColonLoc,
2273 Expr *Range,
2274 SourceLocation RangeLoc,
2275 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002276 // Determine whether we can rebuild the for-range statement with a
2277 // dereferenced range expression.
2278 ExprResult AdjustedRange;
2279 {
2280 Sema::SFINAETrap Trap(SemaRef);
2281
2282 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2283 if (AdjustedRange.isInvalid())
2284 return StmtResult();
2285
Richard Smith9f690bd2015-10-27 06:02:45 +00002286 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002287 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2288 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002289 if (SR.isInvalid())
2290 return StmtResult();
2291 }
2292
2293 // The attempt to dereference worked well enough that it could produce a valid
2294 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2295 // case there are any other (non-fatal) problems with it.
2296 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2297 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith8baa5002018-09-28 18:44:09 +00002298 return SemaRef.ActOnCXXForRangeStmt(
2299 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2300 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002301}
2302
Richard Smith3249fed2013-08-21 01:40:36 +00002303namespace {
2304/// RAII object to automatically invalidate a declaration if an error occurs.
2305struct InvalidateOnErrorScope {
2306 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2307 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2308 ~InvalidateOnErrorScope() {
2309 if (Enabled && Trap.hasErrorOccurred())
2310 D->setInvalidDecl();
2311 }
2312
2313 DiagnosticErrorTrap Trap;
2314 Decl *D;
2315 bool Enabled;
2316};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002317}
Richard Smith3249fed2013-08-21 01:40:36 +00002318
Richard Smitha05b3b52012-09-20 21:52:32 +00002319/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith8baa5002018-09-28 18:44:09 +00002320StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2321 SourceLocation CoawaitLoc, Stmt *InitStmt,
2322 SourceLocation ColonLoc, Stmt *RangeDecl,
2323 Stmt *Begin, Stmt *End, Expr *Cond,
2324 Expr *Inc, Stmt *LoopVarDecl,
2325 SourceLocation RParenLoc,
2326 BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002327 // FIXME: This should not be used during template instantiation. We should
2328 // pick up the set of unqualified lookup results for the != and + operators
2329 // in the initial parse.
2330 //
2331 // Testcase (accepts-invalid):
2332 // template<typename T> void f() { for (auto x : T()) {} }
2333 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2334 // bool operator!=(N::X, N::X); void operator++(N::X);
2335 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002336 Scope *S = getCurScope();
2337
2338 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2339 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2340 QualType RangeVarType = RangeVar->getType();
2341
2342 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2343 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2344
Richard Smith3249fed2013-08-21 01:40:36 +00002345 // If we hit any errors, mark the loop variable as invalid if its type
2346 // contains 'auto'.
2347 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2348 LoopVar->getType()->isUndeducedType());
2349
Richard Smith01694c32016-03-20 10:33:40 +00002350 StmtResult BeginDeclStmt = Begin;
2351 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002352 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2353
Richard Smith27d807c2013-04-30 13:56:41 +00002354 if (RangeVarType->isDependentType()) {
2355 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002356 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002357
2358 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2359 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002360 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2361 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2362 for (auto *Binding : DD->bindings())
2363 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002364 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002365 }
Richard Smith01694c32016-03-20 10:33:40 +00002366 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002367 SourceLocation RangeLoc = RangeVar->getLocation();
2368
Ted Kremenekbed648e2011-10-10 22:36:28 +00002369 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2370
2371 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2372 VK_LValue, ColonLoc);
2373 if (BeginRangeRef.isInvalid())
2374 return StmtError();
2375
2376 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2377 VK_LValue, ColonLoc);
2378 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002379 return StmtError();
2380
2381 QualType AutoType = Context.getAutoDeductType();
2382 Expr *Range = RangeVar->getInit();
2383 if (!Range)
2384 return StmtError();
2385 QualType RangeType = Range->getType();
2386
2387 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002388 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002389 return StmtError();
2390
2391 // Build auto __begin = begin-expr, __end = end-expr.
Matt Davisb8402ef2018-02-14 21:22:11 +00002392 // Divide by 2, since the variables are in the inner scope (loop body).
2393 const auto DepthStr = std::to_string(S->getDepth() / 2);
Richard Smith02e85f32011-04-14 22:09:26 +00002394 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002395 std::string("__begin") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002396 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002397 std::string("__end") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002398
2399 // Build begin-expr and end-expr and attach to __begin and __end variables.
2400 ExprResult BeginExpr, EndExpr;
2401 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2402 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2403 // __range + __bound, respectively, where __bound is the array bound. If
2404 // _RangeT is an array of unknown size or an array of incomplete type,
2405 // the program is ill-formed;
2406
2407 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002408 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002409 if (!CoawaitLoc.isInvalid()) {
2410 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2411 if (BeginExpr.isInvalid())
2412 return StmtError();
2413 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002414 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002415 diag::err_for_range_iter_deduction_failure)) {
2416 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2417 return StmtError();
2418 }
2419
2420 // Find the array bound.
2421 ExprResult BoundExpr;
2422 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002423 BoundExpr = IntegerLiteral::Create(
2424 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002425 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002426 dyn_cast<VariableArrayType>(UnqAT)) {
2427 // For a variably modified type we can't just use the expression within
2428 // the array bounds, since we don't want that to be re-evaluated here.
2429 // Rather, we need to determine what it was when the array was first
2430 // created - so we resort to using sizeof(vla)/sizeof(element).
2431 // For e.g.
Fangrui Song6907ce22018-07-30 19:24:48 +00002432 // void f(int b) {
Faisal Vali1ca2d962017-05-15 01:49:19 +00002433 // int vla[b];
2434 // b = -1; <-- This should not affect the num of iterations below
2435 // for (int &c : vla) { .. }
2436 // }
2437
2438 // FIXME: This results in codegen generating IR that recalculates the
2439 // run-time number of elements (as opposed to just using the IR Value
2440 // that corresponds to the run-time value of each bound that was
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002441 // generated when the array was created.) If this proves too embarrassing
Faisal Vali1ca2d962017-05-15 01:49:19 +00002442 // even for unoptimized IR, consider passing a magic-value/cookie to
2443 // codegen that then knows to simply use that initial llvm::Value (that
2444 // corresponds to the bound at time of array creation) within
2445 // getelementptr. But be prepared to pay the price of increasing a
2446 // customized form of coupling between the two components - which could
2447 // be hard to maintain as the codebase evolves.
2448
2449 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2450 EndVar->getLocation(), UETT_SizeOf,
2451 /*isType=*/true,
2452 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2453 VAT->desugar(), RangeLoc))
2454 .getAsOpaquePtr(),
2455 EndVar->getSourceRange());
2456 if (SizeOfVLAExprR.isInvalid())
2457 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002458
Faisal Vali1ca2d962017-05-15 01:49:19 +00002459 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2460 EndVar->getLocation(), UETT_SizeOf,
2461 /*isType=*/true,
2462 CreateParsedType(VAT->desugar(),
2463 Context.getTrivialTypeSourceInfo(
2464 VAT->getElementType(), RangeLoc))
2465 .getAsOpaquePtr(),
2466 EndVar->getSourceRange());
2467 if (SizeOfEachElementExprR.isInvalid())
2468 return StmtError();
2469
2470 BoundExpr =
2471 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2472 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2473 if (BoundExpr.isInvalid())
2474 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002475
Faisal Vali1ca2d962017-05-15 01:49:19 +00002476 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002477 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2478 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002479 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002480 }
2481
2482 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002483 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002484 BoundExpr.get());
2485 if (EndExpr.isInvalid())
2486 return StmtError();
2487 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2488 diag::err_for_range_iter_deduction_failure)) {
2489 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2490 return StmtError();
2491 }
2492 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002493 OverloadCandidateSet CandidateSet(RangeLoc,
2494 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002495 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002496 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2497 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2498 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2499 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002500
Richard Smitha05b3b52012-09-20 21:52:32 +00002501 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002502 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002503 // If the range is being built from an array parameter, emit a
2504 // a diagnostic that it is being treated as a pointer.
2505 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2506 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2507 QualType ArrayTy = PVD->getOriginalType();
2508 QualType PointerTy = PVD->getType();
2509 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002510 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2511 << RangeLoc << PVD << ArrayTy << PointerTy;
Richard Trieu08254692013-10-11 22:16:04 +00002512 Diag(PVD->getLocation(), diag::note_declared_at);
2513 return StmtError();
2514 }
2515 }
2516 }
2517
2518 // If building the range failed, try dereferencing the range expression
2519 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002520 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002521 CoawaitLoc, InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002522 LoopVarDecl, ColonLoc,
2523 Range, RangeLoc,
2524 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002525 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002526 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002527 }
2528
Sam Panzer0f384432012-08-21 00:52:01 +00002529 // Otherwise, emit diagnostics if we haven't already.
2530 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002531 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
David Blaikie5e328052019-05-03 00:44:50 +00002532 CandidateSet.NoteCandidates(
2533 PartialDiagnosticAt(Range->getBeginLoc(),
2534 PDiag(diag::err_for_range_invalid)
2535 << RangeLoc << Range->getType()
2536 << BEFFailure),
2537 *this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002538 }
2539 // Return an error if no fix was discovered.
2540 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002541 return StmtError();
2542 }
2543
Sam Panzer0f384432012-08-21 00:52:01 +00002544 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2545 "invalid range expression in for loop");
2546
2547 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002548 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002549 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2550 if (!Context.hasSameType(BeginType, EndType)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002551 Diag(RangeLoc, getLangOpts().CPlusPlus17
Richard Smith01694c32016-03-20 10:33:40 +00002552 ? diag::warn_for_range_begin_end_types_differ
2553 : diag::ext_for_range_begin_end_types_differ)
2554 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002555 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2556 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2557 }
2558
Richard Smith01694c32016-03-20 10:33:40 +00002559 BeginDeclStmt =
2560 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2561 EndDeclStmt =
2562 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002563
Ted Kremenekbed648e2011-10-10 22:36:28 +00002564 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2565 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002566 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002567 if (BeginRef.isInvalid())
2568 return StmtError();
2569
Richard Smith02e85f32011-04-14 22:09:26 +00002570 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2571 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002572 if (EndRef.isInvalid())
2573 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002574
2575 // Build and check __begin != __end expression.
2576 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2577 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002578 if (!NotEqExpr.isInvalid())
2579 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2580 if (!NotEqExpr.isInvalid())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002581 NotEqExpr =
2582 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002583 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002584 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2585 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002586 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2587 if (!Context.hasSameType(BeginType, EndType))
2588 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2589 return StmtError();
2590 }
2591
2592 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002593 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2594 VK_LValue, ColonLoc);
2595 if (BeginRef.isInvalid())
2596 return StmtError();
2597
Richard Smith02e85f32011-04-14 22:09:26 +00002598 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002599 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002600 // FIXME: getCurScope() should not be used during template instantiation.
2601 // We should pick up the set of unqualified lookup results for operator
2602 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002603 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002604 if (!IncrExpr.isInvalid())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002605 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002606 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002607 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2608 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002609 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2610 return StmtError();
2611 }
2612
2613 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002614 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2615 VK_LValue, ColonLoc);
2616 if (BeginRef.isInvalid())
2617 return StmtError();
2618
Richard Smith02e85f32011-04-14 22:09:26 +00002619 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2620 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002621 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2622 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002623 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2624 return StmtError();
2625 }
2626
Richard Smitha05b3b52012-09-20 21:52:32 +00002627 // Attach *__begin as initializer for VD. Don't touch it if we're just
2628 // trying to determine whether this would be a valid range.
2629 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002630 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002631 if (LoopVar->isInvalidDecl())
2632 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2633 }
2634 }
2635
Richard Smitha05b3b52012-09-20 21:52:32 +00002636 // Don't bother to actually allocate the result if we're just trying to
2637 // determine whether it would be valid.
2638 if (Kind == BFRK_Check)
2639 return StmtResult();
2640
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002641 return new (Context) CXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002642 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
Richard Smith01694c32016-03-20 10:33:40 +00002643 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002644 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2645 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002646}
2647
Chad Rosier02a84392012-08-10 17:56:09 +00002648/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002649/// statement.
2650StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2651 if (!S || !B)
2652 return StmtError();
2653 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002654
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002655 ForStmt->setBody(B);
2656 return S;
2657}
2658
Richard Trieu3e1d4832015-04-13 22:08:55 +00002659// Warn when the loop variable is a const reference that creates a copy.
2660// Suggest using the non-reference type for copies. If a copy can be prevented
2661// suggest the const reference type that would do so.
2662// For instance, given "for (const &Foo : Range)", suggest
2663// "for (const Foo : Range)" to denote a copy is made for the loop. If
2664// possible, also suggest "for (const &Bar : Range)" if this type prevents
2665// the copy altogether.
2666static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2667 const VarDecl *VD,
2668 QualType RangeInitType) {
2669 const Expr *InitExpr = VD->getInit();
2670 if (!InitExpr)
2671 return;
2672
2673 QualType VariableType = VD->getType();
2674
Tim Shen4a05bb82016-06-21 20:29:17 +00002675 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2676 if (!Cleanups->cleanupsHaveSideEffects())
2677 InitExpr = Cleanups->getSubExpr();
2678
Richard Trieu3e1d4832015-04-13 22:08:55 +00002679 const MaterializeTemporaryExpr *MTE =
2680 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2681
2682 // No copy made.
2683 if (!MTE)
2684 return;
2685
2686 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2687
2688 // Searching for either UnaryOperator for dereference of a pointer or
2689 // CXXOperatorCallExpr for handling iterators.
2690 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2691 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2692 E = CCE->getArg(0);
2693 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2694 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2695 E = ME->getBase();
2696 } else {
2697 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2698 E = MTE->GetTemporaryExpr();
2699 }
2700 E = E->IgnoreImpCasts();
2701 }
2702
2703 bool ReturnsReference = false;
2704 if (isa<UnaryOperator>(E)) {
2705 ReturnsReference = true;
2706 } else {
2707 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2708 const FunctionDecl *FD = Call->getDirectCallee();
2709 QualType ReturnType = FD->getReturnType();
2710 ReturnsReference = ReturnType->isReferenceType();
2711 }
2712
2713 if (ReturnsReference) {
2714 // Loop variable creates a temporary. Suggest either to go with
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002715 // non-reference loop variable to indicate a copy is made, or
Richard Trieu3e1d4832015-04-13 22:08:55 +00002716 // the correct time to bind a const reference.
2717 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2718 << VD << VariableType << E->getType();
2719 QualType NonReferenceType = VariableType.getNonReferenceType();
2720 NonReferenceType.removeLocalConst();
2721 QualType NewReferenceType =
2722 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002723 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002724 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2725 } else {
2726 // The range always returns a copy, so a temporary is always created.
2727 // Suggest removing the reference from the loop variable.
2728 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2729 << VD << RangeInitType;
2730 QualType NonReferenceType = VariableType.getNonReferenceType();
2731 NonReferenceType.removeLocalConst();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002732 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002733 << NonReferenceType << VD->getSourceRange();
2734 }
2735}
2736
2737// Warns when the loop variable can be changed to a reference type to
2738// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2739// "for (const Foo &x : Range)" if this form does not make a copy.
2740static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2741 const VarDecl *VD) {
2742 const Expr *InitExpr = VD->getInit();
2743 if (!InitExpr)
2744 return;
2745
2746 QualType VariableType = VD->getType();
2747
2748 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2749 if (!CE->getConstructor()->isCopyConstructor())
2750 return;
2751 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2752 if (CE->getCastKind() != CK_LValueToRValue)
2753 return;
2754 } else {
2755 return;
2756 }
2757
2758 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2759 // should be emitted. Also, only ignore POD types with trivial copy
2760 // constructors.
2761 if (VariableType.isPODType(SemaRef.Context))
2762 return;
2763
2764 // Suggest changing from a const variable to a const reference variable
2765 // if doing so will prevent a copy.
2766 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2767 << VD << VariableType << InitExpr->getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002768 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002769 << SemaRef.Context.getLValueReferenceType(VariableType)
2770 << VD->getSourceRange();
2771}
2772
2773/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2774/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2775/// using "const foo x" to show that a copy is made
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002776/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
Richard Trieu3e1d4832015-04-13 22:08:55 +00002777/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2778/// prevent the copy.
2779/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2780/// Suggest "const foo &x" to prevent the copy.
2781static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2782 const CXXForRangeStmt *ForStmt) {
2783 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002784 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002785 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002786 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002787 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002788 ForStmt->getBeginLoc())) {
Richard Trieu3e1d4832015-04-13 22:08:55 +00002789 return;
2790 }
2791
2792 const VarDecl *VD = ForStmt->getLoopVariable();
2793 if (!VD)
2794 return;
2795
2796 QualType VariableType = VD->getType();
2797
2798 if (VariableType->isIncompleteType())
2799 return;
2800
2801 const Expr *InitExpr = VD->getInit();
2802 if (!InitExpr)
2803 return;
2804
2805 if (VariableType->isReferenceType()) {
2806 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2807 ForStmt->getRangeInit()->getType());
2808 } else if (VariableType.isConstQualified()) {
2809 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2810 }
2811}
2812
Richard Smith02e85f32011-04-14 22:09:26 +00002813/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2814/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2815/// body cannot be performed until after the type of the range variable is
2816/// determined.
2817StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2818 if (!S || !B)
2819 return StmtError();
2820
Fariborz Jahanian00213472012-07-06 19:04:04 +00002821 if (isa<ObjCForCollectionStmt>(S))
2822 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002823
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002824 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2825 ForStmt->setBody(B);
2826
2827 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2828 diag::warn_empty_range_based_for_body);
2829
Richard Trieu3e1d4832015-04-13 22:08:55 +00002830 DiagnoseForRangeVariableCopies(*this, ForStmt);
2831
Richard Smith02e85f32011-04-14 22:09:26 +00002832 return S;
2833}
2834
Chris Lattnercab02a62011-02-17 20:34:02 +00002835StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2836 SourceLocation LabelLoc,
2837 LabelDecl *TheDecl) {
Reid Kleckner87a31802018-03-12 21:43:02 +00002838 setFunctionHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002839 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002840 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002841}
Chris Lattner1c310502007-05-31 06:00:00 +00002842
John McCalldadc5752010-08-24 06:29:42 +00002843StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002844Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002845 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002846 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002847 if (!E->isTypeDependent()) {
2848 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002849 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002850 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002851 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002852 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2853 if (ExprRes.isInvalid())
2854 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002855 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002856 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002857 return StmtError();
2858 }
John McCalla95172b2010-08-01 00:26:45 +00002859
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002860 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00002861 if (ExprRes.isInvalid())
2862 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002863 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002864
Reid Kleckner87a31802018-03-12 21:43:02 +00002865 setFunctionHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002866
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002867 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002868}
2869
Nico Weberd64657f2015-03-09 02:47:59 +00002870static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2871 const Scope &DestScope) {
2872 if (!S.CurrentSEHFinally.empty() &&
2873 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2874 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2875 }
2876}
2877
John McCalldadc5752010-08-24 06:29:42 +00002878StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002879Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002880 Scope *S = CurScope->getContinueParent();
2881 if (!S) {
2882 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002883 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002884 }
Nico Weberd64657f2015-03-09 02:47:59 +00002885 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002886
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002887 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002888}
2889
John McCalldadc5752010-08-24 06:29:42 +00002890StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002891Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002892 Scope *S = CurScope->getBreakParent();
2893 if (!S) {
2894 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002895 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002896 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002897 if (S->isOpenMPLoopScope())
2898 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2899 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002900 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002901
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002902 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002903}
2904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002905/// Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002906/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002907///
Douglas Gregor5d369002011-01-21 18:05:27 +00002908/// \param ReturnType If we're determining the copy elision candidate for
2909/// a return statement, this is the return type of the function. If we're
2910/// determining the copy elision candidate for a throw expression, this will
2911/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002912///
Douglas Gregor5d369002011-01-21 18:05:27 +00002913/// \param E The expression being returned from the function or block, or
2914/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002915///
Richard Trieu09c163b2018-03-15 03:00:55 +00002916/// \param CESK Whether we allow function parameters or
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002917/// id-expressions that could be moved out of the function to be considered NRVO
2918/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2919/// determine whether we should try to move as part of a return or throw (which
2920/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002921///
2922/// \returns The NRVO candidate variable, if the return statement may use the
2923/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002924VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
Richard Trieu09c163b2018-03-15 03:00:55 +00002925 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002926 // - in a return statement in a function [where] ...
2927 // ... the expression is the name of a non-volatile automatic object ...
2928 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002929 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002930 return nullptr;
2931 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2932 if (!VD)
2933 return nullptr;
2934
Richard Trieu09c163b2018-03-15 03:00:55 +00002935 if (isCopyElisionCandidate(ReturnType, VD, CESK))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002936 return VD;
2937 return nullptr;
2938}
2939
2940bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Richard Trieu09c163b2018-03-15 03:00:55 +00002941 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002942 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002943 // - in a return statement in a function with ...
2944 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002945 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002946 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002947 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002948 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002949 // When considering moving this expression out, allow dissimilar types.
Richard Trieu09c163b2018-03-15 03:00:55 +00002950 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002951 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2952 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002953 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954
John McCall03318c12011-11-11 03:57:31 +00002955 // ...object (other than a function or catch-clause parameter)...
2956 if (VD->getKind() != Decl::Var &&
Richard Trieu09c163b2018-03-15 03:00:55 +00002957 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002958 return false;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002959 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2960 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002961
John McCall03318c12011-11-11 03:57:31 +00002962 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002963 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002964
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002965 // Return false if VD is a __block variable. We don't want to implicitly move
2966 // out of a __block variable during a return because we cannot assume the
2967 // variable will no longer be used.
2968 if (VD->hasAttr<BlocksAttr>()) return false;
2969
Richard Trieu09c163b2018-03-15 03:00:55 +00002970 if (CESK & CES_AllowDifferentTypes)
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002971 return true;
2972
John McCall03318c12011-11-11 03:57:31 +00002973 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002974 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002975
John McCall03318c12011-11-11 03:57:31 +00002976 // Variables with higher required alignment than their type's ABI
2977 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002978 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002979 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002980 return false;
John McCall03318c12011-11-11 03:57:31 +00002981
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002982 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002983}
2984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002985/// Try to perform the initialization of a potentially-movable value,
Richard Trieu09c163b2018-03-15 03:00:55 +00002986/// which is the operand to a return or throw statement.
2987///
2988/// This routine implements C++14 [class.copy]p32, which attempts to treat
2989/// returned lvalues as rvalues in certain cases (to prefer move construction),
2990/// then falls back to treating them as lvalues if that failed.
2991///
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002992/// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
2993/// resolutions that find non-constructors, such as derived-to-base conversions
2994/// or `operator T()&&` member functions. If false, do consider such
2995/// conversion sequences.
2996///
Richard Trieu09c163b2018-03-15 03:00:55 +00002997/// \param Res We will fill this in if move-initialization was possible.
2998/// If move-initialization is not possible, such that we must fall back to
2999/// treating the operand as an lvalue, we will leave Res in its original
3000/// invalid state.
3001static void TryMoveInitialization(Sema& S,
3002 const InitializedEntity &Entity,
3003 const VarDecl *NRVOCandidate,
3004 QualType ResultType,
3005 Expr *&Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003006 bool ConvertingConstructorsOnly,
Richard Trieu09c163b2018-03-15 03:00:55 +00003007 ExprResult &Res) {
3008 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3009 CK_NoOp, Value, VK_XValue);
3010
3011 Expr *InitExpr = &AsRvalue;
3012
3013 InitializationKind Kind = InitializationKind::CreateCopy(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003014 Value->getBeginLoc(), Value->getBeginLoc());
Richard Trieu09c163b2018-03-15 03:00:55 +00003015
3016 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3017
3018 if (!Seq)
3019 return;
3020
3021 for (const InitializationSequence::Step &Step : Seq.steps()) {
3022 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3023 Step.Kind != InitializationSequence::SK_UserConversion)
3024 continue;
3025
3026 FunctionDecl *FD = Step.Function.Function;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003027 if (ConvertingConstructorsOnly) {
3028 if (isa<CXXConstructorDecl>(FD)) {
3029 // C++14 [class.copy]p32:
3030 // [...] If the first overload resolution fails or was not performed,
3031 // or if the type of the first parameter of the selected constructor
3032 // is not an rvalue reference to the object's type (possibly
3033 // cv-qualified), overload resolution is performed again, considering
3034 // the object as an lvalue.
3035 const RValueReferenceType *RRefType =
3036 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3037 if (!RRefType)
3038 break;
3039 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3040 NRVOCandidate->getType()))
3041 break;
3042 } else {
3043 continue;
3044 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003045 } else {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003046 if (isa<CXXConstructorDecl>(FD)) {
3047 // Check that overload resolution selected a constructor taking an
3048 // rvalue reference. If it selected an lvalue reference, then we
3049 // didn't need to cast this thing to an rvalue in the first place.
3050 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3051 break;
3052 } else if (isa<CXXMethodDecl>(FD)) {
3053 // Check that overload resolution selected a conversion operator
3054 // taking an rvalue reference.
3055 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3056 break;
3057 } else {
3058 continue;
3059 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003060 }
3061
3062 // Promote "AsRvalue" to the heap, since we now need this
3063 // expression node to persist.
3064 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3065 Value, nullptr, VK_XValue);
3066
3067 // Complete type-checking the initialization of the return type
3068 // using the constructor we found.
3069 Res = Seq.Perform(S, Entity, Kind, Value);
3070 }
3071}
3072
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003073/// Perform the initialization of a potentially-movable value, which
Douglas Gregor626fbed2011-01-21 21:08:57 +00003074/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00003075///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003076/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00003077/// returned lvalues as rvalues in certain cases (to prefer move construction),
3078/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00003080Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3081 const VarDecl *NRVOCandidate,
3082 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00003083 Expr *Value,
3084 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003085 // C++14 [class.copy]p32:
3086 // When the criteria for elision of a copy/move operation are met, but not for
3087 // an exception-declaration, and the object to be copied is designated by an
3088 // lvalue, or when the expression in a return statement is a (possibly
3089 // parenthesized) id-expression that names an object with automatic storage
3090 // duration declared in the body or parameter-declaration-clause of the
3091 // innermost enclosing function or lambda-expression, overload resolution to
3092 // select the constructor for the copy is first performed as if the object
3093 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00003094 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003095
Richard Trieu09c163b2018-03-15 03:00:55 +00003096 if (AllowNRVO) {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003097 bool AffectedByCWG1579 = false;
3098
Richard Trieu09c163b2018-03-15 03:00:55 +00003099 if (!NRVOCandidate) {
3100 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003101 if (NRVOCandidate &&
3102 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3103 Value->getExprLoc())) {
3104 const VarDecl *NRVOCandidateInCXX11 =
3105 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3106 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3107 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003108 }
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003109
Richard Trieu09c163b2018-03-15 03:00:55 +00003110 if (NRVOCandidate) {
3111 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003112 true, Res);
3113 }
3114
3115 if (!Res.isInvalid() && AffectedByCWG1579) {
3116 QualType QT = NRVOCandidate->getType();
3117 if (QT.getNonReferenceType()
3118 .getUnqualifiedType()
3119 .isTriviallyCopyableType(Context)) {
3120 // Adding 'std::move' around a trivially copyable variable is probably
3121 // pointless. Don't suggest it.
3122 } else {
3123 // Common cases for this are returning unique_ptr<Derived> from a
3124 // function of return type unique_ptr<Base>, or returning T from a
3125 // function of return type Expected<T>. This is totally fine in a
3126 // post-CWG1579 world, but was not fine before.
3127 assert(!ResultType.isNull());
3128 SmallString<32> Str;
3129 Str += "std::move(";
3130 Str += NRVOCandidate->getDeclName().getAsString();
3131 Str += ")";
3132 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3133 << Value->getSourceRange()
3134 << NRVOCandidate->getDeclName() << ResultType << QT;
3135 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3136 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3137 }
3138 } else if (Res.isInvalid() &&
3139 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3140 Value->getExprLoc())) {
3141 const VarDecl *FakeNRVOCandidate =
3142 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3143 if (FakeNRVOCandidate) {
3144 QualType QT = FakeNRVOCandidate->getType();
3145 if (QT->isLValueReferenceType()) {
3146 // Adding 'std::move' around an lvalue reference variable's name is
3147 // dangerous. Don't suggest it.
3148 } else if (QT.getNonReferenceType()
3149 .getUnqualifiedType()
3150 .isTriviallyCopyableType(Context)) {
3151 // Adding 'std::move' around a trivially copyable variable is probably
3152 // pointless. Don't suggest it.
3153 } else {
3154 ExprResult FakeRes = ExprError();
3155 Expr *FakeValue = Value;
3156 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3157 FakeValue, false, FakeRes);
3158 if (!FakeRes.isInvalid()) {
3159 bool IsThrow =
3160 (Entity.getKind() == InitializedEntity::EK_Exception);
3161 SmallString<32> Str;
3162 Str += "std::move(";
3163 Str += FakeNRVOCandidate->getDeclName().getAsString();
3164 Str += ")";
3165 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3166 << Value->getSourceRange()
3167 << FakeNRVOCandidate->getDeclName() << IsThrow;
3168 Diag(Value->getExprLoc(), diag::note_add_std_move)
3169 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3170 }
3171 }
3172 }
Douglas Gregorf282a762011-01-21 19:38:21 +00003173 }
3174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175
Douglas Gregorf282a762011-01-21 19:38:21 +00003176 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00003178 // (again) now with the return value expression as written.
3179 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00003180 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181
Douglas Gregorf282a762011-01-21 19:38:21 +00003182 return Res;
3183}
3184
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003185/// Determine whether the declared return type of the specified function
Richard Smith4db51c22013-09-25 05:02:54 +00003186/// contains 'auto'.
3187static bool hasDeducedReturnType(FunctionDecl *FD) {
3188 const FunctionProtoType *FPT =
3189 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003190 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003191}
3192
Eli Friedman34b49062012-01-26 03:00:14 +00003193/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3194/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003195///
John McCalldadc5752010-08-24 06:29:42 +00003196StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003197Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3198 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003199 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003200 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003201 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003202 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003203 bool HasDeducedReturnType =
3204 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003205
Faisal Valid143a0c2017-04-01 21:30:49 +00003206 if (ExprEvalContexts.back().Context ==
3207 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003208 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3209 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003210 ExprResult ER =
3211 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smithb130fe72016-06-23 19:16:49 +00003212 if (ER.isInvalid())
3213 return StmtError();
3214 RetValExp = ER.get();
3215 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003216 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3217 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003218 }
3219
3220 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003221 // In C++1y, the return type may involve 'auto'.
3222 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3223 FunctionDecl *FD = CurLambda->CallOperator;
3224 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003225 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003226
3227 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3228 assert(AT && "lost auto type from lambda return type");
3229 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3230 FD->setInvalidDecl();
3231 return StmtError();
3232 }
Alp Toker314cc812014-01-25 16:55:45 +00003233 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003234 } else if (CurCap->HasImplicitReturnType) {
3235 // For blocks/lambdas with implicit return types, we check each return
3236 // statement individually, and deduce the common return type when the block
3237 // or lambda is completed.
3238 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003239 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003240 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3241 if (Result.isInvalid())
3242 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003243 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003244
Richard Smith5a0e50c2014-12-19 22:10:51 +00003245 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3246 // when deducing a return type for a lambda-expression (or by extension
3247 // for a block). These rules differ from the stated C++11 rules only in
3248 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003249 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003250 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003251 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003252 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003253 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003254 if (RetValExp) {
3255 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3256 // initializer list, because it is not an expression (even
3257 // though we represent it as one). We still deduce 'void'.
3258 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3259 << RetValExp->getSourceRange();
3260 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003261
Jordan Rosed39e5f12012-07-02 21:19:23 +00003262 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003263 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003264
3265 // Although we'll properly infer the type of the block once it's completed,
3266 // make sure we provide a return type now for better error recovery.
3267 if (CurCap->ReturnType.isNull())
3268 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003269 }
Eli Friedman34b49062012-01-26 03:00:14 +00003270 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003271
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003272 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00003273 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3274 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3275 return StmtError();
3276 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003277 } else if (CapturedRegionScopeInfo *CurRegion =
3278 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3279 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3280 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003281 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003282 assert(CurLambda && "unknown kind of captured scope");
3283 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3284 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003285 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3286 return StmtError();
3287 }
3288 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003289
Steve Naroffc540d662008-09-03 18:15:37 +00003290 // Otherwise, verify that this result type matches the previous one. We are
3291 // pickier with blocks than for normal functions because we don't have GCC
3292 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003293 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003294 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003295 // Delay processing for now. TODO: there are lots of dependent
3296 // types we can conclusively prove aren't void.
3297 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003298 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003299 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003300 (RetValExp->isTypeDependent() ||
3301 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003302 if (!getLangOpts().CPlusPlus &&
3303 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003304 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003305 else {
3306 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003307 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003308 }
Steve Naroffc540d662008-09-03 18:15:37 +00003309 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003310 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003311 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3312 } else if (!RetValExp->isTypeDependent()) {
3313 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003314
John McCall5500ef22011-08-17 22:09:46 +00003315 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3316 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3317 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003318
John McCall5500ef22011-08-17 22:09:46 +00003319 // In C++ the return statement is handled via a copy initialization.
3320 // the C version of which boils down to CheckSingleAssignmentConstraints.
Richard Trieu09c163b2018-03-15 03:00:55 +00003321 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
John McCall5500ef22011-08-17 22:09:46 +00003322 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3323 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003324 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003325 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3326 FnRetType, RetValExp);
3327 if (Res.isInvalid()) {
3328 // FIXME: Cleanup temporaries here, anyway?
3329 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003330 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003331 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003332 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003333 } else {
Richard Trieu09c163b2018-03-15 03:00:55 +00003334 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Steve Naroffc540d662008-09-03 18:15:37 +00003335 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003336
John McCall75f92b52011-08-17 21:34:14 +00003337 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003338 ExprResult ER =
3339 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003340 if (ER.isInvalid())
3341 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003342 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003343 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003344 auto *Result =
3345 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003346
Jordan Rosed39e5f12012-07-02 21:19:23 +00003347 // If we need to check for the named return value optimization,
3348 // or if we need to infer the return type,
3349 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003350 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003351 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352
Richard Smith9f690bd2015-10-27 06:02:45 +00003353 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3354 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3355
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003356 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003357}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003358
Nico Weber72889432014-09-06 01:25:55 +00003359namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003360/// Marks all typedefs in all local classes in a type referenced.
Nico Weber72889432014-09-06 01:25:55 +00003361///
3362/// In a function like
3363/// auto f() {
3364/// struct S { typedef int a; };
3365/// return S();
3366/// }
3367///
3368/// the local type escapes and could be referenced in some TUs but not in
3369/// others. Pretend that all local typedefs are always referenced, to not warn
3370/// on this. This isn't necessary if f has internal linkage, or the typedef
3371/// is private.
3372class LocalTypedefNameReferencer
3373 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3374public:
3375 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3376 bool VisitRecordType(const RecordType *RT);
3377private:
3378 Sema &S;
3379};
3380bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3381 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3382 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3383 R->isDependentType())
3384 return true;
3385 for (auto *TmpD : R->decls())
3386 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3387 if (T->getAccess() != AS_private || R->hasFriends())
3388 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3389 return true;
3390}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003391}
Nico Weber72889432014-09-06 01:25:55 +00003392
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003393TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Leonard Chanc72aaf62019-05-07 03:20:17 +00003394 return FD->getTypeSourceInfo()
3395 ->getTypeLoc()
3396 .getAsAdjusted<FunctionProtoTypeLoc>()
3397 .getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003398}
3399
Richard Smith2a7d4812013-05-04 07:00:32 +00003400/// Deduce the return type for a function from a returned expression, per
3401/// C++1y [dcl.spec.auto]p6.
3402bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3403 SourceLocation ReturnLoc,
3404 Expr *&RetExpr,
3405 AutoType *AT) {
Richard Smith50e291e2018-01-02 23:52:42 +00003406 // If this is the conversion function for a lambda, we choose to deduce it
3407 // type from the corresponding call operator, not from the synthesized return
3408 // statement within it. See Sema::DeduceReturnType.
3409 if (isLambdaConversionOperator(FD))
3410 return false;
3411
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003412 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003413 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003414
Richard Smithc58f38f2013-08-14 20:16:31 +00003415 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3416 // If the deduction is for a return statement and the initializer is
3417 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003418 Diag(RetExpr->getExprLoc(),
3419 getCurLambda() ? diag::err_lambda_return_init_list
3420 : diag::err_auto_fn_return_init_list)
3421 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003422 return true;
3423 }
3424
3425 if (FD->isDependentContext()) {
3426 // C++1y [dcl.spec.auto]p12:
3427 // Return type deduction [...] occurs when the definition is
3428 // instantiated even if the function body contains a return
3429 // statement with a non-type-dependent operand.
3430 assert(AT->isDeduced() && "should have deduced to dependent type");
3431 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003432 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003433
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003434 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003435 // Otherwise, [...] deduce a value for U using the rules of template
3436 // argument deduction.
3437 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3438
3439 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3440 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3441 << OrigResultType.getType() << RetExpr->getType();
3442
3443 if (DAR != DAR_Succeeded)
3444 return true;
Nico Weber72889432014-09-06 01:25:55 +00003445
3446 // If a local type is part of the returned type, mark its fields as
3447 // referenced.
3448 LocalTypedefNameReferencer Referencer(*this);
3449 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003450 } else {
3451 // In the case of a return with no operand, the initializer is considered
3452 // to be void().
3453 //
3454 // Deduction here can only succeed if the return type is exactly 'cv auto'
3455 // or 'decltype(auto)', so just check for that case directly.
3456 if (!OrigResultType.getType()->getAs<AutoType>()) {
3457 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3458 << OrigResultType.getType();
3459 return true;
3460 }
3461 // We always deduce U = void in this case.
3462 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3463 if (Deduced.isNull())
3464 return true;
3465 }
3466
3467 // If a function with a declared return type that contains a placeholder type
3468 // has multiple return statements, the return type is deduced for each return
3469 // statement. [...] if the type deduced is not the same in each deduction,
3470 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003471 QualType DeducedT = AT->getDeducedType();
3472 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003473 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003474 // It is possible that NewAT->getDeducedType() is null. When that happens,
3475 // we should not crash, instead we ignore this deduction.
3476 if (NewAT->getDeducedType().isNull())
3477 return false;
3478
Douglas Gregora602a152015-10-01 20:20:47 +00003479 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003480 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003481 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3482 NewAT->getDeducedType());
3483 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003484 const LambdaScopeInfo *LambdaSI = getCurLambda();
3485 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3486 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003487 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003488 << true /*IsLambda*/;
3489 } else {
3490 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3491 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003492 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003493 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003494 return true;
3495 }
3496 } else if (!FD->isInvalidDecl()) {
3497 // Update all declarations of the function to have the deduced return type.
3498 Context.adjustDeducedFunctionResultType(FD, Deduced);
3499 }
3500
3501 return false;
3502}
3503
John McCalldadc5752010-08-24 06:29:42 +00003504StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003505Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3506 Scope *CurScope) {
Sam McCall835d67f2019-05-08 05:49:42 +00003507 // Correct typos, in case the containing function returns 'auto' and
3508 // RetValExp should determine the deduced type.
3509 ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
3510 if (RetVal.isInvalid())
3511 return StmtError();
3512 StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
Faisal Valid143a0c2017-04-01 21:30:49 +00003513 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3514 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003515 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003516
Taiju Tsuiki3be68e12018-06-19 05:35:30 +00003517 if (VarDecl *VD =
3518 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3519 CurScope->addNRVOCandidate(VD);
3520 } else {
3521 CurScope->setNoNRVO();
3522 }
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003523
Nico Weberd64657f2015-03-09 02:47:59 +00003524 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3525
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003526 return R;
3527}
3528
3529StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003530 // Check for unexpanded parameter packs.
3531 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3532 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003533
Eli Friedman34b49062012-01-26 03:00:14 +00003534 if (isa<CapturingScopeInfo>(getCurFunction()))
3535 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003536
Chris Lattner79413952008-12-04 23:50:19 +00003537 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003538 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003539 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003540 bool isObjCMethod = false;
3541
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003542 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003543 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003544 if (FD->hasAttrs())
3545 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003546 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003547 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003548 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003549 if (FD->isMain() && RetValExp)
3550 if (isa<CXXBoolLiteralExpr>(RetValExp))
3551 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3552 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003553 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003554 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003555 isObjCMethod = true;
3556 if (MD->hasAttrs())
3557 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003558 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3559 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003560 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003561 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003562 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3563 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003564 }
3565 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003566 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003567
Richard Smithb130fe72016-06-23 19:16:49 +00003568 // C++1z: discarded return statements are not considered when deducing a
3569 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003570 if (ExprEvalContexts.back().Context ==
3571 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003572 FnRetType->getContainedAutoType()) {
3573 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003574 ExprResult ER =
3575 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smithb130fe72016-06-23 19:16:49 +00003576 if (ER.isInvalid())
3577 return StmtError();
3578 RetValExp = ER.get();
3579 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003580 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3581 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003582 }
3583
Richard Smith2a7d4812013-05-04 07:00:32 +00003584 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3585 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003586 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003587 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3588 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003589 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003590 FD->setInvalidDecl();
3591 return StmtError();
3592 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003593 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003594 }
3595 }
3596 }
3597
Richard Smithc58f38f2013-08-14 20:16:31 +00003598 bool HasDependentReturnType = FnRetType->isDependentType();
3599
Craig Topperc3ec1492014-05-26 06:22:03 +00003600 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003601 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003602 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003603 if (isa<InitListExpr>(RetValExp)) {
3604 // We simply never allow init lists as the return value of void
3605 // functions. This is compatible because this was never allowed before,
3606 // so there's no legacy code to deal with.
3607 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3608 int FunctionKind = 0;
3609 if (isa<ObjCMethodDecl>(CurDecl))
3610 FunctionKind = 1;
3611 else if (isa<CXXConstructorDecl>(CurDecl))
3612 FunctionKind = 2;
3613 else if (isa<CXXDestructorDecl>(CurDecl))
3614 FunctionKind = 3;
3615
3616 Diag(ReturnLoc, diag::err_return_init_list)
3617 << CurDecl->getDeclName() << FunctionKind
3618 << RetValExp->getSourceRange();
3619
3620 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003621 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003622 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003623 // C99 6.8.6.4p1 (ext_ since GCC warns)
3624 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003625 if (RetValExp->getType()->isVoidType()) {
3626 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3627 if (isa<CXXConstructorDecl>(CurDecl) ||
3628 isa<CXXDestructorDecl>(CurDecl))
3629 D = diag::err_ctor_dtor_returns_void;
3630 else
3631 D = diag::ext_return_has_void_expr;
3632 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003633 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003634 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003635 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003636 if (Result.isInvalid())
3637 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003638 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003639 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003640 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003641 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003642 // return of void in constructor/destructor is illegal in C++.
3643 if (D == diag::err_ctor_dtor_returns_void) {
3644 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3645 Diag(ReturnLoc, D)
3646 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3647 << RetValExp->getSourceRange();
3648 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003649 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003650 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003651 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003652 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003653
3654 int FunctionKind = 0;
3655 if (isa<ObjCMethodDecl>(CurDecl))
3656 FunctionKind = 1;
3657 else if (isa<CXXConstructorDecl>(CurDecl))
3658 FunctionKind = 2;
3659 else if (isa<CXXDestructorDecl>(CurDecl))
3660 FunctionKind = 3;
3661
Nick Lewycky1be750a2011-06-01 07:44:31 +00003662 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003663 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003664 << RetValExp->getSourceRange();
3665 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003666 }
Mike Stump11289f42009-09-09 15:08:12 +00003667
Sebastian Redleef474c2012-02-22 10:50:08 +00003668 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003669 ExprResult ER =
3670 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003671 if (ER.isInvalid())
3672 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003673 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003674 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Bruno Ricci023b1d12018-10-30 14:40:49 +00003677 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3678 /* NRVOCandidate=*/nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003679 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003680 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003681
David Majnemer2887ad32014-12-13 08:12:56 +00003682 unsigned DiagID;
3683 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3684 // C++11 [stmt.return]p2
3685 DiagID = diag::err_constexpr_return_missing_expr;
3686 FD->setInvalidDecl();
3687 } else if (getLangOpts().C99) {
3688 // C99 6.8.6.4p1 (ext_ since GCC warns)
3689 DiagID = diag::ext_return_missing_expr;
3690 } else {
3691 // C90 6.6.6.4p4
3692 DiagID = diag::warn_return_missing_expr;
3693 }
3694
3695 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003696 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003697 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003698 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003699
Bruno Ricci023b1d12018-10-30 14:40:49 +00003700 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3701 /* NRVOCandidate=*/nullptr);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003702 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003703 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003704 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003705
3706 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3707
3708 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3709 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3710 // function return.
3711
3712 // In C++ the return statement is handled via a copy initialization,
3713 // the C version of which boils down to CheckSingleAssignmentConstraints.
3714 if (RetValExp)
Richard Trieu09c163b2018-03-15 03:00:55 +00003715 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Richard Smith2a7d4812013-05-04 07:00:32 +00003716 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003717 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003718 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003719 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003720 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003722 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003723 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003724 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003725 return StmtError();
3726 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003727 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003728
3729 // If we have a related result type, we need to implicitly
3730 // convert back to the formal result type. We can't pretend to
3731 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003732 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003733 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003734 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3735 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003736 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3737 if (Res.isInvalid()) {
3738 // FIXME: Clean up temporaries here anyway?
3739 return StmtError();
3740 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003741 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003742 }
3743
Artyom Skrobov9f213442014-01-24 11:10:39 +00003744 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3745 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747
John McCallacf0ee52010-10-08 02:01:28 +00003748 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003749 ExprResult ER =
3750 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003751 if (ER.isInvalid())
3752 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003753 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003754 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003755 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757
3758 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003759 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003760 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003761 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003762
Richard Smith9f690bd2015-10-27 06:02:45 +00003763 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3764 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3765
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003766 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003767}
3768
John McCalldadc5752010-08-24 06:29:42 +00003769StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003770Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003771 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003772 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003773 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003774 if (Var && Var->isInvalidDecl())
3775 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003777 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003778}
3779
John McCalldadc5752010-08-24 06:29:42 +00003780StmtResult
John McCallb268a282010-08-23 23:25:46 +00003781Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003782 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003783}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003784
John McCalldadc5752010-08-24 06:29:42 +00003785StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003787 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003788 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003789 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3790
Reid Kleckner87a31802018-03-12 21:43:02 +00003791 setFunctionHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003792 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003793 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3794 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003795}
3796
John McCall0bd3e402012-05-08 21:41:25 +00003797StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003798 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003799 ExprResult Result = DefaultLvalueConversion(Throw);
3800 if (Result.isInvalid())
3801 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003802
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003803 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003804 if (Result.isInvalid())
3805 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003806 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003807
Douglas Gregor2900c162010-04-22 21:44:01 +00003808 QualType ThrowType = Throw->getType();
3809 // Make sure the expression type is an ObjC pointer or "void *".
3810 if (!ThrowType->isDependentType() &&
3811 !ThrowType->isObjCObjectPointerType()) {
3812 const PointerType *PT = ThrowType->getAs<PointerType>();
3813 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003814 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003815 << Throw->getType() << Throw->getSourceRange());
3816 }
3817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003819 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003820}
3821
John McCalldadc5752010-08-24 06:29:42 +00003822StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003824 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003825 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003826 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3827
John McCallb268a282010-08-23 23:25:46 +00003828 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003829 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003830 // in the context of an @catch clause).
3831 Scope *AtCatchParent = CurScope;
3832 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3833 AtCatchParent = AtCatchParent->getParent();
3834 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003835 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 }
John McCallb268a282010-08-23 23:25:46 +00003837 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003838}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003839
John McCalld9bb7432011-07-27 21:50:02 +00003840ExprResult
3841Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3842 ExprResult result = DefaultLvalueConversion(operand);
3843 if (result.isInvalid())
3844 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003845 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003846
3847 // Make sure the expression type is an ObjC pointer or "void *".
3848 QualType type = operand->getType();
3849 if (!type->isDependentType() &&
3850 !type->isObjCObjectPointerType()) {
3851 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003852 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3853 if (getLangOpts().CPlusPlus) {
3854 if (RequireCompleteType(atLoc, type,
3855 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003856 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003857 << type << operand->getSourceRange();
3858
3859 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003860 if (result.isInvalid())
3861 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003862 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003863 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003864 << type << operand->getSourceRange();
3865
3866 operand = result.get();
3867 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003868 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003869 << type << operand->getSourceRange();
3870 }
3871 }
John McCalld9bb7432011-07-27 21:50:02 +00003872 }
3873
3874 // The operand to @synchronized is a full-expression.
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003875 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
John McCalld9bb7432011-07-27 21:50:02 +00003876}
3877
John McCalldadc5752010-08-24 06:29:42 +00003878StmtResult
John McCallb268a282010-08-23 23:25:46 +00003879Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3880 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003881 // We can't jump into or indirect-jump out of a @synchronized block.
Reid Kleckner87a31802018-03-12 21:43:02 +00003882 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003883 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003884}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003885
3886/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3887/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003888StmtResult
John McCall48871652010-08-21 09:40:31 +00003889Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003890 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003891 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003892 return new (Context)
3893 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003894}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003895
John McCall31168b02011-06-15 23:02:42 +00003896StmtResult
3897Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
Reid Kleckner87a31802018-03-12 21:43:02 +00003898 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003899 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003900}
3901
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003902namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003903class CatchHandlerType {
3904 QualType QT;
3905 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003906
Aaron Ballman8aee642902015-04-08 00:05:29 +00003907 // This is a special constructor to be used only with DenseMapInfo's
3908 // getEmptyKey() and getTombstoneKey() functions.
3909 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3910 enum Unique { ForDenseMap };
3911 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3912
Sebastian Redl63c4da02009-07-29 17:15:45 +00003913public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003914 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003915 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003916 /// level pointer and cv-qualifiers.
3917 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3918 if (QT->isPointerType())
3919 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003920
Aaron Ballman8aee642902015-04-08 00:05:29 +00003921 if (IsPointer || QT->isReferenceType())
3922 QT = QT->getPointeeType();
3923 QT = QT.getUnqualifiedType();
3924 }
3925
3926 /// Used when creating a CatchHandlerType from a base class type; pretends the
3927 /// type passed in had the pointer qualifier, does not need to get an
3928 /// unqualified type.
3929 CatchHandlerType(QualType QT, bool IsPointer)
3930 : QT(QT), IsPointer(IsPointer) {}
3931
3932 QualType underlying() const { return QT; }
3933 bool isPointer() const { return IsPointer; }
3934
3935 friend bool operator==(const CatchHandlerType &LHS,
3936 const CatchHandlerType &RHS) {
3937 // If the pointer qualification does not match, we can return early.
3938 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003939 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003940 // Otherwise, check the underlying type without cv-qualifiers.
3941 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003942 }
3943};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003944} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003945
Aaron Ballman8aee642902015-04-08 00:05:29 +00003946namespace llvm {
3947template <> struct DenseMapInfo<CatchHandlerType> {
3948 static CatchHandlerType getEmptyKey() {
3949 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3950 CatchHandlerType::ForDenseMap);
3951 }
3952
3953 static CatchHandlerType getTombstoneKey() {
3954 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3955 CatchHandlerType::ForDenseMap);
3956 }
3957
3958 static unsigned getHashValue(const CatchHandlerType &Base) {
3959 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3960 }
3961
3962 static bool isEqual(const CatchHandlerType &LHS,
3963 const CatchHandlerType &RHS) {
3964 return LHS == RHS;
3965 }
3966};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003967}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003968
3969namespace {
3970class CatchTypePublicBases {
3971 ASTContext &Ctx;
3972 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3973 const bool CheckAgainstPointer;
3974
3975 CXXCatchStmt *FoundHandler;
3976 CanQualType FoundHandlerType;
3977
3978public:
3979 CatchTypePublicBases(
3980 ASTContext &Ctx,
3981 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3982 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3983 FoundHandler(nullptr) {}
3984
3985 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3986 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3987
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003988 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003989 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003990 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003991 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003992 auto I = M.find(Check);
3993 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003994 FoundHandler = I->second;
3995 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003996 return true;
3997 }
3998 }
3999 return false;
4000 }
4001};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004002}
Dan Gohman28ade552010-07-26 21:25:24 +00004003
Sebastian Redl9b244a82008-12-22 21:35:02 +00004004/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4005/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00004006StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4007 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00004008 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004009 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +00004010 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +00004011 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +00004012 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
Alexey Bataevc416e642019-02-08 18:02:25 +00004013 }
Anders Carlsson68b36af2011-02-19 19:26:44 +00004014
Justin Lebar2a8db342016-09-28 22:45:54 +00004015 // Exceptions aren't allowed in CUDA device code.
4016 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00004017 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4018 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00004019
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004020 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4021 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4022
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004023 sema::FunctionScopeInfo *FSI = getCurFunction();
4024
Reid Klecknere7175912015-02-02 22:15:31 +00004025 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004026 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00004027 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004028 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00004029 }
4030
Robert Wilhelmcafda822013-08-22 09:20:03 +00004031 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00004032 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00004033 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00004034
Aaron Ballman8aee642902015-04-08 00:05:29 +00004035 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004036 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004037 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004038
Aaron Ballman8aee642902015-04-08 00:05:29 +00004039 // Diagnose when the handler is a catch-all handler, but it isn't the last
4040 // handler for the try block. [except.handle]p5. Also, skip exception
4041 // declarations that are invalid, since we can't usefully report on them.
4042 if (!H->getExceptionDecl()) {
4043 if (i < NumHandlers - 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004044 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00004045 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00004046 } else if (H->getExceptionDecl()->isInvalidDecl())
4047 continue;
4048
4049 // Walk the type hierarchy to diagnose when this type has already been
4050 // handled (duplication), or cannot be handled (derivation inversion). We
4051 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00004052 CatchHandlerType HandlerCHT =
4053 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00004054
4055 // We can ignore whether the type is a reference or a pointer; we need the
4056 // underlying declaration type in order to get at the underlying record
4057 // decl, if there is one.
4058 QualType Underlying = HandlerCHT.underlying();
4059 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4060 if (!RD->hasDefinition())
4061 continue;
4062 // Check that none of the public, unambiguous base classes are in the
4063 // map ([except.handle]p1). Give the base classes the same pointer
4064 // qualification as the original type we are basing off of. This allows
4065 // comparison against the handler type using the same top-level pointer
4066 // as the original type.
4067 CXXBasePaths Paths;
4068 Paths.setOrigin(RD);
4069 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004070 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004071 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4072 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4073 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4074 diag::warn_exception_caught_by_earlier_handler)
4075 << H->getCaughtType();
4076 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4077 diag::note_previous_exception_handler)
4078 << Problem->getCaughtType();
4079 }
4080 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00004081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
Aaron Ballman8aee642902015-04-08 00:05:29 +00004083 // Add the type the list of ones we have handled; diagnose if we've already
4084 // handled it.
4085 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4086 if (!R.second) {
4087 const CXXCatchStmt *Problem = R.first->second;
4088 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4089 diag::warn_exception_caught_by_earlier_handler)
4090 << H->getCaughtType();
4091 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4092 diag::note_previous_exception_handler)
4093 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00004094 }
4095 }
Mike Stump11289f42009-09-09 15:08:12 +00004096
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004097 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00004098
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004099 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00004100}
John Wiegley1c0675e2011-04-28 01:08:34 +00004101
Reid Klecknere7175912015-02-02 22:15:31 +00004102StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4103 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004104 assert(TryBlock && Handler);
4105
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004106 sema::FunctionScopeInfo *FSI = getCurFunction();
4107
Reid Klecknere7175912015-02-02 22:15:31 +00004108 // SEH __try is incompatible with C++ try. Borland appears to support this,
4109 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004110 if (!getLangOpts().Borland) {
4111 if (FSI->FirstCXXTryLoc.isValid()) {
4112 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4113 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4114 }
Reid Klecknere7175912015-02-02 22:15:31 +00004115 }
John Wiegley1c0675e2011-04-28 01:08:34 +00004116
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004117 FSI->setHasSEHTry(TryLoc);
4118
4119 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4120 // track if they use SEH.
4121 DeclContext *DC = CurContext;
4122 while (DC && !DC->isFunctionOrMethod())
4123 DC = DC->getParent();
4124 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4125 if (FD)
4126 FD->setUsesSEHTry(true);
4127 else
4128 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00004129
Reid Kleckner8819a402015-07-10 00:16:25 +00004130 // Reject __try on unsupported targets.
4131 if (!Context.getTargetInfo().isSEHTrySupported())
4132 Diag(TryLoc, diag::err_seh_try_unsupported);
4133
Reid Klecknere7175912015-02-02 22:15:31 +00004134 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00004135}
4136
4137StmtResult
4138Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4139 Expr *FilterExpr,
4140 Stmt *Block) {
4141 assert(FilterExpr && Block);
4142
4143 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00004144 return StmtError(Diag(FilterExpr->getExprLoc(),
4145 diag::err_filter_expression_integral)
4146 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00004147 }
4148
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004149 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004150}
4151
Nico Weberd64657f2015-03-09 02:47:59 +00004152void Sema::ActOnStartSEHFinallyBlock() {
4153 CurrentSEHFinally.push_back(CurScope);
4154}
4155
Nico Weberce903292015-03-09 03:17:15 +00004156void Sema::ActOnAbortSEHFinallyBlock() {
4157 CurrentSEHFinally.pop_back();
4158}
4159
Nico Weberd64657f2015-03-09 02:47:59 +00004160StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004161 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00004162 CurrentSEHFinally.pop_back();
4163 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004164}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004165
Nico Weberc7d05962014-07-06 22:32:59 +00004166StmtResult
4167Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00004168 Scope *SEHTryParent = CurScope;
4169 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4170 SEHTryParent = SEHTryParent->getParent();
4171 if (!SEHTryParent)
4172 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00004173 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00004174
Nico Weber9b982072014-07-07 00:12:30 +00004175 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00004176}
4177
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004178StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4179 bool IsIfExists,
4180 NestedNameSpecifierLoc QualifierLoc,
4181 DeclarationNameInfo NameInfo,
4182 Stmt *Nested)
4183{
4184 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004185 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004186 cast<CompoundStmt>(Nested));
4187}
4188
4189
Chad Rosier02a84392012-08-10 17:56:09 +00004190StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004191 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004192 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004193 UnqualifiedId &Name,
4194 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00004195 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004196 SS.getWithLocInContext(Context),
4197 GetNameFromUnqualifiedId(Name),
4198 Nested);
4199}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004200
4201RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00004202Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4203 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004204 DeclContext *DC = CurContext;
4205 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4206 DC = DC->getParent();
4207
Craig Topperc3ec1492014-05-26 06:22:03 +00004208 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004209 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004210 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4211 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004212 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004213 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004214
Alexey Bataev330de032014-10-29 12:21:55 +00004215 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004216 DC->addDecl(RD);
4217 RD->setImplicit();
4218 RD->startDefinition();
4219
Alexey Bataev9959db52014-05-06 10:08:46 +00004220 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004221 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004222 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004223 return RD;
4224}
4225
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004226static void
Richard Smith30116532019-05-28 23:09:46 +00004227buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4228 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4229 SmallVectorImpl<Expr *> &CaptureInits) {
4230 for (const sema::Capture &Cap : RSI->Captures) {
Richard Smith8cb63232019-05-28 23:09:44 +00004231 if (Cap.isInvalid())
4232 continue;
4233
Richard Smith30116532019-05-28 23:09:46 +00004234 // Create a field for this capture.
4235 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4236
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004237 if (Cap.isThisCapture()) {
4238 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004239 CapturedStmt::VCK_This));
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004240 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004241 continue;
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004242 } else if (Cap.isVLATypeCapture()) {
Alexey Bataev330de032014-10-29 12:21:55 +00004243 Captures.push_back(
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004244 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
Alexey Bataev330de032014-10-29 12:21:55 +00004245 CaptureInits.push_back(nullptr);
4246 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004247 }
4248
Richard Smith30116532019-05-28 23:09:46 +00004249 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4250 S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004251 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4252 Cap.isReferenceCapture()
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004253 ? CapturedStmt::VCK_ByRef
4254 : CapturedStmt::VCK_ByCopy,
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004255 Cap.getVariable()));
4256 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004257 }
4258}
4259
4260void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004261 CapturedRegionKind Kind,
4262 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004263 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004264 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004265
Alexey Bataev9959db52014-05-06 10:08:46 +00004266 // Build the context parameter
4267 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4268 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4269 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004270 auto *Param =
4271 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4272 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004273 DC->addDecl(Param);
4274
4275 CD->setContextParam(0, Param);
4276
4277 // Enter the capturing scope for this captured region.
4278 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4279
4280 if (CurScope)
4281 PushDeclContext(CurScope, CD);
4282 else
4283 CurContext = CD;
4284
Faisal Valid143a0c2017-04-01 21:30:49 +00004285 PushExpressionEvaluationContext(
4286 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004287}
4288
4289void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4290 CapturedRegionKind Kind,
4291 ArrayRef<CapturedParamNameType> Params) {
4292 CapturedDecl *CD = nullptr;
4293 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4294
4295 // Build the context parameter
4296 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4297 bool ContextIsFound = false;
4298 unsigned ParamNum = 0;
4299 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4300 E = Params.end();
4301 I != E; ++I, ++ParamNum) {
4302 if (I->second.isNull()) {
4303 assert(!ContextIsFound &&
4304 "null type has been found already for '__context' parameter");
4305 IdentifierInfo *ParamName = &Context.Idents.get("__context");
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004306 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4307 .withConst()
4308 .withRestrict();
Alexey Bataev56223232017-06-09 13:40:18 +00004309 auto *Param =
4310 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4311 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004312 DC->addDecl(Param);
4313 CD->setContextParam(ParamNum, Param);
4314 ContextIsFound = true;
4315 } else {
4316 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004317 auto *Param =
4318 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4319 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004320 DC->addDecl(Param);
4321 CD->setParam(ParamNum, Param);
4322 }
4323 }
4324 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004325 if (!ContextIsFound) {
4326 // Add __context implicitly if it is not specified.
4327 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4328 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004329 auto *Param =
4330 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4331 ImplicitParamDecl::CapturedContext);
Alexey Bataev301a2d92014-05-14 10:40:54 +00004332 DC->addDecl(Param);
4333 CD->setContextParam(ParamNum, Param);
4334 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004335 // Enter the capturing scope for this captured region.
4336 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4337
4338 if (CurScope)
4339 PushDeclContext(CurScope, CD);
4340 else
4341 CurContext = CD;
4342
Faisal Valid143a0c2017-04-01 21:30:49 +00004343 PushExpressionEvaluationContext(
4344 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004345}
4346
Wei Pan17fbf6e2013-05-04 03:59:06 +00004347void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004348 DiscardCleanupsInEvaluationContext();
4349 PopExpressionEvaluationContext();
4350
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004351 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4352 RecordDecl *Record = RSI->TheRecordDecl;
4353 Record->setInvalidDecl();
4354
Aaron Ballman62e47c42014-03-10 13:43:55 +00004355 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004356 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00004357 SourceLocation(), SourceLocation(), ParsedAttributesView());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004358
Wei Pan17fbf6e2013-05-04 03:59:06 +00004359 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004360 PopFunctionScopeInfo();
4361}
4362
4363StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4364 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4365
4366 SmallVector<CapturedStmt::Capture, 4> Captures;
4367 SmallVector<Expr *, 4> CaptureInits;
Richard Smith30116532019-05-28 23:09:46 +00004368 buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004369
4370 CapturedDecl *CD = RSI->TheCapturedDecl;
4371 RecordDecl *RD = RSI->TheRecordDecl;
4372
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004373 CapturedStmt *Res = CapturedStmt::Create(
4374 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4375 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004376
4377 CD->setBody(Res->getCapturedStmt());
4378 RD->completeDefinition();
4379
Wei Pan17fbf6e2013-05-04 03:59:06 +00004380 DiscardCleanupsInEvaluationContext();
4381 PopExpressionEvaluationContext();
4382
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004383 PopDeclContext();
4384 PopFunctionScopeInfo();
4385
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004386 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004387}