blob: 07af218b77ce0f719b57963bb5ef1ff0dc13e48d [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
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000014#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000015#include "clang/AST/ASTDiagnostic.h"
Richard Smith50e291e2018-01-02 23:52:42 +000016#include "clang/AST/ASTLambda.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000040
Chris Lattneraf8d5812006-11-10 05:07:45 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000043
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000044StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
Richard Smith945f8d32013-01-14 22:39:08 +000045 if (FE.isInvalid())
46 return StmtError();
47
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000048 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
Richard Smith945f8d32013-01-14 22:39:08 +000049 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000050 return StmtError();
51
Chris Lattner903eb512008-07-25 23:18:17 +000052 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
53 // void expression for its side effects. Conversion to void allows any
54 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000055
Chris Lattner903eb512008-07-25 23:18:17 +000056 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000057 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000058}
59
60
John McCalleaef89b2013-03-22 02:10:40 +000061StmtResult Sema::ActOnExprStmtError() {
62 DiscardCleanupsInEvaluationContext();
63 return StmtError();
64}
65
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000066StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000067 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000068 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000069}
70
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000071StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
72 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000073 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattnercbafe8d2009-04-12 20:13:14 +000075 // If we have an invalid decl, just return an error.
76 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000077
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000078 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000079}
Chris Lattneraf8d5812006-11-10 05:07:45 +000080
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000081void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000082 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000083
Douglas Gregor2eb1c572013-04-08 20:52:24 +000084 // If we don't have a declaration, or we have an invalid declaration,
85 // just return.
86 if (DG.isNull() || !DG.isSingleDecl())
87 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000088
Douglas Gregor2eb1c572013-04-08 20:52:24 +000089 Decl *decl = DG.getSingleDecl();
90 if (!decl || decl->isInvalidDecl())
91 return;
92
93 // Only variable declarations are permitted.
94 VarDecl *var = dyn_cast<VarDecl>(decl);
95 if (!var) {
96 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
97 decl->setInvalidDecl();
98 return;
99 }
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // foreach variables are never actually initialized in the way that
102 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000103 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000104
John McCalld4631322011-06-17 06:42:21 +0000105 // In ARC, we don't need to retain the iteration variable of a fast
106 // enumeration loop. Rather than actually trying to catch that
107 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000108 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000109 QualType type = var->getType();
110
111 // Only do this if we inferred the lifetime. Inferred lifetime
112 // will show up as a local qualifier because explicit lifetime
113 // should have shown up as an AttributedType instead.
114 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
115 // Add 'const' and mark the variable as pseudo-strong.
116 var->setType(type.withConst());
117 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000118 }
119 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000120}
121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000122/// Diagnose unused comparisons, both builtin and overloaded operators.
Richard Trieu99e1c952014-03-11 03:11:08 +0000123/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124///
125/// Adding a cast to void (or other expression wrappers) will prevent the
126/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000127static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000128 SourceLocation Loc;
Richard Smithc70f1d62017-12-14 15:16:18 +0000129 bool CanAssign;
130 enum { Equality, Inequality, Relational, ThreeWay } Kind;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000133 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000134 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135
Richard Smithc70f1d62017-12-14 15:16:18 +0000136 if (Op->getOpcode() == BO_EQ)
137 Kind = Equality;
138 else if (Op->getOpcode() == BO_NE)
139 Kind = Inequality;
140 else if (Op->getOpcode() == BO_Cmp)
141 Kind = ThreeWay;
142 else {
143 assert(Op->isRelationalOp());
144 Kind = Relational;
145 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000146 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000147 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000148 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000149 switch (Op->getOperator()) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000150 case OO_EqualEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000151 Kind = Equality;
152 break;
Richard Trieu99e1c952014-03-11 03:11:08 +0000153 case OO_ExclaimEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000154 Kind = Inequality;
Richard Trieu99e1c952014-03-11 03:11:08 +0000155 break;
156 case OO_Less:
157 case OO_Greater:
158 case OO_GreaterEqual:
159 case OO_LessEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000160 Kind = Relational;
Richard Trieu99e1c952014-03-11 03:11:08 +0000161 break;
Richard Smithc70f1d62017-12-14 15:16:18 +0000162 case OO_Spaceship:
163 Kind = ThreeWay;
164 break;
165 default:
166 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000167 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000168
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000169 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000170 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171 } else {
172 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000173 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000174 }
175
176 // Suppress warnings when the operator, suspicious as it may be, comes from
177 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000178 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000179 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000180
Chandler Carruthe2669392011-08-17 09:34:37 +0000181 S.Diag(Loc, diag::warn_unused_comparison)
Richard Smithc70f1d62017-12-14 15:16:18 +0000182 << (unsigned)Kind << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000183
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000184 // If the LHS is a plausible entity to assign to, provide a fixit hint to
185 // correct common typos.
Richard Smithc70f1d62017-12-14 15:16:18 +0000186 if (CanAssign) {
187 if (Kind == Inequality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000188 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
189 << FixItHint::CreateReplacement(Loc, "|=");
Richard Smithc70f1d62017-12-14 15:16:18 +0000190 else if (Kind == Equality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000191 S.Diag(Loc, diag::note_equality_comparison_to_assign)
192 << FixItHint::CreateReplacement(Loc, "=");
193 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000194
195 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000196}
197
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000198void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000199 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
200 return DiagnoseUnusedExprResult(Label->getSubStmt());
201
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000202 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000203 if (!E)
204 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000205
206 // If we are in an unevaluated expression context, then there can be no unused
207 // results because the results aren't expected to be used in the first place.
208 if (isUnevaluatedContext())
209 return;
210
Nico Weber0e631632015-10-27 19:47:40 +0000211 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000212 // In most cases, we don't want to warn if the expression is written in a
213 // macro body, or if the macro comes from a system header. If the offending
214 // expression is a call to a function with the warn_unused_result attribute,
215 // we warn no matter the location. Because of the order in which the various
216 // checks need to happen, we factor out the macro-related test here.
Fangrui Song6907ce22018-07-30 19:24:48 +0000217 bool ShouldSuppress =
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000218 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
219 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000220
Eli Friedmanc11535c2012-05-24 00:47:05 +0000221 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000222 SourceLocation Loc;
223 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000224 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000225 return;
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner6dc7e572012-08-31 22:39:21 +0000227 // If this is a GNU statement expression expanded from a macro, it is probably
228 // unused because it is a function-like macro that can be used as either an
229 // expression or statement. Don't warn, because it is almost certainly a
230 // false positive.
231 if (isa<StmtExpr>(E) && Loc.isMacroID())
232 return;
233
Nico Weber0e631632015-10-27 19:47:40 +0000234 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
235 // That macro is frequently used to suppress "unused parameter" warnings,
236 // but its implementation makes clang's -Wunused-value fire. Prevent this.
237 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
238 SourceLocation SpellLoc = Loc;
239 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
240 return;
241 }
242
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000243 // Okay, we have an unused result. Depending on what the base expression is,
244 // we might want to make a more specific diagnostic. Check for one of these
245 // cases now.
246 unsigned DiagID = diag::warn_unused_expr;
Bill Wendling7c44da22018-10-31 03:48:47 +0000247 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000248 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000249 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
250 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000251
Chandler Carruthe2669392011-08-17 09:34:37 +0000252 if (DiagnoseUnusedComparison(*this, E))
253 return;
254
Eli Friedmanc11535c2012-05-24 00:47:05 +0000255 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000256 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000257 if (E->getType()->isVoidType())
258 return;
259
Aaron Ballmand23e9bc2019-01-03 14:24:31 +0000260 if (const Attr *A = CE->getUnusedResultAttr(Context)) {
261 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
262 return;
263 }
264
Chris Lattner1a6babf2009-10-13 04:53:48 +0000265 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000266 // a more specific message to make it clear what is happening. If the call
267 // is written in a macro body, only warn if it has the warn_unused_result
268 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000269 if (const Decl *FD = CE->getCalleeDecl()) {
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000270 if (ShouldSuppress)
271 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000272 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000273 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
274 return;
275 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000276 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000277 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
278 return;
279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000281 } else if (ShouldSuppress)
282 return;
283
284 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000285 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000286 Diag(Loc, diag::err_arc_unused_init_message) << R1;
287 return;
288 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000289 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000290 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000291 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
292 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000293 return;
294 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000295 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000296 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
297 const Expr *Source = POE->getSyntacticForm();
298 if (isa<ObjCSubscriptRefExpr>(Source))
299 DiagID = diag::warn_unused_container_subscript_expr;
300 else
301 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000302 } else if (const CXXFunctionalCastExpr *FC
303 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000304 const Expr *E = FC->getSubExpr();
305 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
306 E = TE->getSubExpr();
307 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000308 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000309 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
310 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
311 if (!RD->getAttr<WarnUnusedAttr>())
312 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000313 }
John McCall2351cb92010-04-06 22:24:14 +0000314 // Diagnose "(void*) blah" as a typo for "(void) blah".
315 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
316 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
317 QualType T = TI->getType();
318
319 // We really do want to use the non-canonical type here.
320 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000321 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000322
323 Diag(Loc, diag::warn_unused_voidptr)
324 << FixItHint::CreateRemoval(TL.getStarLoc());
325 return;
326 }
327 }
328
Eli Friedmanc11535c2012-05-24 00:47:05 +0000329 if (E->isGLValue() && E->getType().isVolatileQualified()) {
330 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
331 return;
332 }
333
Craig Topperc3ec1492014-05-26 06:22:03 +0000334 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000335}
336
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000337void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
338 PushCompoundScope(IsStmtExpr);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000339}
340
341void Sema::ActOnFinishOfCompoundStmt() {
342 PopCompoundScope();
343}
344
345sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
346 return getCurFunction()->CompoundScopes.back();
347}
348
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000349StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
350 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
351 const unsigned NumElts = Elts.size();
352
Chris Lattnerd864daf2007-08-27 04:29:41 +0000353 // If we're in C89 mode, check that we don't have any decls after stmts. If
354 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000355 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000356 // Note that __extension__ can be around a decl.
357 unsigned i = 0;
358 // Skip over all declarations.
359 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
360 /*empty*/;
361
362 // We found the end of the list or a statement. Scan for another declstmt.
363 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
364 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000365
Chris Lattnerd864daf2007-08-27 04:29:41 +0000366 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000367 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000368 Diag(D->getLocation(), diag::ext_mixed_decls_code);
369 }
370 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000371
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000372 // Check for suspicious empty body (null statement) in `for' and `while'
373 // statements. Don't do anything for template instantiations, this just adds
374 // noise.
375 if (NumElts != 0 && !CurrentInstantiationScope &&
376 getCurCompoundScope().HasEmptyLoopBodies) {
377 for (unsigned i = 0; i != NumElts - 1; ++i)
378 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
379 }
380
Benjamin Kramer07420902017-12-24 16:24:20 +0000381 return CompoundStmt::Create(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000382}
383
Richard Smithef6c43d2018-07-26 18:41:30 +0000384ExprResult
385Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
386 if (!Val.get())
387 return Val;
388
389 if (DiagnoseUnexpandedParameterPack(Val.get()))
390 return ExprError();
391
392 // If we're not inside a switch, let the 'case' statement handling diagnose
393 // this. Just clean up after the expression as best we can.
394 if (!getCurFunction()->SwitchStack.empty()) {
395 Expr *CondExpr =
396 getCurFunction()->SwitchStack.back().getPointer()->getCond();
397 if (!CondExpr)
398 return ExprError();
399 QualType CondType = CondExpr->getType();
400
401 auto CheckAndFinish = [&](Expr *E) {
402 if (CondType->isDependentType() || E->isTypeDependent())
403 return ExprResult(E);
404
405 if (getLangOpts().CPlusPlus11) {
406 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
407 // constant expression of the promoted type of the switch condition.
408 llvm::APSInt TempVal;
409 return CheckConvertedConstantExpression(E, CondType, TempVal,
410 CCEK_CaseValue);
411 }
412
413 ExprResult ER = E;
414 if (!E->isValueDependent())
415 ER = VerifyIntegerConstantExpression(E);
416 if (!ER.isInvalid())
417 ER = DefaultLvalueConversion(ER.get());
418 if (!ER.isInvalid())
419 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
420 return ER;
421 };
422
423 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
424 if (Converted.get() == Val.get())
425 Converted = CheckAndFinish(Val.get());
426 if (Converted.isInvalid())
427 return ExprError();
428 Val = Converted;
429 }
430
431 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
432 getLangOpts().CPlusPlus11);
433}
434
John McCalldadc5752010-08-24 06:29:42 +0000435StmtResult
Richard Smithef6c43d2018-07-26 18:41:30 +0000436Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
437 SourceLocation DotDotDotLoc, ExprResult RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000438 SourceLocation ColonLoc) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000439 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
440 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
441 : RHSVal.isInvalid() || RHSVal.get()) &&
442 "missing RHS value");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000443
John McCallaab3e412010-08-25 08:40:02 +0000444 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000445 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000446 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000447 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000448
Richard Smithef6c43d2018-07-26 18:41:30 +0000449 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
450 getCurFunction()->SwitchStack.back().setInt(true);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000451 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000452 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000453
Bruno Ricci5b30571752018-10-28 12:30:53 +0000454 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
455 CaseLoc, DotDotDotLoc, ColonLoc);
Richard Smithef6c43d2018-07-26 18:41:30 +0000456 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000458}
459
Chris Lattner34a22092009-03-04 04:23:07 +0000460/// ActOnCaseStmtBody - This installs a statement as the body of a case.
Aaron Ballmand9141742018-12-21 21:11:36 +0000461void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
Aaron Ballmand9141742018-12-21 21:11:36 +0000462 cast<CaseStmt>(S)->setSubStmt(SubStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000463}
464
John McCalldadc5752010-08-24 06:29:42 +0000465StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000466Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000467 Stmt *SubStmt, Scope *CurScope) {
John McCallaab3e412010-08-25 08:40:02 +0000468 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000469 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000470 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000471 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000472
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000473 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Richard Smithef6c43d2018-07-26 18:41:30 +0000474 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000475 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000476}
477
John McCalldadc5752010-08-24 06:29:42 +0000478StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000479Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
480 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000481 // If the label was multiply defined, reject it now.
482 if (TheDecl->getStmt()) {
483 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
484 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000485 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000486 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000487
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000488 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000489 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
490 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000491 if (!TheDecl->isGnuLocal()) {
492 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000493 if (!TheDecl->isMSAsmLabel()) {
494 // Don't update the location of MS ASM labels. These will result in
495 // a diagnostic, and changing the location here will mess that up.
496 TheDecl->setLocation(IdentLoc);
497 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000498 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000499 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000500}
501
Richard Smithc202b282012-04-14 00:33:13 +0000502StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000503 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000504 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000505 // Fill in the declaration and return it.
506 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000507 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000508}
509
Richard Trieufaca2d82016-02-18 23:58:40 +0000510namespace {
511class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
512 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
513 Sema &SemaRef;
514public:
515 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
516 void VisitBinaryOperator(BinaryOperator *E) {
517 if (E->getOpcode() == BO_Comma)
518 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
519 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
520 }
521};
522}
523
John McCalldadc5752010-08-24 06:29:42 +0000524StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000525Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
526 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000527 Stmt *thenStmt, SourceLocation ElseLoc,
528 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000529 if (Cond.isInvalid())
530 Cond = ConditionResult(
531 *this, nullptr,
532 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
533 Context.BoolTy, VK_RValue),
534 IfLoc),
535 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000536
Richard Smithb130fe72016-06-23 19:16:49 +0000537 Expr *CondExpr = Cond.get().second;
Richard Trieuf3713802018-10-25 01:08:00 +0000538 // Only call the CommaVisitor when not C89 due to differences in scope flags.
539 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
540 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
Richard Smithb130fe72016-06-23 19:16:49 +0000541 CommaVisitor(*this).Visit(CondExpr);
542
Hans Wennborg59ad1502017-11-20 17:48:54 +0000543 if (!elseStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000544 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
Hans Wennborg95419752017-11-20 17:38:16 +0000545 diag::warn_empty_if_body);
Richard Smithb130fe72016-06-23 19:16:49 +0000546
Richard Smitha547eb22016-07-14 00:11:03 +0000547 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
548 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000549}
550
551StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000552 Stmt *InitStmt, ConditionResult Cond,
553 Stmt *thenStmt, SourceLocation ElseLoc,
554 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000555 if (Cond.isInvalid())
556 return StmtError();
557
Erik Pilkington5cd57172016-08-16 17:44:11 +0000558 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Reid Kleckner87a31802018-03-12 21:43:02 +0000559 setFunctionHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000560
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000561 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
562 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000563}
Steve Naroff86272ea2007-05-29 02:14:17 +0000564
Chris Lattner67998452007-08-23 18:29:20 +0000565namespace {
566 struct CaseCompareFunctor {
567 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
568 const llvm::APSInt &RHS) {
569 return LHS.first < RHS;
570 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000571 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
572 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
573 return LHS.first < RHS.first;
574 }
Chris Lattner67998452007-08-23 18:29:20 +0000575 bool operator()(const llvm::APSInt &LHS,
576 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
577 return LHS < RHS.first;
578 }
579 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000580}
Chris Lattner67998452007-08-23 18:29:20 +0000581
Chris Lattner4b2ff022007-09-21 18:15:22 +0000582/// CmpCaseVals - Comparison predicate for sorting case values.
583///
584static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
585 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
586 if (lhs.first < rhs.first)
587 return true;
588
589 if (lhs.first == rhs.first &&
590 lhs.second->getCaseLoc().getRawEncoding()
591 < rhs.second->getCaseLoc().getRawEncoding())
592 return true;
593 return false;
594}
595
Douglas Gregorbd6839732010-02-08 22:24:16 +0000596/// CmpEnumVals - Comparison predicate for sorting enumeration values.
597///
598static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
599 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
600{
601 return lhs.first < rhs.first;
602}
603
604/// EqEnumVals - Comparison preficate for uniqing enumeration values.
605///
606static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
607 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
608{
609 return lhs.first == rhs.first;
610}
611
Chris Lattnera96d4272009-10-16 16:45:22 +0000612/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
613/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000614static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000615 if (const auto *FE = dyn_cast<FullExpr>(E))
616 E = FE->getSubExpr();
Gabor Horvath64c32412017-08-09 08:57:09 +0000617 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
618 if (ImpCast->getCastKind() != CK_IntegralCast) break;
619 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000620 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000621 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000622}
623
Richard Smith03a4aa32016-06-23 19:02:52 +0000624ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000625 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
626 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000627
Douglas Gregore2b37442012-05-04 22:38:52 +0000628 public:
629 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000630 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
631 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000632
Craig Toppere14c0f82014-03-12 04:55:44 +0000633 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
634 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000635 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
636 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000637
Craig Toppere14c0f82014-03-12 04:55:44 +0000638 SemaDiagnosticBuilder diagnoseIncomplete(
639 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000640 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
641 << T << Cond->getSourceRange();
642 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000643
Craig Toppere14c0f82014-03-12 04:55:44 +0000644 SemaDiagnosticBuilder diagnoseExplicitConv(
645 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000646 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
647 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000648
Craig Toppere14c0f82014-03-12 04:55:44 +0000649 SemaDiagnosticBuilder noteExplicitConv(
650 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000651 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
652 << ConvTy->isEnumeralType() << ConvTy;
653 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000654
Craig Toppere14c0f82014-03-12 04:55:44 +0000655 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
656 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000657 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
658 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000659
Craig Toppere14c0f82014-03-12 04:55:44 +0000660 SemaDiagnosticBuilder noteAmbiguous(
661 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000662 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
663 << ConvTy->isEnumeralType() << ConvTy;
664 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000665
Craig Toppere14c0f82014-03-12 04:55:44 +0000666 SemaDiagnosticBuilder diagnoseConversion(
667 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000668 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000669 }
670 } SwitchDiagnoser(Cond);
671
Richard Smith03a4aa32016-06-23 19:02:52 +0000672 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000673 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000674 if (CondResult.isInvalid())
675 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676
Richard Smithef6c43d2018-07-26 18:41:30 +0000677 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
678 // failed and produced a diagnostic.
679 Cond = CondResult.get();
680 if (!Cond->isTypeDependent() &&
681 !Cond->getType()->isIntegralOrEnumerationType())
682 return ExprError();
683
John McCall5939b162011-08-06 07:30:58 +0000684 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smithef6c43d2018-07-26 18:41:30 +0000685 return UsualUnaryConversions(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +0000686}
John McCall5939b162011-08-06 07:30:58 +0000687
Richard Smithc7a05a92016-06-29 21:17:59 +0000688StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
689 Stmt *InitStmt, ConditionResult Cond) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000690 Expr *CondExpr = Cond.get().second;
691 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
692
693 if (CondExpr && !CondExpr->isTypeDependent()) {
694 // We have already converted the expression to an integral or enumeration
695 // type, when we parsed the switch condition. If we don't have an
696 // appropriate type now, enter the switch scope but remember that it's
697 // invalid.
698 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
699 "invalid condition type");
700 if (CondExpr->isKnownToHaveBooleanValue()) {
701 // switch(bool_expr) {...} is often a programmer error, e.g.
702 // switch(n && mask) { ... } // Doh - should be "n & mask".
703 // One can always use an if statement instead of switch(bool_expr).
704 Diag(SwitchLoc, diag::warn_bool_switch_condition)
705 << CondExpr->getSourceRange();
706 }
707 }
John McCalla95172b2010-08-01 00:26:45 +0000708
Reid Kleckner87a31802018-03-12 21:43:02 +0000709 setFunctionHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710
Bruno Riccie2806f82018-10-29 16:12:37 +0000711 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
Richard Smithef6c43d2018-07-26 18:41:30 +0000712 getCurFunction()->SwitchStack.push_back(
713 FunctionScopeInfo::SwitchInfo(SS, false));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000714 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000715}
716
Gabor Greif16e02862010-10-01 22:05:14 +0000717static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000718 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000719 Val.setIsSigned(IsSigned);
720}
721
Richard Smith077d0832014-08-04 00:40:48 +0000722/// Check the specified case value is in range for the given unpromoted switch
723/// type.
724static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
725 unsigned UnpromotedWidth, bool UnpromotedSign) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000726 // In C++11 onwards, this is checked by the language rules.
727 if (S.getLangOpts().CPlusPlus11)
728 return;
729
Richard Smith077d0832014-08-04 00:40:48 +0000730 // If the case value was signed and negative and the switch expression is
731 // unsigned, don't bother to warn: this is implementation-defined behavior.
732 // FIXME: Introduce a second, default-ignored warning for this case?
733 if (UnpromotedWidth < Val.getBitWidth()) {
734 llvm::APSInt ConvVal(Val);
735 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
736 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
737 // FIXME: Use different diagnostics for overflow in conversion to promoted
738 // type versus "switch expression cannot have this value". Use proper
739 // IntRange checking rather than just looking at the unpromoted type here.
740 if (ConvVal != Val)
741 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
742 << ConvVal.toString(10);
743 }
744}
745
Alexis Hunt724f14e2014-11-28 00:53:20 +0000746typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
747
Dmitri Gribenko58683752013-12-05 22:52:07 +0000748/// Returns true if we should emit a diagnostic about this case expression not
749/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000750static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000751 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000752 const Expr *CaseExpr,
753 EnumValsTy::iterator &EI,
754 EnumValsTy::iterator &EIEnd,
755 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000756 if (!ED->isClosed())
757 return false;
758
Alexis Hunt724f14e2014-11-28 00:53:20 +0000759 if (const DeclRefExpr *DRE =
760 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000761 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000762 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000763 QualType EnumType = S.Context.getTypeDeclType(ED);
764 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
765 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000766 return false;
767 }
768 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000769
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000770 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000771 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000772
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000773 while (EI != EIEnd && EI->first < Val)
774 EI++;
775
776 if (EI != EIEnd && EI->first == Val)
777 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000778
Dmitri Gribenko58683752013-12-05 22:52:07 +0000779 return true;
780}
781
Gabor Horvath64c32412017-08-09 08:57:09 +0000782static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
783 const Expr *Case) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000784 QualType CondType = Cond->getType();
Gabor Horvath64c32412017-08-09 08:57:09 +0000785 QualType CaseType = Case->getType();
786
787 const EnumType *CondEnumType = CondType->getAs<EnumType>();
788 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
789 if (!CondEnumType || !CaseEnumType)
790 return;
791
Gabor Horvathb57e2642017-08-09 12:34:58 +0000792 // Ignore anonymous enums.
Richard Trieu285c9362017-09-09 00:25:05 +0000793 if (!CondEnumType->getDecl()->getIdentifier() &&
794 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000795 return;
Richard Trieu285c9362017-09-09 00:25:05 +0000796 if (!CaseEnumType->getDecl()->getIdentifier() &&
797 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000798 return;
799
Gabor Horvath64c32412017-08-09 08:57:09 +0000800 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
801 return;
802
Gabor Horvath0284a202017-08-09 20:56:43 +0000803 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000804 << CondType << CaseType << Cond->getSourceRange()
805 << Case->getSourceRange();
806}
807
John McCalldadc5752010-08-24 06:29:42 +0000808StmtResult
John McCallb268a282010-08-23 23:25:46 +0000809Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
810 Stmt *BodyStmt) {
811 SwitchStmt *SS = cast<SwitchStmt>(Switch);
Richard Smithef6c43d2018-07-26 18:41:30 +0000812 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
813 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
John McCallaab3e412010-08-25 08:40:02 +0000814 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000815
David Majnemer418ad3f2014-12-15 07:46:12 +0000816 getCurFunction()->SwitchStack.pop_back();
817
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000818 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000819 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000820
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000821 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000822 if (!CondExpr) return StmtError();
823
824 QualType CondType = CondExpr->getType();
825
Chris Lattnera96d4272009-10-16 16:45:22 +0000826 // C++ 6.4.2.p2:
827 // Integral promotions are performed (on the switch condition).
828 //
829 // A case value unrepresentable by the original switch condition
830 // type (before the promotion) doesn't make sense, even when it can
831 // be represented by the promoted type. Therefore we need to find
832 // the pre-promotion type of the switch condition.
Richard Smithef6c43d2018-07-26 18:41:30 +0000833 const Expr *CondExprBeforePromotion = CondExpr;
834 QualType CondTypeBeforePromotion =
835 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000836
Richard Smith077d0832014-08-04 00:40:48 +0000837 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000838 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000839 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000840 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000841 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
842 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
843
844 // Get the width and signedness that the condition might actually have, for
845 // warning purposes.
846 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
847 // type.
848 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000849 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000850 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000851 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000853 // Accumulate all of the case values in a vector so that we can sort them
854 // and detect duplicates. This vector contains the APInt for the case after
855 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000856 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000857 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000858
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000859 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000860 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
861 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Craig Topperc3ec1492014-05-26 06:22:03 +0000863 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000864
Chris Lattner10cb5e52007-08-23 06:23:56 +0000865 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000866
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000867 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000868 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000869
Anders Carlsson51873c22007-07-22 07:07:56 +0000870 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000871 if (TheDefaultStmt) {
872 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000873 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000874
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000875 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000876 // we'll return a valid AST. This requires recursing down the AST and
877 // finding it, not something we are set up to do right now. For now,
878 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000879 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000880 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000881 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000882
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000883 } else {
884 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000885
Chris Lattnera65e1f32008-01-16 19:17:22 +0000886 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000887
Richard Smithef6c43d2018-07-26 18:41:30 +0000888 if (Lo->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000889 HasDependentValue = true;
890 break;
891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
Richard Smithef6c43d2018-07-26 18:41:30 +0000893 // We already verified that the expression has a constant value;
894 // get that value (prior to conversions).
895 const Expr *LoBeforePromotion = Lo;
896 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
897 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000898
Richard Smith077d0832014-08-04 00:40:48 +0000899 // Check the unconverted value is within the range of possible values of
900 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000901 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
902 CondIsSignedBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000903
Richard Smithef6c43d2018-07-26 18:41:30 +0000904 // FIXME: This duplicates the check performed for warn_not_in_enum below.
905 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
906 LoBeforePromotion);
907
Richard Smith077d0832014-08-04 00:40:48 +0000908 // Convert the value to the same width/sign as the condition.
909 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000910
Chris Lattner10cb5e52007-08-23 06:23:56 +0000911 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000912 if (CS->getRHS()) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000913 if (CS->getRHS()->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000914 HasDependentValue = true;
915 break;
916 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000917 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000918 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000919 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000920 }
921 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000922
923 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000924 // If we don't have a default statement, check whether the
925 // condition is constant.
926 llvm::APSInt ConstantCondValue;
927 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000928 if (!HasDependentValue && !TheDefaultStmt) {
Fangrui Song407659a2018-11-30 23:41:18 +0000929 Expr::EvalResult Result;
930 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
Richard Smith077d0832014-08-04 00:40:48 +0000931 Expr::SE_AllowSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +0000932 if (Result.Val.isInt())
933 ConstantCondValue = Result.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +0000934 assert(!HasConstantCond ||
935 (ConstantCondValue.getBitWidth() == CondWidth &&
936 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000937 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000938 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000939
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000940 // Sort all the scalar case values so we can easily detect duplicates.
941 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
942
943 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000944 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
945 if (ShouldCheckConstantCond &&
946 CaseVals[i].first == ConstantCondValue)
947 ShouldCheckConstantCond = false;
948
949 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000950 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000951 // First, determine if either case value has a name
952 StringRef PrevString, CurrString;
953 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
954 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
955 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
956 PrevString = DeclRef->getDecl()->getName();
957 }
958 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
959 CurrString = DeclRef->getDecl()->getName();
960 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000961 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000962 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000963
964 if (PrevString == CurrString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000965 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
966 diag::err_duplicate_case)
967 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000968 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000969 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
970 diag::err_duplicate_case_differing_expr)
971 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
972 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
973 << CaseValStr;
Douglas Gregor9841df62012-05-16 05:32:58 +0000974
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000975 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000976 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000977 // FIXME: We really want to remove the bogus case stmt from the
978 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000979 CaseListIsErroneous = true;
980 }
981 }
982 }
Mike Stump11289f42009-09-09 15:08:12 +0000983
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000984 // Detect duplicate case ranges, which usually don't exist at all in
985 // the first place.
986 if (!CaseRanges.empty()) {
987 // Sort all the case ranges by their low value so we can easily detect
988 // overlaps between ranges.
989 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000990
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000991 // Scan the ranges, computing the high values and removing empty ranges.
992 std::vector<llvm::APSInt> HiVals;
993 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000994 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 CaseStmt *CR = CaseRanges[i].second;
996 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000997
Richard Smithef6c43d2018-07-26 18:41:30 +0000998 const Expr *HiBeforePromotion = Hi;
999 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1000 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001001
Richard Smith077d0832014-08-04 00:40:48 +00001002 // Check the unconverted value is within the range of possible values of
1003 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001004 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
Richard Smith077d0832014-08-04 00:40:48 +00001005 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1006
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001007 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001008 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001009
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001010 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001011 if (LoVal > HiVal) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001012 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001013 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001014 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001015 --i;
1016 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001017 continue;
1018 }
John McCalld3dfbd62010-05-18 03:19:21 +00001019
1020 if (ShouldCheckConstantCond &&
1021 LoVal <= ConstantCondValue &&
1022 ConstantCondValue <= HiVal)
1023 ShouldCheckConstantCond = false;
1024
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001025 HiVals.push_back(HiVal);
1026 }
Mike Stump11289f42009-09-09 15:08:12 +00001027
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001028 // Rescan the ranges, looking for overlap with singleton values and other
1029 // ranges. Since the range list is sorted, we only need to compare case
1030 // ranges with their neighbors.
1031 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1032 llvm::APSInt &CRLo = CaseRanges[i].first;
1033 llvm::APSInt &CRHi = HiVals[i];
1034 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001036 // Check to see whether the case range overlaps with any
1037 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001038 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001039 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001041 // Find the smallest value >= the lower bound. If I is in the
1042 // case range, then we have overlap.
1043 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1044 CaseVals.end(), CRLo,
1045 CaseCompareFunctor());
1046 if (I != CaseVals.end() && I->first < CRHi) {
1047 OverlapVal = I->first; // Found overlap with scalar.
1048 OverlapStmt = I->second;
1049 }
Mike Stump11289f42009-09-09 15:08:12 +00001050
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001051 // Find the smallest value bigger than the upper bound.
1052 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1053 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1054 OverlapVal = (I-1)->first; // Found overlap with scalar.
1055 OverlapStmt = (I-1)->second;
1056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001058 // Check to see if this case stmt overlaps with the subsequent
1059 // case range.
1060 if (i && CRLo <= HiVals[i-1]) {
1061 OverlapVal = HiVals[i-1]; // Found overlap with range.
1062 OverlapStmt = CaseRanges[i-1].second;
1063 }
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001065 if (OverlapStmt) {
1066 // If we have a duplicate, report it.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001067 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1068 << OverlapVal.toString(10);
1069 Diag(OverlapStmt->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001070 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001071 // FIXME: We really want to remove the bogus case stmt from the
1072 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001073 CaseListIsErroneous = true;
1074 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001075 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001076 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001077
John McCalld3dfbd62010-05-18 03:19:21 +00001078 // Complain if we have a constant condition and we didn't find a match.
Richard Smithef6c43d2018-07-26 18:41:30 +00001079 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1080 ShouldCheckConstantCond) {
John McCalld3dfbd62010-05-18 03:19:21 +00001081 // TODO: it would be nice if we printed enums as enums, chars as
1082 // chars, etc.
1083 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1084 << ConstantCondValue.toString(10)
1085 << CondExpr->getSourceRange();
1086 }
1087
1088 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001089 // values. We only issue a warning if there is not 'default:', but
1090 // we still do the analysis to preserve this information in the AST
1091 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001092 //
Chris Lattner51679082010-09-16 17:09:42 +00001093 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001094
Douglas Gregorbd6839732010-02-08 22:24:16 +00001095 // If switch has default case, then ignore it.
Richard Smithef6c43d2018-07-26 18:41:30 +00001096 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1097 ET && ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001098 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001099 EnumValsTy EnumVals;
1100
John McCalld3dfbd62010-05-18 03:19:21 +00001101 // Gather all enum values, set their type and sort them,
1102 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001103 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001104 llvm::APSInt Val = EDI->getInitVal();
1105 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001106 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001107 }
1108 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001109 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001110 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001111
1112 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001113 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001114 CI != CaseVals.end(); CI++) {
1115 Expr *CaseExpr = CI->second->getLHS();
1116 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1117 CI->first))
1118 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1119 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001120 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001121
David Blaikiee476f972012-01-22 02:31:55 +00001122 // See which of case ranges aren't in enum
1123 EI = EnumVals.begin();
1124 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001125 RI != CaseRanges.end(); RI++) {
1126 Expr *CaseExpr = RI->second->getLHS();
1127 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1128 RI->first))
1129 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1130 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001131
Chad Rosier02a84392012-08-10 17:56:09 +00001132 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001133 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1134 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001135
1136 CaseExpr = RI->second->getRHS();
1137 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1138 Hi))
1139 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1140 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142
Ted Kremenekc42f3452010-09-09 00:05:53 +00001143 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001144 auto CI = CaseVals.begin();
1145 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001146 bool hasCasesNotInSwitch = false;
1147
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001148 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001149
Erik Pilkington3e4e3b12018-09-05 19:13:27 +00001150 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1151 // Don't warn about omitted unavailable EnumConstantDecls.
1152 switch (EI->second->getAvailability()) {
1153 case AR_Deprecated:
1154 // Omitting a deprecated constant is ok; it should never materialize.
1155 case AR_Unavailable:
1156 continue;
1157
1158 case AR_NotYetIntroduced:
1159 // Partially available enum constants should be present. Note that we
1160 // suppress -Wunguarded-availability diagnostics for such uses.
1161 case AR_Available:
1162 break;
1163 }
1164
Chris Lattner51679082010-09-16 17:09:42 +00001165 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001166 while (CI != CaseVals.end() && CI->first < EI->first)
1167 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168
Douglas Gregorbd6839732010-02-08 22:24:16 +00001169 if (CI != CaseVals.end() && CI->first == EI->first)
1170 continue;
1171
Ted Kremenekc42f3452010-09-09 00:05:53 +00001172 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001173 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001174 llvm::APSInt Hi =
1175 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001176 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001177 if (EI->first <= Hi)
1178 break;
1179 }
1180
Ted Kremenekc42f3452010-09-09 00:05:53 +00001181 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001182 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001183 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001184 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001187 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001188 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001189
Chris Lattner51679082010-09-16 17:09:42 +00001190 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001191 if (!UnhandledNames.empty()) {
1192 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1193 TheDefaultStmt ? diag::warn_def_missing_case
1194 : diag::warn_missing_case)
1195 << (int)UnhandledNames.size();
1196
1197 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1198 I != E; ++I)
1199 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001200 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001201
1202 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001203 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001204 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001205 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001206
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001207 if (BodyStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001208 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001209 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001210
Mike Stump87c57ac2009-05-16 07:39:55 +00001211 // FIXME: If the case list was broken is some way, we don't have a good system
1212 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001213 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001214 return StmtError();
1215
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001216 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001217}
1218
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001219void
1220Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1221 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001222 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001223 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001224
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001225 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001226 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001227 SrcType->isIntegerType()) {
1228 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1229 SrcExpr->isIntegerConstantExpr(Context)) {
1230 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001231 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001232 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1233
1234 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001235 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001236 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001237
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001238 if (!ED->isClosed())
1239 return;
1240
Alexis Hunt724f14e2014-11-28 00:53:20 +00001241 if (ED->hasAttr<FlagEnumAttr>()) {
1242 if (!IsValueInFlagEnum(ED, RhsVal, true))
1243 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001244 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001245 } else {
1246 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1247 EnumValsTy;
1248 EnumValsTy EnumVals;
1249
1250 // Gather all enum values, set their type and sort them,
1251 // allowing easier comparison with rhs constant.
1252 for (auto *EDI : ED->enumerators()) {
1253 llvm::APSInt Val = EDI->getInitVal();
1254 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1255 EnumVals.push_back(std::make_pair(Val, EDI));
1256 }
1257 if (EnumVals.empty())
1258 return;
1259 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1260 EnumValsTy::iterator EIend =
1261 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1262
1263 // See which values aren't in the enum.
1264 EnumValsTy::const_iterator EI = EnumVals.begin();
1265 while (EI != EIend && EI->first < RhsVal)
1266 EI++;
1267 if (EI == EIend || EI->first != RhsVal) {
1268 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1269 << DstType.getUnqualifiedType();
1270 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001271 }
1272 }
1273 }
1274}
1275
Richard Smith03a4aa32016-06-23 19:02:52 +00001276StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1277 Stmt *Body) {
1278 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001279 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280
Richard Smith03a4aa32016-06-23 19:02:52 +00001281 auto CondVal = Cond.get();
1282 CheckBreakContinueBinding(CondVal.second);
1283
1284 if (CondVal.second &&
1285 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1286 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001287
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001288 if (isa<NullStmt>(Body))
1289 getCurCompoundScope().setHasEmptyLoopBodies();
1290
Bruno Riccibacf7512018-10-30 13:42:41 +00001291 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1292 WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001293}
1294
John McCalldadc5752010-08-24 06:29:42 +00001295StmtResult
John McCallb268a282010-08-23 23:25:46 +00001296Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001297 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001298 Expr *Cond, SourceLocation CondRParen) {
1299 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001300
Serge Pavlov09f99242014-01-23 15:05:00 +00001301 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001302 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001303 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001304 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001305 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001306
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001307 CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
John McCallb268a282010-08-23 23:25:46 +00001308 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001309 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001310 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311
Richard Trieuf3713802018-10-25 01:08:00 +00001312 // Only call the CommaVisitor for C89 due to differences in scope flags.
1313 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1314 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1315 CommaVisitor(*this).Visit(Cond);
1316
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001317 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001318}
1319
Richard Trieu451a5db2012-04-30 18:01:30 +00001320namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001321 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1322 using DeclSetVector =
1323 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1324 llvm::SmallPtrSet<VarDecl *, 8>>;
1325
Richard Trieu451a5db2012-04-30 18:01:30 +00001326 // This visitor will traverse a conditional statement and store all
1327 // the evaluated decls into a vector. Simple is set to true if none
1328 // of the excluded constructs are used.
1329 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001330 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001331 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001332 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001333 public:
1334 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001335
Richard Trieu5fb874a2017-06-02 04:24:46 +00001336 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001337 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001338 Inherited(S.Context),
1339 Decls(Decls),
1340 Ranges(Ranges),
1341 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001344
Richard Trieu9d228802013-05-31 22:46:45 +00001345 // Replaces the method in EvaluatedExprVisitor.
1346 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001347 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001348 }
1349
1350 // Any Stmt not whitelisted will cause the condition to be marked complex.
1351 void VisitStmt(Stmt *S) {
1352 Simple = false;
1353 }
1354
1355 void VisitBinaryOperator(BinaryOperator *E) {
1356 Visit(E->getLHS());
1357 Visit(E->getRHS());
1358 }
1359
1360 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001361 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001362 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001363
Richard Trieu9d228802013-05-31 22:46:45 +00001364 void VisitUnaryOperator(UnaryOperator *E) {
1365 // Skip checking conditionals with derefernces.
1366 if (E->getOpcode() == UO_Deref)
1367 Simple = false;
1368 else
1369 Visit(E->getSubExpr());
1370 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001371
Richard Trieu9d228802013-05-31 22:46:45 +00001372 void VisitConditionalOperator(ConditionalOperator *E) {
1373 Visit(E->getCond());
1374 Visit(E->getTrueExpr());
1375 Visit(E->getFalseExpr());
1376 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 void VisitParenExpr(ParenExpr *E) {
1379 Visit(E->getSubExpr());
1380 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001381
Richard Trieu9d228802013-05-31 22:46:45 +00001382 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1383 Visit(E->getOpaqueValue()->getSourceExpr());
1384 Visit(E->getFalseExpr());
1385 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001386
Richard Trieu9d228802013-05-31 22:46:45 +00001387 void VisitIntegerLiteral(IntegerLiteral *E) { }
1388 void VisitFloatingLiteral(FloatingLiteral *E) { }
1389 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1390 void VisitCharacterLiteral(CharacterLiteral *E) { }
1391 void VisitGNUNullExpr(GNUNullExpr *E) { }
1392 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001393
Richard Trieu9d228802013-05-31 22:46:45 +00001394 void VisitDeclRefExpr(DeclRefExpr *E) {
1395 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
Richard Trieu6b13e892018-10-20 02:15:58 +00001396 if (!VD) {
1397 // Don't allow unhandled Decl types.
1398 Simple = false;
1399 return;
1400 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001401
Richard Trieu9d228802013-05-31 22:46:45 +00001402 Ranges.push_back(E->getSourceRange());
1403
1404 Decls.insert(VD);
1405 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001406
1407 }; // end class DeclExtractor
1408
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001409 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001410 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001411 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001412 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001413 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001414
Richard Trieu9d228802013-05-31 22:46:45 +00001415 public:
1416 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001417
Richard Trieu5fb874a2017-06-02 04:24:46 +00001418 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001419 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1420 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001421
Richard Trieu9d228802013-05-31 22:46:45 +00001422 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001423 }
1424
Richard Trieu9d228802013-05-31 22:46:45 +00001425 void VisitReturnStmt(ReturnStmt *S) {
1426 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001427 }
1428
Richard Trieu9d228802013-05-31 22:46:45 +00001429 void VisitBreakStmt(BreakStmt *S) {
1430 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001431 }
1432
Richard Trieu9d228802013-05-31 22:46:45 +00001433 void VisitGotoStmt(GotoStmt *S) {
1434 FoundDecl = true;
1435 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001436
Richard Trieu9d228802013-05-31 22:46:45 +00001437 void VisitCastExpr(CastExpr *E) {
1438 if (E->getCastKind() == CK_LValueToRValue)
1439 CheckLValueToRValueCast(E->getSubExpr());
1440 else
1441 Visit(E->getSubExpr());
1442 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001443
Richard Trieu9d228802013-05-31 22:46:45 +00001444 void CheckLValueToRValueCast(Expr *E) {
1445 E = E->IgnoreParenImpCasts();
1446
1447 if (isa<DeclRefExpr>(E)) {
1448 return;
1449 }
1450
1451 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1452 Visit(CO->getCond());
1453 CheckLValueToRValueCast(CO->getTrueExpr());
1454 CheckLValueToRValueCast(CO->getFalseExpr());
1455 return;
1456 }
1457
1458 if (BinaryConditionalOperator *BCO =
1459 dyn_cast<BinaryConditionalOperator>(E)) {
1460 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1461 CheckLValueToRValueCast(BCO->getFalseExpr());
1462 return;
1463 }
1464
1465 Visit(E);
1466 }
1467
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
1469 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1470 if (Decls.count(VD))
1471 FoundDecl = true;
1472 }
1473
Steven Wu92910f62016-03-10 02:02:48 +00001474 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1475 // Only need to visit the semantics for POE.
1476 // SyntaticForm doesn't really use the Decal.
1477 for (auto *S : POE->semantics()) {
1478 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1479 // Look past the OVE into the expression it binds.
1480 Visit(OVE->getSourceExpr());
1481 else
1482 Visit(S);
1483 }
1484 }
1485
Richard Trieu9d228802013-05-31 22:46:45 +00001486 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001487
1488 }; // end class DeclMatcher
1489
1490 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1491 Expr *Third, Stmt *Body) {
1492 // Condition is empty
1493 if (!Second) return;
1494
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001495 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001496 Second->getBeginLoc()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001497 return;
1498
1499 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001500 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001501 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001502 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001503 DE.Visit(Second);
1504
1505 // Don't analyze complex conditionals.
1506 if (!DE.isSimple()) return;
1507
1508 // No decls found.
1509 if (Decls.size() == 0) return;
1510
Richard Trieu0030f1d2012-05-04 03:01:54 +00001511 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001512 for (auto *VD : Decls)
1513 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1514 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001515
1516 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1517 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1518 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1519 return;
1520
1521 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001522 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001523 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001524 } else {
1525 PDiag << (unsigned)Decls.size();
1526 for (auto *VD : Decls)
1527 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001528 }
1529
Richard Trieu5fb874a2017-06-02 04:24:46 +00001530 for (auto Range : Ranges)
1531 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001532
1533 S.Diag(Ranges.begin()->getBegin(), PDiag);
1534 }
1535
Richard Trieu4e7c9622013-08-06 21:31:54 +00001536 // If Statement is an incemement or decrement, return true and sets the
1537 // variables Increment and DRE.
1538 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1539 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001540 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1541 if (!Cleanups->cleanupsHaveSideEffects())
1542 Statement = Cleanups->getSubExpr();
1543
Richard Trieu4e7c9622013-08-06 21:31:54 +00001544 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1545 switch (UO->getOpcode()) {
1546 default: return false;
1547 case UO_PostInc:
1548 case UO_PreInc:
1549 Increment = true;
1550 break;
1551 case UO_PostDec:
1552 case UO_PreDec:
1553 Increment = false;
1554 break;
1555 }
1556 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1557 return DRE;
1558 }
1559
1560 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1561 FunctionDecl *FD = Call->getDirectCallee();
1562 if (!FD || !FD->isOverloadedOperator()) return false;
1563 switch (FD->getOverloadedOperator()) {
1564 default: return false;
1565 case OO_PlusPlus:
1566 Increment = true;
1567 break;
1568 case OO_MinusMinus:
1569 Increment = false;
1570 break;
1571 }
1572 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1573 return DRE;
1574 }
1575
1576 return false;
1577 }
1578
Serge Pavlov09f99242014-01-23 15:05:00 +00001579 // A visitor to determine if a continue or break statement is a
1580 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001581 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001582 SourceLocation BreakLoc;
1583 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001584 bool InSwitch = false;
1585
Richard Trieu4e7c9622013-08-06 21:31:54 +00001586 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001587 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001588 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001589 Visit(Body);
1590 }
1591
Eli Friedmane91b2e62017-07-04 00:52:24 +00001592 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001593
Eli Friedmane91b2e62017-07-04 00:52:24 +00001594 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001595 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001596 }
1597
Eli Friedmane91b2e62017-07-04 00:52:24 +00001598 void VisitBreakStmt(const BreakStmt* E) {
1599 if (!InSwitch)
1600 BreakLoc = E->getBreakLoc();
1601 }
1602
1603 void VisitSwitchStmt(const SwitchStmt* S) {
1604 if (const Stmt *Init = S->getInit())
1605 Visit(Init);
1606 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1607 Visit(CondVar);
1608 if (const Stmt *Cond = S->getCond())
1609 Visit(Cond);
1610
1611 // Don't return break statements from the body of a switch.
1612 InSwitch = true;
1613 if (const Stmt *Body = S->getBody())
1614 Visit(Body);
1615 InSwitch = false;
1616 }
1617
1618 void VisitForStmt(const ForStmt *S) {
1619 // Only visit the init statement of a for loop; the body
1620 // has a different break/continue scope.
1621 if (const Stmt *Init = S->getInit())
1622 Visit(Init);
1623 }
1624
1625 void VisitWhileStmt(const WhileStmt *) {
1626 // Do nothing; the children of a while loop have a different
1627 // break/continue scope.
1628 }
1629
1630 void VisitDoStmt(const DoStmt *) {
1631 // Do nothing; the children of a while loop have a different
1632 // break/continue scope.
1633 }
1634
1635 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1636 // Only visit the initialization of a for loop; the body
1637 // has a different break/continue scope.
Richard Smith8baa5002018-09-28 18:44:09 +00001638 if (const Stmt *Init = S->getInit())
1639 Visit(Init);
Eli Friedmane91b2e62017-07-04 00:52:24 +00001640 if (const Stmt *Range = S->getRangeStmt())
1641 Visit(Range);
1642 if (const Stmt *Begin = S->getBeginStmt())
1643 Visit(Begin);
1644 if (const Stmt *End = S->getEndStmt())
1645 Visit(End);
1646 }
1647
1648 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1649 // Only visit the initialization of a for loop; the body
1650 // has a different break/continue scope.
1651 if (const Stmt *Element = S->getElement())
1652 Visit(Element);
1653 if (const Stmt *Collection = S->getCollection())
1654 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001655 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001656
Serge Pavlov09f99242014-01-23 15:05:00 +00001657 bool ContinueFound() { return ContinueLoc.isValid(); }
1658 bool BreakFound() { return BreakLoc.isValid(); }
1659 SourceLocation GetContinueLoc() { return ContinueLoc; }
1660 SourceLocation GetBreakLoc() { return BreakLoc; }
1661
1662 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001663
1664 // Emit a warning when a loop increment/decrement appears twice per loop
1665 // iteration. The conditions which trigger this warning are:
1666 // 1) The last statement in the loop body and the third expression in the
1667 // for loop are both increment or both decrement of the same variable
1668 // 2) No continue statements in the loop body.
1669 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1670 // Return when there is nothing to check.
1671 if (!Body || !Third) return;
1672
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001673 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001674 Third->getBeginLoc()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001675 return;
1676
1677 // Get the last statement from the loop body.
1678 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1679 if (!CS || CS->body_empty()) return;
1680 Stmt *LastStmt = CS->body_back();
1681 if (!LastStmt) return;
1682
1683 bool LoopIncrement, LastIncrement;
1684 DeclRefExpr *LoopDRE, *LastDRE;
1685
1686 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1687 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1688
1689 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001690 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001691 if (LoopIncrement != LastIncrement ||
1692 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1693
Serge Pavlov09f99242014-01-23 15:05:00 +00001694 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001695
1696 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1697 << LastDRE->getDecl() << LastIncrement;
1698 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1699 << LoopIncrement;
1700 }
1701
Richard Trieu451a5db2012-04-30 18:01:30 +00001702} // end namespace
1703
Serge Pavlov09f99242014-01-23 15:05:00 +00001704
1705void Sema::CheckBreakContinueBinding(Expr *E) {
1706 if (!E || getLangOpts().CPlusPlus)
1707 return;
1708 BreakContinueFinder BCFinder(*this, E);
1709 Scope *BreakParent = CurScope->getBreakParent();
1710 if (BCFinder.BreakFound() && BreakParent) {
1711 if (BreakParent->getFlags() & Scope::SwitchScope) {
1712 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1713 } else {
1714 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1715 << "break";
1716 }
1717 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1718 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1719 << "continue";
1720 }
1721}
1722
Richard Smith03a4aa32016-06-23 19:02:52 +00001723StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1724 Stmt *First, ConditionResult Second,
1725 FullExprArg third, SourceLocation RParenLoc,
1726 Stmt *Body) {
1727 if (Second.isInvalid())
1728 return StmtError();
1729
David Blaikiebbafb8a2012-03-11 07:00:24 +00001730 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001731 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001732 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1733 // declare identifiers for objects having storage class 'auto' or
1734 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001735 for (auto *DI : DS->decls()) {
1736 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001737 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001738 VD = nullptr;
1739 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001740 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1741 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001742 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001743 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001744 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001745 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001746
Richard Smith03a4aa32016-06-23 19:02:52 +00001747 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001748 CheckBreakContinueBinding(third.get());
1749
Richard Smith03a4aa32016-06-23 19:02:52 +00001750 if (!Second.get().first)
1751 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1752 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001753 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001754
Richard Smith03a4aa32016-06-23 19:02:52 +00001755 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001756 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001757 Second.get().second->getExprLoc()))
1758 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001759
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001760 Expr *Third = third.release().getAs<Expr>();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001761 if (isa<NullStmt>(Body))
1762 getCurCompoundScope().setHasEmptyLoopBodies();
1763
Richard Smith03a4aa32016-06-23 19:02:52 +00001764 return new (Context)
1765 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1766 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001767}
1768
John McCall34376a62010-12-04 03:47:34 +00001769/// In an Objective C collection iteration statement:
1770/// for (x in y)
1771/// x can be an arbitrary l-value expression. Bind it up as a
1772/// full-expression.
1773StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001774 // Reduce placeholder expressions here. Note that this rejects the
1775 // use of pseudo-object l-values in this position.
1776 ExprResult result = CheckPlaceholderExpr(E);
1777 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001778 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001779
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001780 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00001781 if (FullExpr.isInvalid())
1782 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001783 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001784}
1785
John McCall53848232011-07-27 01:07:15 +00001786ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001787Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1788 if (!collection)
1789 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001790
Kaelyn Takata15867822014-11-21 18:48:04 +00001791 ExprResult result = CorrectDelayedTyposInExpr(collection);
1792 if (!result.isUsable())
1793 return ExprError();
1794 collection = result.get();
1795
John McCall53848232011-07-27 01:07:15 +00001796 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001797 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001798
1799 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001800 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001801 if (result.isInvalid())
1802 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001803 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001804
1805 // The operand needs to have object-pointer type.
1806 // TODO: should we do a contextual conversion?
1807 const ObjCObjectPointerType *pointerType =
1808 collection->getType()->getAs<ObjCObjectPointerType>();
1809 if (!pointerType)
1810 return Diag(forLoc, diag::err_collection_expr_type)
1811 << collection->getType() << collection->getSourceRange();
1812
1813 // Check that the operand provides
1814 // - countByEnumeratingWithState:objects:count:
1815 const ObjCObjectType *objectType = pointerType->getObjectType();
1816 ObjCInterfaceDecl *iface = objectType->getInterface();
1817
1818 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001819 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001820 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001821 (getLangOpts().ObjCAutoRefCount
1822 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1823 diag::err_arc_collection_forward, collection)
1824 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001825 // Otherwise, if we have any useful type information, check that
1826 // the type declares the appropriate method.
1827 } else if (iface || !objectType->qual_empty()) {
1828 IdentifierInfo *selectorIdents[] = {
1829 &Context.Idents.get("countByEnumeratingWithState"),
1830 &Context.Idents.get("objects"),
1831 &Context.Idents.get("count")
1832 };
1833 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1834
Craig Topperc3ec1492014-05-26 06:22:03 +00001835 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001836
1837 // If there's an interface, look in both the public and private APIs.
1838 if (iface) {
1839 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001840 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001841 }
1842
1843 // Also check protocol qualifiers.
1844 if (!method)
1845 method = LookupMethodInQualifiedType(selector, pointerType,
1846 /*instance*/ true);
1847
1848 // If we didn't find it anywhere, give up.
1849 if (!method) {
1850 Diag(forLoc, diag::warn_collection_expr_type)
1851 << collection->getType() << selector << collection->getSourceRange();
1852 }
1853
1854 // TODO: check for an incompatible signature?
1855 }
1856
1857 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001858 return collection;
John McCall53848232011-07-27 01:07:15 +00001859}
1860
John McCalldadc5752010-08-24 06:29:42 +00001861StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001862Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001863 Stmt *First, Expr *collection,
1864 SourceLocation RParenLoc) {
Reid Kleckner87a31802018-03-12 21:43:02 +00001865 setFunctionHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001866
1867 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001868 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001869
Fariborz Jahanian93977672008-01-10 20:33:58 +00001870 if (First) {
1871 QualType FirstType;
1872 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001873 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001874 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1875 diag::err_toomany_element_decls));
1876
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001877 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1878 if (!D || D->isInvalidDecl())
1879 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001880
John McCall31168b02011-06-15 23:02:42 +00001881 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001882 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1883 // declare identifiers for objects having storage class 'auto' or
1884 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001885 if (!D->hasLocalStorage())
1886 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001887 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001888
1889 // If the type contained 'auto', deduce the 'auto' to 'id'.
1890 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001891 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1892 VK_RValue);
1893 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001894 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1895 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001896 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001897 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001898 D->setInvalidDecl();
1899 return StmtError();
1900 }
1901
Richard Smith061f1e22013-04-30 21:23:01 +00001902 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001903
Richard Smith51ec0cf2017-02-21 01:17:38 +00001904 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001905 SourceLocation Loc =
1906 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001907 Diag(Loc, diag::warn_auto_var_is_id)
1908 << D->getDeclName();
1909 }
1910 }
1911
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001912 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001913 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001914 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001915 return StmtError(
1916 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1917 << First->getSourceRange());
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001918
Mike Stump11289f42009-09-09 15:08:12 +00001919 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001920 if (FirstType.isConstQualified())
1921 Diag(ForLoc, diag::err_selector_element_const_type)
1922 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001923 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001924 if (!FirstType->isDependentType() &&
1925 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001926 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001927 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1928 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001929 }
Chad Rosier02a84392012-08-10 17:56:09 +00001930
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001931 if (CollectionExprResult.isInvalid())
1932 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001933
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001934 CollectionExprResult =
1935 ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00001936 if (CollectionExprResult.isInvalid())
1937 return StmtError();
1938
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001939 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1940 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001941}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001942
Richard Smith02e85f32011-04-14 22:09:26 +00001943/// Finish building a variable declaration for a for-range statement.
1944/// \return true if an error occurs.
1945static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001946 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001947 if (Decl->getType()->isUndeducedType()) {
1948 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1949 if (!Res.isUsable()) {
1950 Decl->setInvalidDecl();
1951 return true;
1952 }
1953 Init = Res.get();
1954 }
1955
Richard Smith02e85f32011-04-14 22:09:26 +00001956 // Deduce the type for the iterator variable now rather than leaving it to
1957 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001958 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001959 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001960 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001961 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001962 SemaRef.Diag(Loc, DiagID) << Init->getType();
1963 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001964 Decl->setInvalidDecl();
1965 return true;
1966 }
Richard Smith061f1e22013-04-30 21:23:01 +00001967 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001968
John McCall31168b02011-06-15 23:02:42 +00001969 // In ARC, infer lifetime.
1970 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1971 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001972 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001973 SemaRef.inferObjCARCLifetime(Decl))
1974 Decl->setInvalidDecl();
1975
Richard Smith3beb7c62017-01-12 02:27:38 +00001976 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001977 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001978 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001979 return false;
1980}
1981
Sam Panzer0f384432012-08-21 00:52:01 +00001982namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001983// An enum to represent whether something is dealing with a call to begin()
1984// or a call to end() in a range-based for loop.
1985enum BeginEndFunction {
1986 BEF_begin,
1987 BEF_end
1988};
Sam Panzer0f384432012-08-21 00:52:01 +00001989
Richard Smith02e85f32011-04-14 22:09:26 +00001990/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001991/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001992/// nor from the diagnostics produced when analysing the implicit expressions
1993/// required in a for-range statement.
1994void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001995 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001996 CallExpr *CE = dyn_cast<CallExpr>(E);
1997 if (!CE)
1998 return;
1999 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2000 if (!D)
2001 return;
2002 SourceLocation Loc = D->getLocation();
2003
2004 std::string Description;
2005 bool IsTemplate = false;
2006 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2007 Description = SemaRef.getTemplateArgumentBindingsText(
2008 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2009 IsTemplate = true;
2010 }
2011
2012 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2013 << BEF << IsTemplate << Description << E->getType();
2014}
2015
Sam Panzer0f384432012-08-21 00:52:01 +00002016/// Build a variable declaration for a for-range statement.
2017VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
Matt Davisb8402ef2018-02-14 21:22:11 +00002018 QualType Type, StringRef Name) {
Sam Panzer0f384432012-08-21 00:52:01 +00002019 DeclContext *DC = SemaRef.CurContext;
2020 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2021 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2022 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002023 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00002024 Decl->setImplicit();
2025 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00002026}
2027
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002028}
Richard Smith02e85f32011-04-14 22:09:26 +00002029
Fariborz Jahanian00213472012-07-06 19:04:04 +00002030static bool ObjCEnumerationCollection(Expr *Collection) {
2031 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00002032 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00002033}
2034
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002035/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002036///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002037/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00002038/// A range-based for statement is equivalent to
2039///
2040/// {
2041/// auto && __range = range-init;
2042/// for ( auto __begin = begin-expr,
2043/// __end = end-expr;
2044/// __begin != __end;
2045/// ++__begin ) {
2046/// for-range-declaration = *__begin;
2047/// statement
2048/// }
2049/// }
2050///
2051/// The body of the loop is not available yet, since it cannot be analysed until
2052/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00002053StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002054 SourceLocation CoawaitLoc, Stmt *InitStmt,
2055 Stmt *First, SourceLocation ColonLoc,
2056 Expr *Range, SourceLocation RParenLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +00002057 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00002058 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00002059 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002060
Richard Smith8baa5002018-09-28 18:44:09 +00002061 if (Range && ObjCEnumerationCollection(Range)) {
2062 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2063 if (InitStmt)
2064 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2065 << InitStmt->getSourceRange();
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002066 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith8baa5002018-09-28 18:44:09 +00002067 }
Richard Smith02e85f32011-04-14 22:09:26 +00002068
2069 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2070 assert(DS && "first part of for range not a decl stmt");
2071
2072 if (!DS->isSingleDecl()) {
Stephen Kellya6e43582018-08-09 21:05:56 +00002073 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
Richard Smith02e85f32011-04-14 22:09:26 +00002074 return StmtError();
2075 }
Richard Smith02e85f32011-04-14 22:09:26 +00002076
Richard Smith3249fed2013-08-21 01:40:36 +00002077 Decl *LoopVar = DS->getSingleDecl();
2078 if (LoopVar->isInvalidDecl() || !Range ||
2079 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2080 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002081 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002082 }
Richard Smith02e85f32011-04-14 22:09:26 +00002083
Eric Fiselierb936a392017-06-14 03:24:55 +00002084 // Build the coroutine state immediately and not later during template
2085 // instantiation
2086 if (!CoawaitLoc.isInvalid()) {
2087 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2088 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002089 }
2090
Richard Smith02e85f32011-04-14 22:09:26 +00002091 // Build auto && __range = range-init
Matt Davisb8402ef2018-02-14 21:22:11 +00002092 // Divide by 2, since the variables are in the inner scope (loop body).
2093 const auto DepthStr = std::to_string(S->getDepth() / 2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002094 SourceLocation RangeLoc = Range->getBeginLoc();
Richard Smith02e85f32011-04-14 22:09:26 +00002095 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2096 Context.getAutoRRefDeductType(),
Matt Davisb8402ef2018-02-14 21:22:11 +00002097 std::string("__range") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002098 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002099 diag::err_for_range_deduction_failure)) {
2100 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002101 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002102 }
Richard Smith02e85f32011-04-14 22:09:26 +00002103
2104 // Claim the type doesn't contain auto: we've already done the checking.
2105 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002106 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002107 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002108 if (RangeDecl.isInvalid()) {
2109 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002110 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002111 }
Richard Smith02e85f32011-04-14 22:09:26 +00002112
Richard Smith8baa5002018-09-28 18:44:09 +00002113 return BuildCXXForRangeStmt(
2114 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2115 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2116 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002117}
2118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002119/// Create the initialization, compare, and increment steps for
Sam Panzer0f384432012-08-21 00:52:01 +00002120/// the range-based for loop expression.
2121/// This function does not handle array-based for loops,
2122/// which are created in Sema::BuildCXXForRangeStmt.
2123///
2124/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2125/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2126/// CandidateSet and BEF are set and some non-success value is returned on
2127/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002128static Sema::ForRangeStatus
2129BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2130 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2131 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2132 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2133 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002134 DeclarationNameInfo BeginNameInfo(
2135 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2136 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2137 ColonLoc);
2138
2139 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2140 Sema::LookupMemberName);
2141 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2142
Richard Smith236ffde2018-09-24 23:17:44 +00002143 auto BuildBegin = [&] {
2144 *BEF = BEF_begin;
2145 Sema::ForRangeStatus RangeStatus =
2146 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2147 BeginMemberLookup, CandidateSet,
2148 BeginRange, BeginExpr);
2149
2150 if (RangeStatus != Sema::FRS_Success) {
2151 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2152 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2153 << ColonLoc << BEF_begin << BeginRange->getType();
2154 return RangeStatus;
2155 }
2156 if (!CoawaitLoc.isInvalid()) {
2157 // FIXME: getCurScope() should not be used during template instantiation.
2158 // We should pick up the set of unqualified lookup results for operator
2159 // co_await during the initial parse.
2160 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2161 BeginExpr->get());
2162 if (BeginExpr->isInvalid())
2163 return Sema::FRS_DiagnosticIssued;
2164 }
2165 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2166 diag::err_for_range_iter_deduction_failure)) {
2167 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2168 return Sema::FRS_DiagnosticIssued;
2169 }
2170 return Sema::FRS_Success;
2171 };
2172
2173 auto BuildEnd = [&] {
2174 *BEF = BEF_end;
2175 Sema::ForRangeStatus RangeStatus =
2176 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2177 EndMemberLookup, CandidateSet,
2178 EndRange, EndExpr);
2179 if (RangeStatus != Sema::FRS_Success) {
2180 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2181 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2182 << ColonLoc << BEF_end << EndRange->getType();
2183 return RangeStatus;
2184 }
2185 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2186 diag::err_for_range_iter_deduction_failure)) {
2187 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2188 return Sema::FRS_DiagnosticIssued;
2189 }
2190 return Sema::FRS_Success;
2191 };
2192
Sam Panzer0f384432012-08-21 00:52:01 +00002193 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2194 // - if _RangeT is a class type, the unqualified-ids begin and end are
2195 // looked up in the scope of class _RangeT as if by class member access
2196 // lookup (3.4.5), and if either (or both) finds at least one
2197 // declaration, begin-expr and end-expr are __range.begin() and
2198 // __range.end(), respectively;
2199 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002200 if (BeginMemberLookup.isAmbiguous())
2201 return Sema::FRS_DiagnosticIssued;
2202
Sam Panzer0f384432012-08-21 00:52:01 +00002203 SemaRef.LookupQualifiedName(EndMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002204 if (EndMemberLookup.isAmbiguous())
2205 return Sema::FRS_DiagnosticIssued;
Sam Panzer0f384432012-08-21 00:52:01 +00002206
2207 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
Richard Smith236ffde2018-09-24 23:17:44 +00002208 // Look up the non-member form of the member we didn't find, first.
2209 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2210 // a 'begin' but ignored it because there was no member 'end'"
2211 // diagnostic.
2212 auto BuildNonmember = [&](
2213 BeginEndFunction BEFFound, LookupResult &Found,
2214 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2215 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2216 LookupResult OldFound = std::move(Found);
2217 Found.clear();
Sam Panzer0f384432012-08-21 00:52:01 +00002218
Richard Smith236ffde2018-09-24 23:17:44 +00002219 if (Sema::ForRangeStatus Result = BuildNotFound())
2220 return Result;
2221
2222 switch (BuildFound()) {
2223 case Sema::FRS_Success:
2224 return Sema::FRS_Success;
2225
2226 case Sema::FRS_NoViableFunction:
2227 SemaRef.Diag(BeginRange->getBeginLoc(), diag::err_for_range_invalid)
2228 << BeginRange->getType() << BEFFound;
2229 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, BeginRange);
2230 LLVM_FALLTHROUGH;
2231
2232 case Sema::FRS_DiagnosticIssued:
2233 for (NamedDecl *D : OldFound) {
2234 SemaRef.Diag(D->getLocation(),
2235 diag::note_for_range_member_begin_end_ignored)
2236 << BeginRange->getType() << BEFFound;
2237 }
2238 return Sema::FRS_DiagnosticIssued;
2239 }
2240 llvm_unreachable("unexpected ForRangeStatus");
2241 };
2242 if (BeginMemberLookup.empty())
2243 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2244 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
Sam Panzer0f384432012-08-21 00:52:01 +00002245 }
2246 } else {
2247 // - otherwise, begin-expr and end-expr are begin(__range) and
2248 // end(__range), respectively, where begin and end are looked up with
2249 // argument-dependent lookup (3.4.2). For the purposes of this name
2250 // lookup, namespace std is an associated namespace.
Sam Panzer0f384432012-08-21 00:52:01 +00002251 }
2252
Richard Smith236ffde2018-09-24 23:17:44 +00002253 if (Sema::ForRangeStatus Result = BuildBegin())
2254 return Result;
2255 return BuildEnd();
Sam Panzer0f384432012-08-21 00:52:01 +00002256}
2257
2258/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002259/// If the attempt fails, this function will return a valid, null StmtResult
2260/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002261static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2262 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002263 SourceLocation CoawaitLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002264 Stmt *InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002265 Stmt *LoopVarDecl,
2266 SourceLocation ColonLoc,
2267 Expr *Range,
2268 SourceLocation RangeLoc,
2269 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002270 // Determine whether we can rebuild the for-range statement with a
2271 // dereferenced range expression.
2272 ExprResult AdjustedRange;
2273 {
2274 Sema::SFINAETrap Trap(SemaRef);
2275
2276 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2277 if (AdjustedRange.isInvalid())
2278 return StmtResult();
2279
Richard Smith9f690bd2015-10-27 06:02:45 +00002280 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002281 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2282 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002283 if (SR.isInvalid())
2284 return StmtResult();
2285 }
2286
2287 // The attempt to dereference worked well enough that it could produce a valid
2288 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2289 // case there are any other (non-fatal) problems with it.
2290 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2291 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith8baa5002018-09-28 18:44:09 +00002292 return SemaRef.ActOnCXXForRangeStmt(
2293 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2294 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002295}
2296
Richard Smith3249fed2013-08-21 01:40:36 +00002297namespace {
2298/// RAII object to automatically invalidate a declaration if an error occurs.
2299struct InvalidateOnErrorScope {
2300 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2301 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2302 ~InvalidateOnErrorScope() {
2303 if (Enabled && Trap.hasErrorOccurred())
2304 D->setInvalidDecl();
2305 }
2306
2307 DiagnosticErrorTrap Trap;
2308 Decl *D;
2309 bool Enabled;
2310};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002311}
Richard Smith3249fed2013-08-21 01:40:36 +00002312
Richard Smitha05b3b52012-09-20 21:52:32 +00002313/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith8baa5002018-09-28 18:44:09 +00002314StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2315 SourceLocation CoawaitLoc, Stmt *InitStmt,
2316 SourceLocation ColonLoc, Stmt *RangeDecl,
2317 Stmt *Begin, Stmt *End, Expr *Cond,
2318 Expr *Inc, Stmt *LoopVarDecl,
2319 SourceLocation RParenLoc,
2320 BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002321 // FIXME: This should not be used during template instantiation. We should
2322 // pick up the set of unqualified lookup results for the != and + operators
2323 // in the initial parse.
2324 //
2325 // Testcase (accepts-invalid):
2326 // template<typename T> void f() { for (auto x : T()) {} }
2327 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2328 // bool operator!=(N::X, N::X); void operator++(N::X);
2329 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002330 Scope *S = getCurScope();
2331
2332 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2333 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2334 QualType RangeVarType = RangeVar->getType();
2335
2336 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2337 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2338
Richard Smith3249fed2013-08-21 01:40:36 +00002339 // If we hit any errors, mark the loop variable as invalid if its type
2340 // contains 'auto'.
2341 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2342 LoopVar->getType()->isUndeducedType());
2343
Richard Smith01694c32016-03-20 10:33:40 +00002344 StmtResult BeginDeclStmt = Begin;
2345 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002346 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2347
Richard Smith27d807c2013-04-30 13:56:41 +00002348 if (RangeVarType->isDependentType()) {
2349 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002350 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002351
2352 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2353 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002354 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2355 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2356 for (auto *Binding : DD->bindings())
2357 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002358 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002359 }
Richard Smith01694c32016-03-20 10:33:40 +00002360 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002361 SourceLocation RangeLoc = RangeVar->getLocation();
2362
Ted Kremenekbed648e2011-10-10 22:36:28 +00002363 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2364
2365 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2366 VK_LValue, ColonLoc);
2367 if (BeginRangeRef.isInvalid())
2368 return StmtError();
2369
2370 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2371 VK_LValue, ColonLoc);
2372 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002373 return StmtError();
2374
2375 QualType AutoType = Context.getAutoDeductType();
2376 Expr *Range = RangeVar->getInit();
2377 if (!Range)
2378 return StmtError();
2379 QualType RangeType = Range->getType();
2380
2381 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002382 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002383 return StmtError();
2384
2385 // Build auto __begin = begin-expr, __end = end-expr.
Matt Davisb8402ef2018-02-14 21:22:11 +00002386 // Divide by 2, since the variables are in the inner scope (loop body).
2387 const auto DepthStr = std::to_string(S->getDepth() / 2);
Richard Smith02e85f32011-04-14 22:09:26 +00002388 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002389 std::string("__begin") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002390 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002391 std::string("__end") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002392
2393 // Build begin-expr and end-expr and attach to __begin and __end variables.
2394 ExprResult BeginExpr, EndExpr;
2395 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2396 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2397 // __range + __bound, respectively, where __bound is the array bound. If
2398 // _RangeT is an array of unknown size or an array of incomplete type,
2399 // the program is ill-formed;
2400
2401 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002402 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002403 if (!CoawaitLoc.isInvalid()) {
2404 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2405 if (BeginExpr.isInvalid())
2406 return StmtError();
2407 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002408 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002409 diag::err_for_range_iter_deduction_failure)) {
2410 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2411 return StmtError();
2412 }
2413
2414 // Find the array bound.
2415 ExprResult BoundExpr;
2416 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002417 BoundExpr = IntegerLiteral::Create(
2418 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002419 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002420 dyn_cast<VariableArrayType>(UnqAT)) {
2421 // For a variably modified type we can't just use the expression within
2422 // the array bounds, since we don't want that to be re-evaluated here.
2423 // Rather, we need to determine what it was when the array was first
2424 // created - so we resort to using sizeof(vla)/sizeof(element).
2425 // For e.g.
Fangrui Song6907ce22018-07-30 19:24:48 +00002426 // void f(int b) {
Faisal Vali1ca2d962017-05-15 01:49:19 +00002427 // int vla[b];
2428 // b = -1; <-- This should not affect the num of iterations below
2429 // for (int &c : vla) { .. }
2430 // }
2431
2432 // FIXME: This results in codegen generating IR that recalculates the
2433 // run-time number of elements (as opposed to just using the IR Value
2434 // that corresponds to the run-time value of each bound that was
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002435 // generated when the array was created.) If this proves too embarrassing
Faisal Vali1ca2d962017-05-15 01:49:19 +00002436 // even for unoptimized IR, consider passing a magic-value/cookie to
2437 // codegen that then knows to simply use that initial llvm::Value (that
2438 // corresponds to the bound at time of array creation) within
2439 // getelementptr. But be prepared to pay the price of increasing a
2440 // customized form of coupling between the two components - which could
2441 // be hard to maintain as the codebase evolves.
2442
2443 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2444 EndVar->getLocation(), UETT_SizeOf,
2445 /*isType=*/true,
2446 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2447 VAT->desugar(), RangeLoc))
2448 .getAsOpaquePtr(),
2449 EndVar->getSourceRange());
2450 if (SizeOfVLAExprR.isInvalid())
2451 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002452
Faisal Vali1ca2d962017-05-15 01:49:19 +00002453 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2454 EndVar->getLocation(), UETT_SizeOf,
2455 /*isType=*/true,
2456 CreateParsedType(VAT->desugar(),
2457 Context.getTrivialTypeSourceInfo(
2458 VAT->getElementType(), RangeLoc))
2459 .getAsOpaquePtr(),
2460 EndVar->getSourceRange());
2461 if (SizeOfEachElementExprR.isInvalid())
2462 return StmtError();
2463
2464 BoundExpr =
2465 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2466 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2467 if (BoundExpr.isInvalid())
2468 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002469
Faisal Vali1ca2d962017-05-15 01:49:19 +00002470 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002471 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2472 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002473 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002474 }
2475
2476 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002477 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002478 BoundExpr.get());
2479 if (EndExpr.isInvalid())
2480 return StmtError();
2481 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2482 diag::err_for_range_iter_deduction_failure)) {
2483 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2484 return StmtError();
2485 }
2486 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002487 OverloadCandidateSet CandidateSet(RangeLoc,
2488 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002489 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002490 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2491 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2492 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2493 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002494
Richard Smitha05b3b52012-09-20 21:52:32 +00002495 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002496 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002497 // If the range is being built from an array parameter, emit a
2498 // a diagnostic that it is being treated as a pointer.
2499 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2500 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2501 QualType ArrayTy = PVD->getOriginalType();
2502 QualType PointerTy = PVD->getType();
2503 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002504 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2505 << RangeLoc << PVD << ArrayTy << PointerTy;
Richard Trieu08254692013-10-11 22:16:04 +00002506 Diag(PVD->getLocation(), diag::note_declared_at);
2507 return StmtError();
2508 }
2509 }
2510 }
2511
2512 // If building the range failed, try dereferencing the range expression
2513 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002514 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002515 CoawaitLoc, InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002516 LoopVarDecl, ColonLoc,
2517 Range, RangeLoc,
2518 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002519 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002520 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002521 }
2522
Sam Panzer0f384432012-08-21 00:52:01 +00002523 // Otherwise, emit diagnostics if we haven't already.
2524 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002525 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002526 Diag(Range->getBeginLoc(), diag::err_for_range_invalid)
Sam Panzer0f384432012-08-21 00:52:01 +00002527 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002528 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002529 }
2530 // Return an error if no fix was discovered.
2531 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002532 return StmtError();
2533 }
2534
Sam Panzer0f384432012-08-21 00:52:01 +00002535 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2536 "invalid range expression in for loop");
2537
2538 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002539 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002540 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2541 if (!Context.hasSameType(BeginType, EndType)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002542 Diag(RangeLoc, getLangOpts().CPlusPlus17
Richard Smith01694c32016-03-20 10:33:40 +00002543 ? diag::warn_for_range_begin_end_types_differ
2544 : diag::ext_for_range_begin_end_types_differ)
2545 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002546 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2547 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2548 }
2549
Richard Smith01694c32016-03-20 10:33:40 +00002550 BeginDeclStmt =
2551 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2552 EndDeclStmt =
2553 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002554
Ted Kremenekbed648e2011-10-10 22:36:28 +00002555 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2556 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002557 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002558 if (BeginRef.isInvalid())
2559 return StmtError();
2560
Richard Smith02e85f32011-04-14 22:09:26 +00002561 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2562 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002563 if (EndRef.isInvalid())
2564 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002565
2566 // Build and check __begin != __end expression.
2567 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2568 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002569 if (!NotEqExpr.isInvalid())
2570 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2571 if (!NotEqExpr.isInvalid())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002572 NotEqExpr =
2573 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002574 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002575 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2576 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002577 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2578 if (!Context.hasSameType(BeginType, EndType))
2579 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2580 return StmtError();
2581 }
2582
2583 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002584 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2585 VK_LValue, ColonLoc);
2586 if (BeginRef.isInvalid())
2587 return StmtError();
2588
Richard Smith02e85f32011-04-14 22:09:26 +00002589 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002590 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002591 // FIXME: getCurScope() should not be used during template instantiation.
2592 // We should pick up the set of unqualified lookup results for operator
2593 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002594 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002595 if (!IncrExpr.isInvalid())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002596 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002597 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002598 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2599 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002600 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2601 return StmtError();
2602 }
2603
2604 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002605 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2606 VK_LValue, ColonLoc);
2607 if (BeginRef.isInvalid())
2608 return StmtError();
2609
Richard Smith02e85f32011-04-14 22:09:26 +00002610 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2611 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002612 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2613 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002614 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2615 return StmtError();
2616 }
2617
Richard Smitha05b3b52012-09-20 21:52:32 +00002618 // Attach *__begin as initializer for VD. Don't touch it if we're just
2619 // trying to determine whether this would be a valid range.
2620 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002621 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002622 if (LoopVar->isInvalidDecl())
2623 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2624 }
2625 }
2626
Richard Smitha05b3b52012-09-20 21:52:32 +00002627 // Don't bother to actually allocate the result if we're just trying to
2628 // determine whether it would be valid.
2629 if (Kind == BFRK_Check)
2630 return StmtResult();
2631
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002632 return new (Context) CXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002633 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
Richard Smith01694c32016-03-20 10:33:40 +00002634 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002635 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2636 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002637}
2638
Chad Rosier02a84392012-08-10 17:56:09 +00002639/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002640/// statement.
2641StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2642 if (!S || !B)
2643 return StmtError();
2644 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002645
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002646 ForStmt->setBody(B);
2647 return S;
2648}
2649
Richard Trieu3e1d4832015-04-13 22:08:55 +00002650// Warn when the loop variable is a const reference that creates a copy.
2651// Suggest using the non-reference type for copies. If a copy can be prevented
2652// suggest the const reference type that would do so.
2653// For instance, given "for (const &Foo : Range)", suggest
2654// "for (const Foo : Range)" to denote a copy is made for the loop. If
2655// possible, also suggest "for (const &Bar : Range)" if this type prevents
2656// the copy altogether.
2657static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2658 const VarDecl *VD,
2659 QualType RangeInitType) {
2660 const Expr *InitExpr = VD->getInit();
2661 if (!InitExpr)
2662 return;
2663
2664 QualType VariableType = VD->getType();
2665
Tim Shen4a05bb82016-06-21 20:29:17 +00002666 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2667 if (!Cleanups->cleanupsHaveSideEffects())
2668 InitExpr = Cleanups->getSubExpr();
2669
Richard Trieu3e1d4832015-04-13 22:08:55 +00002670 const MaterializeTemporaryExpr *MTE =
2671 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2672
2673 // No copy made.
2674 if (!MTE)
2675 return;
2676
2677 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2678
2679 // Searching for either UnaryOperator for dereference of a pointer or
2680 // CXXOperatorCallExpr for handling iterators.
2681 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2682 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2683 E = CCE->getArg(0);
2684 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2685 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2686 E = ME->getBase();
2687 } else {
2688 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2689 E = MTE->GetTemporaryExpr();
2690 }
2691 E = E->IgnoreImpCasts();
2692 }
2693
2694 bool ReturnsReference = false;
2695 if (isa<UnaryOperator>(E)) {
2696 ReturnsReference = true;
2697 } else {
2698 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2699 const FunctionDecl *FD = Call->getDirectCallee();
2700 QualType ReturnType = FD->getReturnType();
2701 ReturnsReference = ReturnType->isReferenceType();
2702 }
2703
2704 if (ReturnsReference) {
2705 // Loop variable creates a temporary. Suggest either to go with
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002706 // non-reference loop variable to indicate a copy is made, or
Richard Trieu3e1d4832015-04-13 22:08:55 +00002707 // the correct time to bind a const reference.
2708 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2709 << VD << VariableType << E->getType();
2710 QualType NonReferenceType = VariableType.getNonReferenceType();
2711 NonReferenceType.removeLocalConst();
2712 QualType NewReferenceType =
2713 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002714 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002715 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2716 } else {
2717 // The range always returns a copy, so a temporary is always created.
2718 // Suggest removing the reference from the loop variable.
2719 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2720 << VD << RangeInitType;
2721 QualType NonReferenceType = VariableType.getNonReferenceType();
2722 NonReferenceType.removeLocalConst();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002723 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002724 << NonReferenceType << VD->getSourceRange();
2725 }
2726}
2727
2728// Warns when the loop variable can be changed to a reference type to
2729// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2730// "for (const Foo &x : Range)" if this form does not make a copy.
2731static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2732 const VarDecl *VD) {
2733 const Expr *InitExpr = VD->getInit();
2734 if (!InitExpr)
2735 return;
2736
2737 QualType VariableType = VD->getType();
2738
2739 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2740 if (!CE->getConstructor()->isCopyConstructor())
2741 return;
2742 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2743 if (CE->getCastKind() != CK_LValueToRValue)
2744 return;
2745 } else {
2746 return;
2747 }
2748
2749 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2750 // should be emitted. Also, only ignore POD types with trivial copy
2751 // constructors.
2752 if (VariableType.isPODType(SemaRef.Context))
2753 return;
2754
2755 // Suggest changing from a const variable to a const reference variable
2756 // if doing so will prevent a copy.
2757 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2758 << VD << VariableType << InitExpr->getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002759 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002760 << SemaRef.Context.getLValueReferenceType(VariableType)
2761 << VD->getSourceRange();
2762}
2763
2764/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2765/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2766/// using "const foo x" to show that a copy is made
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002767/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
Richard Trieu3e1d4832015-04-13 22:08:55 +00002768/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2769/// prevent the copy.
2770/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2771/// Suggest "const foo &x" to prevent the copy.
2772static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2773 const CXXForRangeStmt *ForStmt) {
2774 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002775 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002776 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002777 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002778 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002779 ForStmt->getBeginLoc())) {
Richard Trieu3e1d4832015-04-13 22:08:55 +00002780 return;
2781 }
2782
2783 const VarDecl *VD = ForStmt->getLoopVariable();
2784 if (!VD)
2785 return;
2786
2787 QualType VariableType = VD->getType();
2788
2789 if (VariableType->isIncompleteType())
2790 return;
2791
2792 const Expr *InitExpr = VD->getInit();
2793 if (!InitExpr)
2794 return;
2795
2796 if (VariableType->isReferenceType()) {
2797 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2798 ForStmt->getRangeInit()->getType());
2799 } else if (VariableType.isConstQualified()) {
2800 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2801 }
2802}
2803
Richard Smith02e85f32011-04-14 22:09:26 +00002804/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2805/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2806/// body cannot be performed until after the type of the range variable is
2807/// determined.
2808StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2809 if (!S || !B)
2810 return StmtError();
2811
Fariborz Jahanian00213472012-07-06 19:04:04 +00002812 if (isa<ObjCForCollectionStmt>(S))
2813 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002814
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002815 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2816 ForStmt->setBody(B);
2817
2818 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2819 diag::warn_empty_range_based_for_body);
2820
Richard Trieu3e1d4832015-04-13 22:08:55 +00002821 DiagnoseForRangeVariableCopies(*this, ForStmt);
2822
Richard Smith02e85f32011-04-14 22:09:26 +00002823 return S;
2824}
2825
Chris Lattnercab02a62011-02-17 20:34:02 +00002826StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2827 SourceLocation LabelLoc,
2828 LabelDecl *TheDecl) {
Reid Kleckner87a31802018-03-12 21:43:02 +00002829 setFunctionHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002830 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002831 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002832}
Chris Lattner1c310502007-05-31 06:00:00 +00002833
John McCalldadc5752010-08-24 06:29:42 +00002834StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002835Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002836 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002837 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002838 if (!E->isTypeDependent()) {
2839 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002840 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002841 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002842 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002843 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2844 if (ExprRes.isInvalid())
2845 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002846 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002847 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002848 return StmtError();
2849 }
John McCalla95172b2010-08-01 00:26:45 +00002850
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00002851 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00002852 if (ExprRes.isInvalid())
2853 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002854 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002855
Reid Kleckner87a31802018-03-12 21:43:02 +00002856 setFunctionHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002857
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002858 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002859}
2860
Nico Weberd64657f2015-03-09 02:47:59 +00002861static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2862 const Scope &DestScope) {
2863 if (!S.CurrentSEHFinally.empty() &&
2864 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2865 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2866 }
2867}
2868
John McCalldadc5752010-08-24 06:29:42 +00002869StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002870Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002871 Scope *S = CurScope->getContinueParent();
2872 if (!S) {
2873 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002874 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002875 }
Nico Weberd64657f2015-03-09 02:47:59 +00002876 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002877
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002878 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002879}
2880
John McCalldadc5752010-08-24 06:29:42 +00002881StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002882Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002883 Scope *S = CurScope->getBreakParent();
2884 if (!S) {
2885 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002886 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002887 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002888 if (S->isOpenMPLoopScope())
2889 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2890 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002891 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002892
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002893 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002894}
2895
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002896/// Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002897/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002898///
Douglas Gregor5d369002011-01-21 18:05:27 +00002899/// \param ReturnType If we're determining the copy elision candidate for
2900/// a return statement, this is the return type of the function. If we're
2901/// determining the copy elision candidate for a throw expression, this will
2902/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002903///
Douglas Gregor5d369002011-01-21 18:05:27 +00002904/// \param E The expression being returned from the function or block, or
2905/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002906///
Richard Trieu09c163b2018-03-15 03:00:55 +00002907/// \param CESK Whether we allow function parameters or
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002908/// id-expressions that could be moved out of the function to be considered NRVO
2909/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2910/// determine whether we should try to move as part of a return or throw (which
2911/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002912///
2913/// \returns The NRVO candidate variable, if the return statement may use the
2914/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002915VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
Richard Trieu09c163b2018-03-15 03:00:55 +00002916 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002917 // - in a return statement in a function [where] ...
2918 // ... the expression is the name of a non-volatile automatic object ...
2919 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002920 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002921 return nullptr;
2922 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2923 if (!VD)
2924 return nullptr;
2925
Richard Trieu09c163b2018-03-15 03:00:55 +00002926 if (isCopyElisionCandidate(ReturnType, VD, CESK))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002927 return VD;
2928 return nullptr;
2929}
2930
2931bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Richard Trieu09c163b2018-03-15 03:00:55 +00002932 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002933 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002934 // - in a return statement in a function with ...
2935 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002936 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002937 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002938 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002939 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002940 // When considering moving this expression out, allow dissimilar types.
Richard Trieu09c163b2018-03-15 03:00:55 +00002941 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002942 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2943 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002944 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
John McCall03318c12011-11-11 03:57:31 +00002946 // ...object (other than a function or catch-clause parameter)...
2947 if (VD->getKind() != Decl::Var &&
Richard Trieu09c163b2018-03-15 03:00:55 +00002948 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002949 return false;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002950 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2951 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
John McCall03318c12011-11-11 03:57:31 +00002953 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002954 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002955
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002956 // Return false if VD is a __block variable. We don't want to implicitly move
2957 // out of a __block variable during a return because we cannot assume the
2958 // variable will no longer be used.
2959 if (VD->hasAttr<BlocksAttr>()) return false;
2960
Richard Trieu09c163b2018-03-15 03:00:55 +00002961 if (CESK & CES_AllowDifferentTypes)
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002962 return true;
2963
John McCall03318c12011-11-11 03:57:31 +00002964 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002965 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002966
John McCall03318c12011-11-11 03:57:31 +00002967 // Variables with higher required alignment than their type's ABI
2968 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002969 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002970 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002971 return false;
John McCall03318c12011-11-11 03:57:31 +00002972
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002973 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002974}
2975
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002976/// Try to perform the initialization of a potentially-movable value,
Richard Trieu09c163b2018-03-15 03:00:55 +00002977/// which is the operand to a return or throw statement.
2978///
2979/// This routine implements C++14 [class.copy]p32, which attempts to treat
2980/// returned lvalues as rvalues in certain cases (to prefer move construction),
2981/// then falls back to treating them as lvalues if that failed.
2982///
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002983/// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
2984/// resolutions that find non-constructors, such as derived-to-base conversions
2985/// or `operator T()&&` member functions. If false, do consider such
2986/// conversion sequences.
2987///
Richard Trieu09c163b2018-03-15 03:00:55 +00002988/// \param Res We will fill this in if move-initialization was possible.
2989/// If move-initialization is not possible, such that we must fall back to
2990/// treating the operand as an lvalue, we will leave Res in its original
2991/// invalid state.
2992static void TryMoveInitialization(Sema& S,
2993 const InitializedEntity &Entity,
2994 const VarDecl *NRVOCandidate,
2995 QualType ResultType,
2996 Expr *&Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002997 bool ConvertingConstructorsOnly,
Richard Trieu09c163b2018-03-15 03:00:55 +00002998 ExprResult &Res) {
2999 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3000 CK_NoOp, Value, VK_XValue);
3001
3002 Expr *InitExpr = &AsRvalue;
3003
3004 InitializationKind Kind = InitializationKind::CreateCopy(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003005 Value->getBeginLoc(), Value->getBeginLoc());
Richard Trieu09c163b2018-03-15 03:00:55 +00003006
3007 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3008
3009 if (!Seq)
3010 return;
3011
3012 for (const InitializationSequence::Step &Step : Seq.steps()) {
3013 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3014 Step.Kind != InitializationSequence::SK_UserConversion)
3015 continue;
3016
3017 FunctionDecl *FD = Step.Function.Function;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003018 if (ConvertingConstructorsOnly) {
3019 if (isa<CXXConstructorDecl>(FD)) {
3020 // C++14 [class.copy]p32:
3021 // [...] If the first overload resolution fails or was not performed,
3022 // or if the type of the first parameter of the selected constructor
3023 // is not an rvalue reference to the object's type (possibly
3024 // cv-qualified), overload resolution is performed again, considering
3025 // the object as an lvalue.
3026 const RValueReferenceType *RRefType =
3027 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3028 if (!RRefType)
3029 break;
3030 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3031 NRVOCandidate->getType()))
3032 break;
3033 } else {
3034 continue;
3035 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003036 } else {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003037 if (isa<CXXConstructorDecl>(FD)) {
3038 // Check that overload resolution selected a constructor taking an
3039 // rvalue reference. If it selected an lvalue reference, then we
3040 // didn't need to cast this thing to an rvalue in the first place.
3041 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3042 break;
3043 } else if (isa<CXXMethodDecl>(FD)) {
3044 // Check that overload resolution selected a conversion operator
3045 // taking an rvalue reference.
3046 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3047 break;
3048 } else {
3049 continue;
3050 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003051 }
3052
3053 // Promote "AsRvalue" to the heap, since we now need this
3054 // expression node to persist.
3055 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3056 Value, nullptr, VK_XValue);
3057
3058 // Complete type-checking the initialization of the return type
3059 // using the constructor we found.
3060 Res = Seq.Perform(S, Entity, Kind, Value);
3061 }
3062}
3063
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003064/// Perform the initialization of a potentially-movable value, which
Douglas Gregor626fbed2011-01-21 21:08:57 +00003065/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00003066///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003067/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00003068/// returned lvalues as rvalues in certain cases (to prefer move construction),
3069/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00003071Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3072 const VarDecl *NRVOCandidate,
3073 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00003074 Expr *Value,
3075 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003076 // C++14 [class.copy]p32:
3077 // When the criteria for elision of a copy/move operation are met, but not for
3078 // an exception-declaration, and the object to be copied is designated by an
3079 // lvalue, or when the expression in a return statement is a (possibly
3080 // parenthesized) id-expression that names an object with automatic storage
3081 // duration declared in the body or parameter-declaration-clause of the
3082 // innermost enclosing function or lambda-expression, overload resolution to
3083 // select the constructor for the copy is first performed as if the object
3084 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00003085 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003086
Richard Trieu09c163b2018-03-15 03:00:55 +00003087 if (AllowNRVO) {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003088 bool AffectedByCWG1579 = false;
3089
Richard Trieu09c163b2018-03-15 03:00:55 +00003090 if (!NRVOCandidate) {
3091 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003092 if (NRVOCandidate &&
3093 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3094 Value->getExprLoc())) {
3095 const VarDecl *NRVOCandidateInCXX11 =
3096 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3097 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3098 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003099 }
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003100
Richard Trieu09c163b2018-03-15 03:00:55 +00003101 if (NRVOCandidate) {
3102 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003103 true, Res);
3104 }
3105
3106 if (!Res.isInvalid() && AffectedByCWG1579) {
3107 QualType QT = NRVOCandidate->getType();
3108 if (QT.getNonReferenceType()
3109 .getUnqualifiedType()
3110 .isTriviallyCopyableType(Context)) {
3111 // Adding 'std::move' around a trivially copyable variable is probably
3112 // pointless. Don't suggest it.
3113 } else {
3114 // Common cases for this are returning unique_ptr<Derived> from a
3115 // function of return type unique_ptr<Base>, or returning T from a
3116 // function of return type Expected<T>. This is totally fine in a
3117 // post-CWG1579 world, but was not fine before.
3118 assert(!ResultType.isNull());
3119 SmallString<32> Str;
3120 Str += "std::move(";
3121 Str += NRVOCandidate->getDeclName().getAsString();
3122 Str += ")";
3123 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3124 << Value->getSourceRange()
3125 << NRVOCandidate->getDeclName() << ResultType << QT;
3126 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3127 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3128 }
3129 } else if (Res.isInvalid() &&
3130 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3131 Value->getExprLoc())) {
3132 const VarDecl *FakeNRVOCandidate =
3133 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3134 if (FakeNRVOCandidate) {
3135 QualType QT = FakeNRVOCandidate->getType();
3136 if (QT->isLValueReferenceType()) {
3137 // Adding 'std::move' around an lvalue reference variable's name is
3138 // dangerous. Don't suggest it.
3139 } else if (QT.getNonReferenceType()
3140 .getUnqualifiedType()
3141 .isTriviallyCopyableType(Context)) {
3142 // Adding 'std::move' around a trivially copyable variable is probably
3143 // pointless. Don't suggest it.
3144 } else {
3145 ExprResult FakeRes = ExprError();
3146 Expr *FakeValue = Value;
3147 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3148 FakeValue, false, FakeRes);
3149 if (!FakeRes.isInvalid()) {
3150 bool IsThrow =
3151 (Entity.getKind() == InitializedEntity::EK_Exception);
3152 SmallString<32> Str;
3153 Str += "std::move(";
3154 Str += FakeNRVOCandidate->getDeclName().getAsString();
3155 Str += ")";
3156 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3157 << Value->getSourceRange()
3158 << FakeNRVOCandidate->getDeclName() << IsThrow;
3159 Diag(Value->getExprLoc(), diag::note_add_std_move)
3160 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3161 }
3162 }
3163 }
Douglas Gregorf282a762011-01-21 19:38:21 +00003164 }
3165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregorf282a762011-01-21 19:38:21 +00003167 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003168 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00003169 // (again) now with the return value expression as written.
3170 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00003171 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172
Douglas Gregorf282a762011-01-21 19:38:21 +00003173 return Res;
3174}
3175
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003176/// Determine whether the declared return type of the specified function
Richard Smith4db51c22013-09-25 05:02:54 +00003177/// contains 'auto'.
3178static bool hasDeducedReturnType(FunctionDecl *FD) {
3179 const FunctionProtoType *FPT =
3180 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003181 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003182}
3183
Eli Friedman34b49062012-01-26 03:00:14 +00003184/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3185/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003186///
John McCalldadc5752010-08-24 06:29:42 +00003187StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003188Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3189 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003190 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003191 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003192 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003193 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003194 bool HasDeducedReturnType =
3195 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003196
Faisal Valid143a0c2017-04-01 21:30:49 +00003197 if (ExprEvalContexts.back().Context ==
3198 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003199 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3200 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003201 ExprResult ER =
3202 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smithb130fe72016-06-23 19:16:49 +00003203 if (ER.isInvalid())
3204 return StmtError();
3205 RetValExp = ER.get();
3206 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003207 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3208 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003209 }
3210
3211 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003212 // In C++1y, the return type may involve 'auto'.
3213 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3214 FunctionDecl *FD = CurLambda->CallOperator;
3215 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003216 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003217
3218 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3219 assert(AT && "lost auto type from lambda return type");
3220 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3221 FD->setInvalidDecl();
3222 return StmtError();
3223 }
Alp Toker314cc812014-01-25 16:55:45 +00003224 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003225 } else if (CurCap->HasImplicitReturnType) {
3226 // For blocks/lambdas with implicit return types, we check each return
3227 // statement individually, and deduce the common return type when the block
3228 // or lambda is completed.
3229 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003230 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003231 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3232 if (Result.isInvalid())
3233 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003234 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003235
Richard Smith5a0e50c2014-12-19 22:10:51 +00003236 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3237 // when deducing a return type for a lambda-expression (or by extension
3238 // for a block). These rules differ from the stated C++11 rules only in
3239 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003240 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003241 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003242 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003243 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003244 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003245 if (RetValExp) {
3246 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3247 // initializer list, because it is not an expression (even
3248 // though we represent it as one). We still deduce 'void'.
3249 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3250 << RetValExp->getSourceRange();
3251 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003252
Jordan Rosed39e5f12012-07-02 21:19:23 +00003253 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003254 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003255
3256 // Although we'll properly infer the type of the block once it's completed,
3257 // make sure we provide a return type now for better error recovery.
3258 if (CurCap->ReturnType.isNull())
3259 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003260 }
Eli Friedman34b49062012-01-26 03:00:14 +00003261 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003262
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003263 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00003264 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3265 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3266 return StmtError();
3267 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003268 } else if (CapturedRegionScopeInfo *CurRegion =
3269 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3270 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3271 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003272 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003273 assert(CurLambda && "unknown kind of captured scope");
3274 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3275 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003276 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3277 return StmtError();
3278 }
3279 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003280
Steve Naroffc540d662008-09-03 18:15:37 +00003281 // Otherwise, verify that this result type matches the previous one. We are
3282 // pickier with blocks than for normal functions because we don't have GCC
3283 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003284 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003285 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003286 // Delay processing for now. TODO: there are lots of dependent
3287 // types we can conclusively prove aren't void.
3288 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003289 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003290 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003291 (RetValExp->isTypeDependent() ||
3292 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003293 if (!getLangOpts().CPlusPlus &&
3294 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003295 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003296 else {
3297 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003298 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003299 }
Steve Naroffc540d662008-09-03 18:15:37 +00003300 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003301 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003302 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3303 } else if (!RetValExp->isTypeDependent()) {
3304 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003305
John McCall5500ef22011-08-17 22:09:46 +00003306 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3307 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3308 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003309
John McCall5500ef22011-08-17 22:09:46 +00003310 // In C++ the return statement is handled via a copy initialization.
3311 // the C version of which boils down to CheckSingleAssignmentConstraints.
Richard Trieu09c163b2018-03-15 03:00:55 +00003312 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
John McCall5500ef22011-08-17 22:09:46 +00003313 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3314 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003315 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003316 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3317 FnRetType, RetValExp);
3318 if (Res.isInvalid()) {
3319 // FIXME: Cleanup temporaries here, anyway?
3320 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003321 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003322 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003323 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003324 } else {
Richard Trieu09c163b2018-03-15 03:00:55 +00003325 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Steve Naroffc540d662008-09-03 18:15:37 +00003326 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003327
John McCall75f92b52011-08-17 21:34:14 +00003328 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003329 ExprResult ER =
3330 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003331 if (ER.isInvalid())
3332 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003333 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003334 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003335 auto *Result =
3336 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003337
Jordan Rosed39e5f12012-07-02 21:19:23 +00003338 // If we need to check for the named return value optimization,
3339 // or if we need to infer the return type,
3340 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003341 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003342 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343
Richard Smith9f690bd2015-10-27 06:02:45 +00003344 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3345 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3346
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003347 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003348}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003349
Nico Weber72889432014-09-06 01:25:55 +00003350namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003351/// Marks all typedefs in all local classes in a type referenced.
Nico Weber72889432014-09-06 01:25:55 +00003352///
3353/// In a function like
3354/// auto f() {
3355/// struct S { typedef int a; };
3356/// return S();
3357/// }
3358///
3359/// the local type escapes and could be referenced in some TUs but not in
3360/// others. Pretend that all local typedefs are always referenced, to not warn
3361/// on this. This isn't necessary if f has internal linkage, or the typedef
3362/// is private.
3363class LocalTypedefNameReferencer
3364 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3365public:
3366 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3367 bool VisitRecordType(const RecordType *RT);
3368private:
3369 Sema &S;
3370};
3371bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3372 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3373 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3374 R->isDependentType())
3375 return true;
3376 for (auto *TmpD : R->decls())
3377 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3378 if (T->getAccess() != AS_private || R->hasFriends())
3379 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3380 return true;
3381}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003382}
Nico Weber72889432014-09-06 01:25:55 +00003383
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003384TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003385 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003386 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3387 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003388 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003389}
3390
Richard Smith2a7d4812013-05-04 07:00:32 +00003391/// Deduce the return type for a function from a returned expression, per
3392/// C++1y [dcl.spec.auto]p6.
3393bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3394 SourceLocation ReturnLoc,
3395 Expr *&RetExpr,
3396 AutoType *AT) {
Richard Smith50e291e2018-01-02 23:52:42 +00003397 // If this is the conversion function for a lambda, we choose to deduce it
3398 // type from the corresponding call operator, not from the synthesized return
3399 // statement within it. See Sema::DeduceReturnType.
3400 if (isLambdaConversionOperator(FD))
3401 return false;
3402
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003403 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003404 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003405
Richard Smithc58f38f2013-08-14 20:16:31 +00003406 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3407 // If the deduction is for a return statement and the initializer is
3408 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003409 Diag(RetExpr->getExprLoc(),
3410 getCurLambda() ? diag::err_lambda_return_init_list
3411 : diag::err_auto_fn_return_init_list)
3412 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003413 return true;
3414 }
3415
3416 if (FD->isDependentContext()) {
3417 // C++1y [dcl.spec.auto]p12:
3418 // Return type deduction [...] occurs when the definition is
3419 // instantiated even if the function body contains a return
3420 // statement with a non-type-dependent operand.
3421 assert(AT->isDeduced() && "should have deduced to dependent type");
3422 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003423 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003424
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003425 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003426 // Otherwise, [...] deduce a value for U using the rules of template
3427 // argument deduction.
3428 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3429
3430 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3431 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3432 << OrigResultType.getType() << RetExpr->getType();
3433
3434 if (DAR != DAR_Succeeded)
3435 return true;
Nico Weber72889432014-09-06 01:25:55 +00003436
3437 // If a local type is part of the returned type, mark its fields as
3438 // referenced.
3439 LocalTypedefNameReferencer Referencer(*this);
3440 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003441 } else {
3442 // In the case of a return with no operand, the initializer is considered
3443 // to be void().
3444 //
3445 // Deduction here can only succeed if the return type is exactly 'cv auto'
3446 // or 'decltype(auto)', so just check for that case directly.
3447 if (!OrigResultType.getType()->getAs<AutoType>()) {
3448 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3449 << OrigResultType.getType();
3450 return true;
3451 }
3452 // We always deduce U = void in this case.
3453 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3454 if (Deduced.isNull())
3455 return true;
3456 }
3457
3458 // If a function with a declared return type that contains a placeholder type
3459 // has multiple return statements, the return type is deduced for each return
3460 // statement. [...] if the type deduced is not the same in each deduction,
3461 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003462 QualType DeducedT = AT->getDeducedType();
3463 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003464 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003465 // It is possible that NewAT->getDeducedType() is null. When that happens,
3466 // we should not crash, instead we ignore this deduction.
3467 if (NewAT->getDeducedType().isNull())
3468 return false;
3469
Douglas Gregora602a152015-10-01 20:20:47 +00003470 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003471 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003472 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3473 NewAT->getDeducedType());
3474 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003475 const LambdaScopeInfo *LambdaSI = getCurLambda();
3476 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3477 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003478 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003479 << true /*IsLambda*/;
3480 } else {
3481 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3482 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003483 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003484 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003485 return true;
3486 }
3487 } else if (!FD->isInvalidDecl()) {
3488 // Update all declarations of the function to have the deduced return type.
3489 Context.adjustDeducedFunctionResultType(FD, Deduced);
3490 }
3491
3492 return false;
3493}
3494
John McCalldadc5752010-08-24 06:29:42 +00003495StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003496Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3497 Scope *CurScope) {
3498 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Faisal Valid143a0c2017-04-01 21:30:49 +00003499 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3500 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003501 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003502
Taiju Tsuiki3be68e12018-06-19 05:35:30 +00003503 if (VarDecl *VD =
3504 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3505 CurScope->addNRVOCandidate(VD);
3506 } else {
3507 CurScope->setNoNRVO();
3508 }
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003509
Nico Weberd64657f2015-03-09 02:47:59 +00003510 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3511
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003512 return R;
3513}
3514
3515StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003516 // Check for unexpanded parameter packs.
3517 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3518 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003519
Eli Friedman34b49062012-01-26 03:00:14 +00003520 if (isa<CapturingScopeInfo>(getCurFunction()))
3521 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003522
Chris Lattner79413952008-12-04 23:50:19 +00003523 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003524 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003525 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003526 bool isObjCMethod = false;
3527
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003528 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003529 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003530 if (FD->hasAttrs())
3531 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003532 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003533 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003534 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003535 if (FD->isMain() && RetValExp)
3536 if (isa<CXXBoolLiteralExpr>(RetValExp))
3537 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3538 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003539 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003540 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003541 isObjCMethod = true;
3542 if (MD->hasAttrs())
3543 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003544 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3545 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003546 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003547 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003548 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3549 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003550 }
3551 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003552 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003553
Richard Smithb130fe72016-06-23 19:16:49 +00003554 // C++1z: discarded return statements are not considered when deducing a
3555 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003556 if (ExprEvalContexts.back().Context ==
3557 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003558 FnRetType->getContainedAutoType()) {
3559 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003560 ExprResult ER =
3561 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smithb130fe72016-06-23 19:16:49 +00003562 if (ER.isInvalid())
3563 return StmtError();
3564 RetValExp = ER.get();
3565 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003566 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3567 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003568 }
3569
Richard Smith2a7d4812013-05-04 07:00:32 +00003570 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3571 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003572 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003573 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3574 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003575 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003576 FD->setInvalidDecl();
3577 return StmtError();
3578 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003579 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003580 }
3581 }
3582 }
3583
Richard Smithc58f38f2013-08-14 20:16:31 +00003584 bool HasDependentReturnType = FnRetType->isDependentType();
3585
Craig Topperc3ec1492014-05-26 06:22:03 +00003586 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003587 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003588 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003589 if (isa<InitListExpr>(RetValExp)) {
3590 // We simply never allow init lists as the return value of void
3591 // functions. This is compatible because this was never allowed before,
3592 // so there's no legacy code to deal with.
3593 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3594 int FunctionKind = 0;
3595 if (isa<ObjCMethodDecl>(CurDecl))
3596 FunctionKind = 1;
3597 else if (isa<CXXConstructorDecl>(CurDecl))
3598 FunctionKind = 2;
3599 else if (isa<CXXDestructorDecl>(CurDecl))
3600 FunctionKind = 3;
3601
3602 Diag(ReturnLoc, diag::err_return_init_list)
3603 << CurDecl->getDeclName() << FunctionKind
3604 << RetValExp->getSourceRange();
3605
3606 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003607 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003608 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003609 // C99 6.8.6.4p1 (ext_ since GCC warns)
3610 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003611 if (RetValExp->getType()->isVoidType()) {
3612 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3613 if (isa<CXXConstructorDecl>(CurDecl) ||
3614 isa<CXXDestructorDecl>(CurDecl))
3615 D = diag::err_ctor_dtor_returns_void;
3616 else
3617 D = diag::ext_return_has_void_expr;
3618 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003619 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003620 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003621 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003622 if (Result.isInvalid())
3623 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003624 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003625 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003626 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003627 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003628 // return of void in constructor/destructor is illegal in C++.
3629 if (D == diag::err_ctor_dtor_returns_void) {
3630 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3631 Diag(ReturnLoc, D)
3632 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3633 << RetValExp->getSourceRange();
3634 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003635 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003636 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003637 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003638 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003639
3640 int FunctionKind = 0;
3641 if (isa<ObjCMethodDecl>(CurDecl))
3642 FunctionKind = 1;
3643 else if (isa<CXXConstructorDecl>(CurDecl))
3644 FunctionKind = 2;
3645 else if (isa<CXXDestructorDecl>(CurDecl))
3646 FunctionKind = 3;
3647
Nick Lewycky1be750a2011-06-01 07:44:31 +00003648 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003649 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003650 << RetValExp->getSourceRange();
3651 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003652 }
Mike Stump11289f42009-09-09 15:08:12 +00003653
Sebastian Redleef474c2012-02-22 10:50:08 +00003654 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003655 ExprResult ER =
3656 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003657 if (ER.isInvalid())
3658 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003659 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003660 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Bruno Ricci023b1d12018-10-30 14:40:49 +00003663 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3664 /* NRVOCandidate=*/nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003665 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003666 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003667
David Majnemer2887ad32014-12-13 08:12:56 +00003668 unsigned DiagID;
3669 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3670 // C++11 [stmt.return]p2
3671 DiagID = diag::err_constexpr_return_missing_expr;
3672 FD->setInvalidDecl();
3673 } else if (getLangOpts().C99) {
3674 // C99 6.8.6.4p1 (ext_ since GCC warns)
3675 DiagID = diag::ext_return_missing_expr;
3676 } else {
3677 // C90 6.6.6.4p4
3678 DiagID = diag::warn_return_missing_expr;
3679 }
3680
3681 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003682 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003683 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003684 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003685
Bruno Ricci023b1d12018-10-30 14:40:49 +00003686 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3687 /* NRVOCandidate=*/nullptr);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003688 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003689 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003690 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003691
3692 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3693
3694 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3695 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3696 // function return.
3697
3698 // In C++ the return statement is handled via a copy initialization,
3699 // the C version of which boils down to CheckSingleAssignmentConstraints.
3700 if (RetValExp)
Richard Trieu09c163b2018-03-15 03:00:55 +00003701 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Richard Smith2a7d4812013-05-04 07:00:32 +00003702 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003703 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003705 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003706 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003707 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003708 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003709 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003710 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003711 return StmtError();
3712 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003713 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003714
3715 // If we have a related result type, we need to implicitly
3716 // convert back to the formal result type. We can't pretend to
3717 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003718 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003719 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003720 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3721 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003722 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3723 if (Res.isInvalid()) {
3724 // FIXME: Clean up temporaries here anyway?
3725 return StmtError();
3726 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003727 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003728 }
3729
Artyom Skrobov9f213442014-01-24 11:10:39 +00003730 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3731 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733
John McCallacf0ee52010-10-08 02:01:28 +00003734 if (RetValExp) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003735 ExprResult ER =
3736 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003737 if (ER.isInvalid())
3738 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003739 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003740 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003741 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743
3744 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003745 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003746 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003747 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003748
Richard Smith9f690bd2015-10-27 06:02:45 +00003749 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3750 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3751
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003752 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003753}
3754
John McCalldadc5752010-08-24 06:29:42 +00003755StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003756Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003757 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003758 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003759 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003760 if (Var && Var->isInvalidDecl())
3761 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003763 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003764}
3765
John McCalldadc5752010-08-24 06:29:42 +00003766StmtResult
John McCallb268a282010-08-23 23:25:46 +00003767Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003768 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003769}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003770
John McCalldadc5752010-08-24 06:29:42 +00003771StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003773 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003774 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003775 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3776
Reid Kleckner87a31802018-03-12 21:43:02 +00003777 setFunctionHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003778 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003779 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3780 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003781}
3782
John McCall0bd3e402012-05-08 21:41:25 +00003783StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003784 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003785 ExprResult Result = DefaultLvalueConversion(Throw);
3786 if (Result.isInvalid())
3787 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003788
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003789 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
Richard Smith945f8d32013-01-14 22:39:08 +00003790 if (Result.isInvalid())
3791 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003792 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003793
Douglas Gregor2900c162010-04-22 21:44:01 +00003794 QualType ThrowType = Throw->getType();
3795 // Make sure the expression type is an ObjC pointer or "void *".
3796 if (!ThrowType->isDependentType() &&
3797 !ThrowType->isObjCObjectPointerType()) {
3798 const PointerType *PT = ThrowType->getAs<PointerType>();
3799 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003800 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003801 << Throw->getType() << Throw->getSourceRange());
3802 }
3803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003805 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003806}
3807
John McCalldadc5752010-08-24 06:29:42 +00003808StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003810 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003811 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003812 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3813
John McCallb268a282010-08-23 23:25:46 +00003814 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003815 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003816 // in the context of an @catch clause).
3817 Scope *AtCatchParent = CurScope;
3818 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3819 AtCatchParent = AtCatchParent->getParent();
3820 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003821 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822 }
John McCallb268a282010-08-23 23:25:46 +00003823 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003824}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003825
John McCalld9bb7432011-07-27 21:50:02 +00003826ExprResult
3827Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3828 ExprResult result = DefaultLvalueConversion(operand);
3829 if (result.isInvalid())
3830 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003831 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003832
3833 // Make sure the expression type is an ObjC pointer or "void *".
3834 QualType type = operand->getType();
3835 if (!type->isDependentType() &&
3836 !type->isObjCObjectPointerType()) {
3837 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003838 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3839 if (getLangOpts().CPlusPlus) {
3840 if (RequireCompleteType(atLoc, type,
3841 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003842 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003843 << type << operand->getSourceRange();
3844
3845 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003846 if (result.isInvalid())
3847 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003848 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003849 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003850 << type << operand->getSourceRange();
3851
3852 operand = result.get();
3853 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003854 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003855 << type << operand->getSourceRange();
3856 }
3857 }
John McCalld9bb7432011-07-27 21:50:02 +00003858 }
3859
3860 // The operand to @synchronized is a full-expression.
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00003861 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
John McCalld9bb7432011-07-27 21:50:02 +00003862}
3863
John McCalldadc5752010-08-24 06:29:42 +00003864StmtResult
John McCallb268a282010-08-23 23:25:46 +00003865Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3866 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003867 // We can't jump into or indirect-jump out of a @synchronized block.
Reid Kleckner87a31802018-03-12 21:43:02 +00003868 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003869 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003870}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003871
3872/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3873/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003874StmtResult
John McCall48871652010-08-21 09:40:31 +00003875Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003876 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003877 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003878 return new (Context)
3879 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003880}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003881
John McCall31168b02011-06-15 23:02:42 +00003882StmtResult
3883Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
Reid Kleckner87a31802018-03-12 21:43:02 +00003884 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003885 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003886}
3887
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003888namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003889class CatchHandlerType {
3890 QualType QT;
3891 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003892
Aaron Ballman8aee642902015-04-08 00:05:29 +00003893 // This is a special constructor to be used only with DenseMapInfo's
3894 // getEmptyKey() and getTombstoneKey() functions.
3895 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3896 enum Unique { ForDenseMap };
3897 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3898
Sebastian Redl63c4da02009-07-29 17:15:45 +00003899public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003900 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003901 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003902 /// level pointer and cv-qualifiers.
3903 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3904 if (QT->isPointerType())
3905 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003906
Aaron Ballman8aee642902015-04-08 00:05:29 +00003907 if (IsPointer || QT->isReferenceType())
3908 QT = QT->getPointeeType();
3909 QT = QT.getUnqualifiedType();
3910 }
3911
3912 /// Used when creating a CatchHandlerType from a base class type; pretends the
3913 /// type passed in had the pointer qualifier, does not need to get an
3914 /// unqualified type.
3915 CatchHandlerType(QualType QT, bool IsPointer)
3916 : QT(QT), IsPointer(IsPointer) {}
3917
3918 QualType underlying() const { return QT; }
3919 bool isPointer() const { return IsPointer; }
3920
3921 friend bool operator==(const CatchHandlerType &LHS,
3922 const CatchHandlerType &RHS) {
3923 // If the pointer qualification does not match, we can return early.
3924 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003925 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003926 // Otherwise, check the underlying type without cv-qualifiers.
3927 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003928 }
3929};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003930} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003931
Aaron Ballman8aee642902015-04-08 00:05:29 +00003932namespace llvm {
3933template <> struct DenseMapInfo<CatchHandlerType> {
3934 static CatchHandlerType getEmptyKey() {
3935 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3936 CatchHandlerType::ForDenseMap);
3937 }
3938
3939 static CatchHandlerType getTombstoneKey() {
3940 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3941 CatchHandlerType::ForDenseMap);
3942 }
3943
3944 static unsigned getHashValue(const CatchHandlerType &Base) {
3945 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3946 }
3947
3948 static bool isEqual(const CatchHandlerType &LHS,
3949 const CatchHandlerType &RHS) {
3950 return LHS == RHS;
3951 }
3952};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003953}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003954
3955namespace {
3956class CatchTypePublicBases {
3957 ASTContext &Ctx;
3958 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3959 const bool CheckAgainstPointer;
3960
3961 CXXCatchStmt *FoundHandler;
3962 CanQualType FoundHandlerType;
3963
3964public:
3965 CatchTypePublicBases(
3966 ASTContext &Ctx,
3967 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3968 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3969 FoundHandler(nullptr) {}
3970
3971 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3972 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3973
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003974 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003975 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003976 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003977 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003978 auto I = M.find(Check);
3979 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003980 FoundHandler = I->second;
3981 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003982 return true;
3983 }
3984 }
3985 return false;
3986 }
3987};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003988}
Dan Gohman28ade552010-07-26 21:25:24 +00003989
Sebastian Redl9b244a82008-12-22 21:35:02 +00003990/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3991/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003992StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3993 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003994 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003995 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +00003996 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +00003997 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +00003998 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
Alexey Bataevc416e642019-02-08 18:02:25 +00003999 }
Anders Carlsson68b36af2011-02-19 19:26:44 +00004000
Justin Lebar2a8db342016-09-28 22:45:54 +00004001 // Exceptions aren't allowed in CUDA device code.
4002 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00004003 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4004 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00004005
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004006 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4007 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4008
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004009 sema::FunctionScopeInfo *FSI = getCurFunction();
4010
Reid Klecknere7175912015-02-02 22:15:31 +00004011 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004012 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00004013 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004014 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00004015 }
4016
Robert Wilhelmcafda822013-08-22 09:20:03 +00004017 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00004018 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00004019 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00004020
Aaron Ballman8aee642902015-04-08 00:05:29 +00004021 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004022 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004023 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004024
Aaron Ballman8aee642902015-04-08 00:05:29 +00004025 // Diagnose when the handler is a catch-all handler, but it isn't the last
4026 // handler for the try block. [except.handle]p5. Also, skip exception
4027 // declarations that are invalid, since we can't usefully report on them.
4028 if (!H->getExceptionDecl()) {
4029 if (i < NumHandlers - 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004030 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00004031 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00004032 } else if (H->getExceptionDecl()->isInvalidDecl())
4033 continue;
4034
4035 // Walk the type hierarchy to diagnose when this type has already been
4036 // handled (duplication), or cannot be handled (derivation inversion). We
4037 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00004038 CatchHandlerType HandlerCHT =
4039 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00004040
4041 // We can ignore whether the type is a reference or a pointer; we need the
4042 // underlying declaration type in order to get at the underlying record
4043 // decl, if there is one.
4044 QualType Underlying = HandlerCHT.underlying();
4045 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4046 if (!RD->hasDefinition())
4047 continue;
4048 // Check that none of the public, unambiguous base classes are in the
4049 // map ([except.handle]p1). Give the base classes the same pointer
4050 // qualification as the original type we are basing off of. This allows
4051 // comparison against the handler type using the same top-level pointer
4052 // as the original type.
4053 CXXBasePaths Paths;
4054 Paths.setOrigin(RD);
4055 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004056 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004057 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4058 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4059 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4060 diag::warn_exception_caught_by_earlier_handler)
4061 << H->getCaughtType();
4062 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4063 diag::note_previous_exception_handler)
4064 << Problem->getCaughtType();
4065 }
4066 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00004067 }
Mike Stump11289f42009-09-09 15:08:12 +00004068
Aaron Ballman8aee642902015-04-08 00:05:29 +00004069 // Add the type the list of ones we have handled; diagnose if we've already
4070 // handled it.
4071 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4072 if (!R.second) {
4073 const CXXCatchStmt *Problem = R.first->second;
4074 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4075 diag::warn_exception_caught_by_earlier_handler)
4076 << H->getCaughtType();
4077 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4078 diag::note_previous_exception_handler)
4079 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00004080 }
4081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004083 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00004084
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004085 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00004086}
John Wiegley1c0675e2011-04-28 01:08:34 +00004087
Reid Klecknere7175912015-02-02 22:15:31 +00004088StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4089 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004090 assert(TryBlock && Handler);
4091
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004092 sema::FunctionScopeInfo *FSI = getCurFunction();
4093
Reid Klecknere7175912015-02-02 22:15:31 +00004094 // SEH __try is incompatible with C++ try. Borland appears to support this,
4095 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004096 if (!getLangOpts().Borland) {
4097 if (FSI->FirstCXXTryLoc.isValid()) {
4098 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4099 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4100 }
Reid Klecknere7175912015-02-02 22:15:31 +00004101 }
John Wiegley1c0675e2011-04-28 01:08:34 +00004102
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004103 FSI->setHasSEHTry(TryLoc);
4104
4105 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4106 // track if they use SEH.
4107 DeclContext *DC = CurContext;
4108 while (DC && !DC->isFunctionOrMethod())
4109 DC = DC->getParent();
4110 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4111 if (FD)
4112 FD->setUsesSEHTry(true);
4113 else
4114 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00004115
Reid Kleckner8819a402015-07-10 00:16:25 +00004116 // Reject __try on unsupported targets.
4117 if (!Context.getTargetInfo().isSEHTrySupported())
4118 Diag(TryLoc, diag::err_seh_try_unsupported);
4119
Reid Klecknere7175912015-02-02 22:15:31 +00004120 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00004121}
4122
4123StmtResult
4124Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4125 Expr *FilterExpr,
4126 Stmt *Block) {
4127 assert(FilterExpr && Block);
4128
4129 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00004130 return StmtError(Diag(FilterExpr->getExprLoc(),
4131 diag::err_filter_expression_integral)
4132 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00004133 }
4134
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004135 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004136}
4137
Nico Weberd64657f2015-03-09 02:47:59 +00004138void Sema::ActOnStartSEHFinallyBlock() {
4139 CurrentSEHFinally.push_back(CurScope);
4140}
4141
Nico Weberce903292015-03-09 03:17:15 +00004142void Sema::ActOnAbortSEHFinallyBlock() {
4143 CurrentSEHFinally.pop_back();
4144}
4145
Nico Weberd64657f2015-03-09 02:47:59 +00004146StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004147 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00004148 CurrentSEHFinally.pop_back();
4149 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004150}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004151
Nico Weberc7d05962014-07-06 22:32:59 +00004152StmtResult
4153Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00004154 Scope *SEHTryParent = CurScope;
4155 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4156 SEHTryParent = SEHTryParent->getParent();
4157 if (!SEHTryParent)
4158 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00004159 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00004160
Nico Weber9b982072014-07-07 00:12:30 +00004161 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00004162}
4163
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004164StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4165 bool IsIfExists,
4166 NestedNameSpecifierLoc QualifierLoc,
4167 DeclarationNameInfo NameInfo,
4168 Stmt *Nested)
4169{
4170 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004171 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004172 cast<CompoundStmt>(Nested));
4173}
4174
4175
Chad Rosier02a84392012-08-10 17:56:09 +00004176StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004177 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004178 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004179 UnqualifiedId &Name,
4180 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00004181 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004182 SS.getWithLocInContext(Context),
4183 GetNameFromUnqualifiedId(Name),
4184 Nested);
4185}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004186
4187RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00004188Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4189 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004190 DeclContext *DC = CurContext;
4191 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4192 DC = DC->getParent();
4193
Craig Topperc3ec1492014-05-26 06:22:03 +00004194 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004195 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004196 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4197 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004198 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004199 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004200
Alexey Bataev330de032014-10-29 12:21:55 +00004201 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004202 DC->addDecl(RD);
4203 RD->setImplicit();
4204 RD->startDefinition();
4205
Alexey Bataev9959db52014-05-06 10:08:46 +00004206 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004207 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004208 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004209 return RD;
4210}
4211
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004212static void
4213buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
4214 SmallVectorImpl<Expr *> &CaptureInits,
4215 ArrayRef<sema::Capture> Candidates) {
4216 for (const sema::Capture &Cap : Candidates) {
4217 if (Cap.isThisCapture()) {
4218 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004219 CapturedStmt::VCK_This));
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004220 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004221 continue;
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004222 } else if (Cap.isVLATypeCapture()) {
Alexey Bataev330de032014-10-29 12:21:55 +00004223 Captures.push_back(
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004224 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
Alexey Bataev330de032014-10-29 12:21:55 +00004225 CaptureInits.push_back(nullptr);
4226 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004227 }
4228
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004229 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4230 Cap.isReferenceCapture()
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004231 ? CapturedStmt::VCK_ByRef
4232 : CapturedStmt::VCK_ByCopy,
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004233 Cap.getVariable()));
4234 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004235 }
4236}
4237
4238void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004239 CapturedRegionKind Kind,
4240 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004241 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004242 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004243
Alexey Bataev9959db52014-05-06 10:08:46 +00004244 // Build the context parameter
4245 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4246 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4247 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004248 auto *Param =
4249 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4250 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004251 DC->addDecl(Param);
4252
4253 CD->setContextParam(0, Param);
4254
4255 // Enter the capturing scope for this captured region.
4256 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4257
4258 if (CurScope)
4259 PushDeclContext(CurScope, CD);
4260 else
4261 CurContext = CD;
4262
Faisal Valid143a0c2017-04-01 21:30:49 +00004263 PushExpressionEvaluationContext(
4264 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004265}
4266
4267void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4268 CapturedRegionKind Kind,
4269 ArrayRef<CapturedParamNameType> Params) {
4270 CapturedDecl *CD = nullptr;
4271 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4272
4273 // Build the context parameter
4274 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4275 bool ContextIsFound = false;
4276 unsigned ParamNum = 0;
4277 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4278 E = Params.end();
4279 I != E; ++I, ++ParamNum) {
4280 if (I->second.isNull()) {
4281 assert(!ContextIsFound &&
4282 "null type has been found already for '__context' parameter");
4283 IdentifierInfo *ParamName = &Context.Idents.get("__context");
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004284 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4285 .withConst()
4286 .withRestrict();
Alexey Bataev56223232017-06-09 13:40:18 +00004287 auto *Param =
4288 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4289 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004290 DC->addDecl(Param);
4291 CD->setContextParam(ParamNum, Param);
4292 ContextIsFound = true;
4293 } else {
4294 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004295 auto *Param =
4296 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4297 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004298 DC->addDecl(Param);
4299 CD->setParam(ParamNum, Param);
4300 }
4301 }
4302 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004303 if (!ContextIsFound) {
4304 // Add __context implicitly if it is not specified.
4305 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4306 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004307 auto *Param =
4308 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4309 ImplicitParamDecl::CapturedContext);
Alexey Bataev301a2d92014-05-14 10:40:54 +00004310 DC->addDecl(Param);
4311 CD->setContextParam(ParamNum, Param);
4312 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004313 // Enter the capturing scope for this captured region.
4314 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4315
4316 if (CurScope)
4317 PushDeclContext(CurScope, CD);
4318 else
4319 CurContext = CD;
4320
Faisal Valid143a0c2017-04-01 21:30:49 +00004321 PushExpressionEvaluationContext(
4322 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004323}
4324
Wei Pan17fbf6e2013-05-04 03:59:06 +00004325void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004326 DiscardCleanupsInEvaluationContext();
4327 PopExpressionEvaluationContext();
4328
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004329 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4330 RecordDecl *Record = RSI->TheRecordDecl;
4331 Record->setInvalidDecl();
4332
Aaron Ballman62e47c42014-03-10 13:43:55 +00004333 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004334 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00004335 SourceLocation(), SourceLocation(), ParsedAttributesView());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004336
Wei Pan17fbf6e2013-05-04 03:59:06 +00004337 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004338 PopFunctionScopeInfo();
4339}
4340
4341StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4342 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4343
4344 SmallVector<CapturedStmt::Capture, 4> Captures;
4345 SmallVector<Expr *, 4> CaptureInits;
4346 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4347
4348 CapturedDecl *CD = RSI->TheCapturedDecl;
4349 RecordDecl *RD = RSI->TheRecordDecl;
4350
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004351 CapturedStmt *Res = CapturedStmt::Create(
4352 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4353 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004354
4355 CD->setBody(Res->getCapturedStmt());
4356 RD->completeDefinition();
4357
Wei Pan17fbf6e2013-05-04 03:59:06 +00004358 DiscardCleanupsInEvaluationContext();
4359 PopExpressionEvaluationContext();
4360
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004361 PopDeclContext();
4362 PopFunctionScopeInfo();
4363
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004364 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004365}