blob: c170d74ca5e931ec692fe9030c548f15bee3d971 [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
Richard Smith50e291e2018-01-02 23:52:42 +000017#include "clang/AST/ASTLambda.h"
John McCall03318c12011-11-11 03:57:31 +000018#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000023#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000024#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000028#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000035#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000036#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000037#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000038#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000039#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000040#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000041
Chris Lattneraf8d5812006-11-10 05:07:45 +000042using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000043using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000044
Richard Smith945f8d32013-01-14 22:39:08 +000045StmtResult Sema::ActOnExprStmt(ExprResult FE) {
46 if (FE.isInvalid())
47 return StmtError();
48
49 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
50 /*DiscardedValue*/ true);
51 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000052 return StmtError();
53
Chris Lattner903eb512008-07-25 23:18:17 +000054 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
55 // void expression for its side effects. Conversion to void allows any
56 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000057
Chris Lattner903eb512008-07-25 23:18:17 +000058 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000059 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000060}
61
62
John McCalleaef89b2013-03-22 02:10:40 +000063StmtResult Sema::ActOnExprStmtError() {
64 DiscardCleanupsInEvaluationContext();
65 return StmtError();
66}
67
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000068StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000069 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000070 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000071}
72
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000073StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
74 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000075 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000076
Chris Lattnercbafe8d2009-04-12 20:13:14 +000077 // If we have an invalid decl, just return an error.
78 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000079
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000080 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000081}
Chris Lattneraf8d5812006-11-10 05:07:45 +000082
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000083void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000084 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000085
Douglas Gregor2eb1c572013-04-08 20:52:24 +000086 // If we don't have a declaration, or we have an invalid declaration,
87 // just return.
88 if (DG.isNull() || !DG.isSingleDecl())
89 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000090
Douglas Gregor2eb1c572013-04-08 20:52:24 +000091 Decl *decl = DG.getSingleDecl();
92 if (!decl || decl->isInvalidDecl())
93 return;
94
95 // Only variable declarations are permitted.
96 VarDecl *var = dyn_cast<VarDecl>(decl);
97 if (!var) {
98 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
99 decl->setInvalidDecl();
100 return;
101 }
John McCall31168b02011-06-15 23:02:42 +0000102
John McCalld4631322011-06-17 06:42:21 +0000103 // foreach variables are never actually initialized in the way that
104 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000106
John McCalld4631322011-06-17 06:42:21 +0000107 // In ARC, we don't need to retain the iteration variable of a fast
108 // enumeration loop. Rather than actually trying to catch that
109 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000110 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000111 QualType type = var->getType();
112
113 // Only do this if we inferred the lifetime. Inferred lifetime
114 // will show up as a local qualifier because explicit lifetime
115 // should have shown up as an AttributedType instead.
116 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
117 // Add 'const' and mark the variable as pseudo-strong.
118 var->setType(type.withConst());
119 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000120 }
121 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000122}
123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000124/// Diagnose unused comparisons, both builtin and overloaded operators.
Richard Trieu99e1c952014-03-11 03:11:08 +0000125/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000126///
127/// Adding a cast to void (or other expression wrappers) will prevent the
128/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000129static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130 SourceLocation Loc;
Richard Smithc70f1d62017-12-14 15:16:18 +0000131 bool CanAssign;
132 enum { Equality, Inequality, Relational, ThreeWay } Kind;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000133
134 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000135 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000136 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137
Richard Smithc70f1d62017-12-14 15:16:18 +0000138 if (Op->getOpcode() == BO_EQ)
139 Kind = Equality;
140 else if (Op->getOpcode() == BO_NE)
141 Kind = Inequality;
142 else if (Op->getOpcode() == BO_Cmp)
143 Kind = ThreeWay;
144 else {
145 assert(Op->isRelationalOp());
146 Kind = Relational;
147 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000148 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000149 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000150 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000151 switch (Op->getOperator()) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000152 case OO_EqualEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000153 Kind = Equality;
154 break;
Richard Trieu99e1c952014-03-11 03:11:08 +0000155 case OO_ExclaimEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000156 Kind = Inequality;
Richard Trieu99e1c952014-03-11 03:11:08 +0000157 break;
158 case OO_Less:
159 case OO_Greater:
160 case OO_GreaterEqual:
161 case OO_LessEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000162 Kind = Relational;
Richard Trieu99e1c952014-03-11 03:11:08 +0000163 break;
Richard Smithc70f1d62017-12-14 15:16:18 +0000164 case OO_Spaceship:
165 Kind = ThreeWay;
166 break;
167 default:
168 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000170
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000173 } else {
174 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000175 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000176 }
177
178 // Suppress warnings when the operator, suspicious as it may be, comes from
179 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000180 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000181 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000182
Chandler Carruthe2669392011-08-17 09:34:37 +0000183 S.Diag(Loc, diag::warn_unused_comparison)
Richard Smithc70f1d62017-12-14 15:16:18 +0000184 << (unsigned)Kind << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000185
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000186 // If the LHS is a plausible entity to assign to, provide a fixit hint to
187 // correct common typos.
Richard Smithc70f1d62017-12-14 15:16:18 +0000188 if (CanAssign) {
189 if (Kind == Inequality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000190 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
191 << FixItHint::CreateReplacement(Loc, "|=");
Richard Smithc70f1d62017-12-14 15:16:18 +0000192 else if (Kind == Equality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000193 S.Diag(Loc, diag::note_equality_comparison_to_assign)
194 << FixItHint::CreateReplacement(Loc, "=");
195 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000196
197 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000198}
199
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000200void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000201 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
202 return DiagnoseUnusedExprResult(Label->getSubStmt());
203
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000204 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000205 if (!E)
206 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000207
208 // If we are in an unevaluated expression context, then there can be no unused
209 // results because the results aren't expected to be used in the first place.
210 if (isUnevaluatedContext())
211 return;
212
Nico Weber0e631632015-10-27 19:47:40 +0000213 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000214 // In most cases, we don't want to warn if the expression is written in a
215 // macro body, or if the macro comes from a system header. If the offending
216 // expression is a call to a function with the warn_unused_result attribute,
217 // we warn no matter the location. Because of the order in which the various
218 // checks need to happen, we factor out the macro-related test here.
Fangrui Song6907ce22018-07-30 19:24:48 +0000219 bool ShouldSuppress =
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000220 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
221 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000222
Eli Friedmanc11535c2012-05-24 00:47:05 +0000223 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000224 SourceLocation Loc;
225 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000226 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner6dc7e572012-08-31 22:39:21 +0000229 // If this is a GNU statement expression expanded from a macro, it is probably
230 // unused because it is a function-like macro that can be used as either an
231 // expression or statement. Don't warn, because it is almost certainly a
232 // false positive.
233 if (isa<StmtExpr>(E) && Loc.isMacroID())
234 return;
235
Nico Weber0e631632015-10-27 19:47:40 +0000236 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
237 // That macro is frequently used to suppress "unused parameter" warnings,
238 // but its implementation makes clang's -Wunused-value fire. Prevent this.
239 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
240 SourceLocation SpellLoc = Loc;
241 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
242 return;
243 }
244
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000245 // Okay, we have an unused result. Depending on what the base expression is,
246 // we might want to make a more specific diagnostic. Check for one of these
247 // cases now.
248 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000249 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000250 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000251 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
252 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000253
Chandler Carruthe2669392011-08-17 09:34:37 +0000254 if (DiagnoseUnusedComparison(*this, E))
255 return;
256
Eli Friedmanc11535c2012-05-24 00:47:05 +0000257 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000258 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000259 if (E->getType()->isVoidType())
260 return;
261
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000263 // a more specific message to make it clear what is happening. If the call
264 // is written in a macro body, only warn if it has the warn_unused_result
265 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000266 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000267 if (const Attr *A = isa<FunctionDecl>(FD)
268 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
269 : FD->getAttr<WarnUnusedResultAttr>()) {
270 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000271 return;
272 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000273 if (ShouldSuppress)
274 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000275 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000276 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
277 return;
278 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000279 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000280 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
281 return;
282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000284 } else if (ShouldSuppress)
285 return;
286
287 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000288 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000289 Diag(Loc, diag::err_arc_unused_init_message) << R1;
290 return;
291 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000292 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000293 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000294 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
295 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000296 return;
297 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000298 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000299 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
300 const Expr *Source = POE->getSyntacticForm();
301 if (isa<ObjCSubscriptRefExpr>(Source))
302 DiagID = diag::warn_unused_container_subscript_expr;
303 else
304 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000305 } else if (const CXXFunctionalCastExpr *FC
306 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000307 const Expr *E = FC->getSubExpr();
308 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
309 E = TE->getSubExpr();
310 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000311 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000312 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
313 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
314 if (!RD->getAttr<WarnUnusedAttr>())
315 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000316 }
John McCall2351cb92010-04-06 22:24:14 +0000317 // Diagnose "(void*) blah" as a typo for "(void) blah".
318 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
319 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
320 QualType T = TI->getType();
321
322 // We really do want to use the non-canonical type here.
323 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000324 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000325
326 Diag(Loc, diag::warn_unused_voidptr)
327 << FixItHint::CreateRemoval(TL.getStarLoc());
328 return;
329 }
330 }
331
Eli Friedmanc11535c2012-05-24 00:47:05 +0000332 if (E->isGLValue() && E->getType().isVolatileQualified()) {
333 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
334 return;
335 }
336
Craig Topperc3ec1492014-05-26 06:22:03 +0000337 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000338}
339
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000340void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
341 PushCompoundScope(IsStmtExpr);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000342}
343
344void Sema::ActOnFinishOfCompoundStmt() {
345 PopCompoundScope();
346}
347
348sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
349 return getCurFunction()->CompoundScopes.back();
350}
351
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000352StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
353 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
354 const unsigned NumElts = Elts.size();
355
Chris Lattnerd864daf2007-08-27 04:29:41 +0000356 // If we're in C89 mode, check that we don't have any decls after stmts. If
357 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000358 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000359 // Note that __extension__ can be around a decl.
360 unsigned i = 0;
361 // Skip over all declarations.
362 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
363 /*empty*/;
364
365 // We found the end of the list or a statement. Scan for another declstmt.
366 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
367 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattnerd864daf2007-08-27 04:29:41 +0000369 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000370 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000371 Diag(D->getLocation(), diag::ext_mixed_decls_code);
372 }
373 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000374 // Warn about unused expressions in statements.
375 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000376 // Ignore statements that are last in a statement expression.
377 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000378 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000379
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000380 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000381 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000382
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000383 // Check for suspicious empty body (null statement) in `for' and `while'
384 // statements. Don't do anything for template instantiations, this just adds
385 // noise.
386 if (NumElts != 0 && !CurrentInstantiationScope &&
387 getCurCompoundScope().HasEmptyLoopBodies) {
388 for (unsigned i = 0; i != NumElts - 1; ++i)
389 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
390 }
391
Benjamin Kramer07420902017-12-24 16:24:20 +0000392 return CompoundStmt::Create(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000393}
394
Richard Smithef6c43d2018-07-26 18:41:30 +0000395ExprResult
396Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
397 if (!Val.get())
398 return Val;
399
400 if (DiagnoseUnexpandedParameterPack(Val.get()))
401 return ExprError();
402
403 // If we're not inside a switch, let the 'case' statement handling diagnose
404 // this. Just clean up after the expression as best we can.
405 if (!getCurFunction()->SwitchStack.empty()) {
406 Expr *CondExpr =
407 getCurFunction()->SwitchStack.back().getPointer()->getCond();
408 if (!CondExpr)
409 return ExprError();
410 QualType CondType = CondExpr->getType();
411
412 auto CheckAndFinish = [&](Expr *E) {
413 if (CondType->isDependentType() || E->isTypeDependent())
414 return ExprResult(E);
415
416 if (getLangOpts().CPlusPlus11) {
417 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
418 // constant expression of the promoted type of the switch condition.
419 llvm::APSInt TempVal;
420 return CheckConvertedConstantExpression(E, CondType, TempVal,
421 CCEK_CaseValue);
422 }
423
424 ExprResult ER = E;
425 if (!E->isValueDependent())
426 ER = VerifyIntegerConstantExpression(E);
427 if (!ER.isInvalid())
428 ER = DefaultLvalueConversion(ER.get());
429 if (!ER.isInvalid())
430 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
431 return ER;
432 };
433
434 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
435 if (Converted.get() == Val.get())
436 Converted = CheckAndFinish(Val.get());
437 if (Converted.isInvalid())
438 return ExprError();
439 Val = Converted;
440 }
441
442 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
443 getLangOpts().CPlusPlus11);
444}
445
John McCalldadc5752010-08-24 06:29:42 +0000446StmtResult
Richard Smithef6c43d2018-07-26 18:41:30 +0000447Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
448 SourceLocation DotDotDotLoc, ExprResult RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000449 SourceLocation ColonLoc) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000450 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
451 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
452 : RHSVal.isInvalid() || RHSVal.get()) &&
453 "missing RHS value");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000454
John McCallaab3e412010-08-25 08:40:02 +0000455 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000456 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000457 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000458 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000459
Richard Smithef6c43d2018-07-26 18:41:30 +0000460 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
461 getCurFunction()->SwitchStack.back().setInt(true);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000462 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000463 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000464
Richard Smith5b555da2014-11-20 01:24:12 +0000465 CaseStmt *CS = new (Context)
Richard Smithef6c43d2018-07-26 18:41:30 +0000466 CaseStmt(LHSVal.get(), RHSVal.get(), CaseLoc, DotDotDotLoc, ColonLoc);
467 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000468 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000469}
470
Chris Lattner34a22092009-03-04 04:23:07 +0000471/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000472void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000473 DiagnoseUnusedExprResult(SubStmt);
474
Chris Lattner34a22092009-03-04 04:23:07 +0000475 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000476 CS->setSubStmt(SubStmt);
477}
478
John McCalldadc5752010-08-24 06:29:42 +0000479StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000480Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000481 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000482 DiagnoseUnusedExprResult(SubStmt);
483
John McCallaab3e412010-08-25 08:40:02 +0000484 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000485 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000486 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000487 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000488
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000489 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Richard Smithef6c43d2018-07-26 18:41:30 +0000490 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000491 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000492}
493
John McCalldadc5752010-08-24 06:29:42 +0000494StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000495Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
496 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000497 // If the label was multiply defined, reject it now.
498 if (TheDecl->getStmt()) {
499 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
500 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000501 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000502 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000503
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000504 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000505 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
506 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000507 if (!TheDecl->isGnuLocal()) {
508 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000509 if (!TheDecl->isMSAsmLabel()) {
510 // Don't update the location of MS ASM labels. These will result in
511 // a diagnostic, and changing the location here will mess that up.
512 TheDecl->setLocation(IdentLoc);
513 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000514 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000515 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000516}
517
Richard Smithc202b282012-04-14 00:33:13 +0000518StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000519 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000520 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000521 // Fill in the declaration and return it.
522 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000523 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000524}
525
Richard Trieufaca2d82016-02-18 23:58:40 +0000526namespace {
527class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
528 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
529 Sema &SemaRef;
530public:
531 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
532 void VisitBinaryOperator(BinaryOperator *E) {
533 if (E->getOpcode() == BO_Comma)
534 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
535 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
536 }
537};
538}
539
John McCalldadc5752010-08-24 06:29:42 +0000540StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000541Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
542 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000543 Stmt *thenStmt, SourceLocation ElseLoc,
544 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000545 if (Cond.isInvalid())
546 Cond = ConditionResult(
547 *this, nullptr,
548 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
549 Context.BoolTy, VK_RValue),
550 IfLoc),
551 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000552
Richard Smithb130fe72016-06-23 19:16:49 +0000553 Expr *CondExpr = Cond.get().second;
Richard Smith03a4aa32016-06-23 19:02:52 +0000554 if (!Diags.isIgnored(diag::warn_comma_operator,
Richard Smithb130fe72016-06-23 19:16:49 +0000555 CondExpr->getExprLoc()))
556 CommaVisitor(*this).Visit(CondExpr);
557
Hans Wennborg59ad1502017-11-20 17:48:54 +0000558 if (!elseStmt)
Hans Wennborg95419752017-11-20 17:38:16 +0000559 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
560 diag::warn_empty_if_body);
Richard Smithb130fe72016-06-23 19:16:49 +0000561
Richard Smitha547eb22016-07-14 00:11:03 +0000562 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
563 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000564}
565
566StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000567 Stmt *InitStmt, ConditionResult Cond,
568 Stmt *thenStmt, SourceLocation ElseLoc,
569 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000570 if (Cond.isInvalid())
571 return StmtError();
572
Erik Pilkington5cd57172016-08-16 17:44:11 +0000573 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Reid Kleckner87a31802018-03-12 21:43:02 +0000574 setFunctionHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000575
576 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000577 DiagnoseUnusedExprResult(elseStmt);
578
Richard Smitha547eb22016-07-14 00:11:03 +0000579 return new (Context)
580 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
581 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000582}
Steve Naroff86272ea2007-05-29 02:14:17 +0000583
Chris Lattner67998452007-08-23 18:29:20 +0000584namespace {
585 struct CaseCompareFunctor {
586 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
587 const llvm::APSInt &RHS) {
588 return LHS.first < RHS;
589 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000590 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
591 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
592 return LHS.first < RHS.first;
593 }
Chris Lattner67998452007-08-23 18:29:20 +0000594 bool operator()(const llvm::APSInt &LHS,
595 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
596 return LHS < RHS.first;
597 }
598 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000599}
Chris Lattner67998452007-08-23 18:29:20 +0000600
Chris Lattner4b2ff022007-09-21 18:15:22 +0000601/// CmpCaseVals - Comparison predicate for sorting case values.
602///
603static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
604 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
605 if (lhs.first < rhs.first)
606 return true;
607
608 if (lhs.first == rhs.first &&
609 lhs.second->getCaseLoc().getRawEncoding()
610 < rhs.second->getCaseLoc().getRawEncoding())
611 return true;
612 return false;
613}
614
Douglas Gregorbd6839732010-02-08 22:24:16 +0000615/// CmpEnumVals - Comparison predicate for sorting enumeration values.
616///
617static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
618 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
619{
620 return lhs.first < rhs.first;
621}
622
623/// EqEnumVals - Comparison preficate for uniqing enumeration values.
624///
625static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
626 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
627{
628 return lhs.first == rhs.first;
629}
630
Chris Lattnera96d4272009-10-16 16:45:22 +0000631/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
632/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000633static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
634 if (const auto *CleanUps = dyn_cast<ExprWithCleanups>(E))
635 E = CleanUps->getSubExpr();
636 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
637 if (ImpCast->getCastKind() != CK_IntegralCast) break;
638 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000639 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000640 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000641}
642
Richard Smith03a4aa32016-06-23 19:02:52 +0000643ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000644 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
645 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000646
Douglas Gregore2b37442012-05-04 22:38:52 +0000647 public:
648 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000649 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
650 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000651
Craig Toppere14c0f82014-03-12 04:55:44 +0000652 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
653 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000654 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
655 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000656
Craig Toppere14c0f82014-03-12 04:55:44 +0000657 SemaDiagnosticBuilder diagnoseIncomplete(
658 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000659 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
660 << T << Cond->getSourceRange();
661 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000662
Craig Toppere14c0f82014-03-12 04:55:44 +0000663 SemaDiagnosticBuilder diagnoseExplicitConv(
664 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000665 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
666 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000667
Craig Toppere14c0f82014-03-12 04:55:44 +0000668 SemaDiagnosticBuilder noteExplicitConv(
669 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000670 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
671 << ConvTy->isEnumeralType() << ConvTy;
672 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000673
Craig Toppere14c0f82014-03-12 04:55:44 +0000674 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
675 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000676 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
677 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000678
Craig Toppere14c0f82014-03-12 04:55:44 +0000679 SemaDiagnosticBuilder noteAmbiguous(
680 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000681 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
682 << ConvTy->isEnumeralType() << ConvTy;
683 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000684
Craig Toppere14c0f82014-03-12 04:55:44 +0000685 SemaDiagnosticBuilder diagnoseConversion(
686 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000687 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000688 }
689 } SwitchDiagnoser(Cond);
690
Richard Smith03a4aa32016-06-23 19:02:52 +0000691 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000692 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000693 if (CondResult.isInvalid())
694 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
Richard Smithef6c43d2018-07-26 18:41:30 +0000696 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
697 // failed and produced a diagnostic.
698 Cond = CondResult.get();
699 if (!Cond->isTypeDependent() &&
700 !Cond->getType()->isIntegralOrEnumerationType())
701 return ExprError();
702
John McCall5939b162011-08-06 07:30:58 +0000703 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smithef6c43d2018-07-26 18:41:30 +0000704 return UsualUnaryConversions(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +0000705}
John McCall5939b162011-08-06 07:30:58 +0000706
Richard Smithc7a05a92016-06-29 21:17:59 +0000707StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
708 Stmt *InitStmt, ConditionResult Cond) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000709 Expr *CondExpr = Cond.get().second;
710 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
711
712 if (CondExpr && !CondExpr->isTypeDependent()) {
713 // We have already converted the expression to an integral or enumeration
714 // type, when we parsed the switch condition. If we don't have an
715 // appropriate type now, enter the switch scope but remember that it's
716 // invalid.
717 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
718 "invalid condition type");
719 if (CondExpr->isKnownToHaveBooleanValue()) {
720 // switch(bool_expr) {...} is often a programmer error, e.g.
721 // switch(n && mask) { ... } // Doh - should be "n & mask".
722 // One can always use an if statement instead of switch(bool_expr).
723 Diag(SwitchLoc, diag::warn_bool_switch_condition)
724 << CondExpr->getSourceRange();
725 }
726 }
John McCalla95172b2010-08-01 00:26:45 +0000727
Reid Kleckner87a31802018-03-12 21:43:02 +0000728 setFunctionHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000729
Richard Smitha547eb22016-07-14 00:11:03 +0000730 SwitchStmt *SS = new (Context)
Richard Smithef6c43d2018-07-26 18:41:30 +0000731 SwitchStmt(Context, InitStmt, Cond.get().first, CondExpr);
732 getCurFunction()->SwitchStack.push_back(
733 FunctionScopeInfo::SwitchInfo(SS, false));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000734 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000735}
736
Gabor Greif16e02862010-10-01 22:05:14 +0000737static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000738 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000739 Val.setIsSigned(IsSigned);
740}
741
Richard Smith077d0832014-08-04 00:40:48 +0000742/// Check the specified case value is in range for the given unpromoted switch
743/// type.
744static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
745 unsigned UnpromotedWidth, bool UnpromotedSign) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000746 // In C++11 onwards, this is checked by the language rules.
747 if (S.getLangOpts().CPlusPlus11)
748 return;
749
Richard Smith077d0832014-08-04 00:40:48 +0000750 // If the case value was signed and negative and the switch expression is
751 // unsigned, don't bother to warn: this is implementation-defined behavior.
752 // FIXME: Introduce a second, default-ignored warning for this case?
753 if (UnpromotedWidth < Val.getBitWidth()) {
754 llvm::APSInt ConvVal(Val);
755 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
756 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
757 // FIXME: Use different diagnostics for overflow in conversion to promoted
758 // type versus "switch expression cannot have this value". Use proper
759 // IntRange checking rather than just looking at the unpromoted type here.
760 if (ConvVal != Val)
761 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
762 << ConvVal.toString(10);
763 }
764}
765
Alexis Hunt724f14e2014-11-28 00:53:20 +0000766typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
767
Dmitri Gribenko58683752013-12-05 22:52:07 +0000768/// Returns true if we should emit a diagnostic about this case expression not
769/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000770static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000771 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000772 const Expr *CaseExpr,
773 EnumValsTy::iterator &EI,
774 EnumValsTy::iterator &EIEnd,
775 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000776 if (!ED->isClosed())
777 return false;
778
Alexis Hunt724f14e2014-11-28 00:53:20 +0000779 if (const DeclRefExpr *DRE =
780 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000781 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000782 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000783 QualType EnumType = S.Context.getTypeDeclType(ED);
784 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
785 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000786 return false;
787 }
788 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000789
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000790 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000791 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000792
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000793 while (EI != EIEnd && EI->first < Val)
794 EI++;
795
796 if (EI != EIEnd && EI->first == Val)
797 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000798
Dmitri Gribenko58683752013-12-05 22:52:07 +0000799 return true;
800}
801
Gabor Horvath64c32412017-08-09 08:57:09 +0000802static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
803 const Expr *Case) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000804 QualType CondType = Cond->getType();
Gabor Horvath64c32412017-08-09 08:57:09 +0000805 QualType CaseType = Case->getType();
806
807 const EnumType *CondEnumType = CondType->getAs<EnumType>();
808 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
809 if (!CondEnumType || !CaseEnumType)
810 return;
811
Gabor Horvathb57e2642017-08-09 12:34:58 +0000812 // Ignore anonymous enums.
Richard Trieu285c9362017-09-09 00:25:05 +0000813 if (!CondEnumType->getDecl()->getIdentifier() &&
814 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000815 return;
Richard Trieu285c9362017-09-09 00:25:05 +0000816 if (!CaseEnumType->getDecl()->getIdentifier() &&
817 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000818 return;
819
Gabor Horvath64c32412017-08-09 08:57:09 +0000820 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
821 return;
822
Gabor Horvath0284a202017-08-09 20:56:43 +0000823 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000824 << CondType << CaseType << Cond->getSourceRange()
825 << Case->getSourceRange();
826}
827
John McCalldadc5752010-08-24 06:29:42 +0000828StmtResult
John McCallb268a282010-08-23 23:25:46 +0000829Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
830 Stmt *BodyStmt) {
831 SwitchStmt *SS = cast<SwitchStmt>(Switch);
Richard Smithef6c43d2018-07-26 18:41:30 +0000832 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
833 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
John McCallaab3e412010-08-25 08:40:02 +0000834 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000835
David Majnemer418ad3f2014-12-15 07:46:12 +0000836 getCurFunction()->SwitchStack.pop_back();
837
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000838 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000839 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000840
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000841 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000842 if (!CondExpr) return StmtError();
843
844 QualType CondType = CondExpr->getType();
845
Chris Lattnera96d4272009-10-16 16:45:22 +0000846 // C++ 6.4.2.p2:
847 // Integral promotions are performed (on the switch condition).
848 //
849 // A case value unrepresentable by the original switch condition
850 // type (before the promotion) doesn't make sense, even when it can
851 // be represented by the promoted type. Therefore we need to find
852 // the pre-promotion type of the switch condition.
Richard Smithef6c43d2018-07-26 18:41:30 +0000853 const Expr *CondExprBeforePromotion = CondExpr;
854 QualType CondTypeBeforePromotion =
855 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000856
Richard Smith077d0832014-08-04 00:40:48 +0000857 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000858 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000859 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000860 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000861 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
862 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
863
864 // Get the width and signedness that the condition might actually have, for
865 // warning purposes.
866 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
867 // type.
868 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000869 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000870 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000871 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000873 // Accumulate all of the case values in a vector so that we can sort them
874 // and detect duplicates. This vector contains the APInt for the case after
875 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000876 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000877 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000878
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000879 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000880 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
881 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000882
Craig Topperc3ec1492014-05-26 06:22:03 +0000883 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattner10cb5e52007-08-23 06:23:56 +0000885 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000886
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000887 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000888 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000889
Anders Carlsson51873c22007-07-22 07:07:56 +0000890 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000891 if (TheDefaultStmt) {
892 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000893 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000894
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000895 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000896 // we'll return a valid AST. This requires recursing down the AST and
897 // finding it, not something we are set up to do right now. For now,
898 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000899 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000900 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000901 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000903 } else {
904 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattnera65e1f32008-01-16 19:17:22 +0000906 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000907
Richard Smithef6c43d2018-07-26 18:41:30 +0000908 if (Lo->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000909 HasDependentValue = true;
910 break;
911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Richard Smithef6c43d2018-07-26 18:41:30 +0000913 // We already verified that the expression has a constant value;
914 // get that value (prior to conversions).
915 const Expr *LoBeforePromotion = Lo;
916 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
917 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000918
Richard Smith077d0832014-08-04 00:40:48 +0000919 // Check the unconverted value is within the range of possible values of
920 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000921 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
922 CondIsSignedBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000923
Richard Smithef6c43d2018-07-26 18:41:30 +0000924 // FIXME: This duplicates the check performed for warn_not_in_enum below.
925 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
926 LoBeforePromotion);
927
Richard Smith077d0832014-08-04 00:40:48 +0000928 // Convert the value to the same width/sign as the condition.
929 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000930
Chris Lattner10cb5e52007-08-23 06:23:56 +0000931 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000932 if (CS->getRHS()) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000933 if (CS->getRHS()->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000934 HasDependentValue = true;
935 break;
936 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000937 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000938 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000939 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000940 }
941 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000942
943 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000944 // If we don't have a default statement, check whether the
945 // condition is constant.
946 llvm::APSInt ConstantCondValue;
947 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000948 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000949 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
950 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000951 assert(!HasConstantCond ||
952 (ConstantCondValue.getBitWidth() == CondWidth &&
953 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000954 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000955 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000956
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000957 // Sort all the scalar case values so we can easily detect duplicates.
958 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
959
960 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000961 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
962 if (ShouldCheckConstantCond &&
963 CaseVals[i].first == ConstantCondValue)
964 ShouldCheckConstantCond = false;
965
966 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000967 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000968 // First, determine if either case value has a name
969 StringRef PrevString, CurrString;
970 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
971 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
972 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
973 PrevString = DeclRef->getDecl()->getName();
974 }
975 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
976 CurrString = DeclRef->getDecl()->getName();
977 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000978 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000979 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000980
981 if (PrevString == CurrString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000982 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
983 diag::err_duplicate_case)
984 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000985 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000986 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
987 diag::err_duplicate_case_differing_expr)
988 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
989 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
990 << CaseValStr;
Douglas Gregor9841df62012-05-16 05:32:58 +0000991
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000992 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000993 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000994 // FIXME: We really want to remove the bogus case stmt from the
995 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000996 CaseListIsErroneous = true;
997 }
998 }
999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001001 // Detect duplicate case ranges, which usually don't exist at all in
1002 // the first place.
1003 if (!CaseRanges.empty()) {
1004 // Sort all the case ranges by their low value so we can easily detect
1005 // overlaps between ranges.
1006 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +00001007
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001008 // Scan the ranges, computing the high values and removing empty ranges.
1009 std::vector<llvm::APSInt> HiVals;
1010 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +00001011 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001012 CaseStmt *CR = CaseRanges[i].second;
1013 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +00001014
Richard Smithef6c43d2018-07-26 18:41:30 +00001015 const Expr *HiBeforePromotion = Hi;
1016 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1017 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Richard Smith077d0832014-08-04 00:40:48 +00001019 // Check the unconverted value is within the range of possible values of
1020 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001021 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
Richard Smith077d0832014-08-04 00:40:48 +00001022 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1023
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001024 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001025 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001027 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001028 if (LoVal > HiVal) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001029 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1030 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001031 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001032 --i;
1033 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001034 continue;
1035 }
John McCalld3dfbd62010-05-18 03:19:21 +00001036
1037 if (ShouldCheckConstantCond &&
1038 LoVal <= ConstantCondValue &&
1039 ConstantCondValue <= HiVal)
1040 ShouldCheckConstantCond = false;
1041
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001042 HiVals.push_back(HiVal);
1043 }
Mike Stump11289f42009-09-09 15:08:12 +00001044
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001045 // Rescan the ranges, looking for overlap with singleton values and other
1046 // ranges. Since the range list is sorted, we only need to compare case
1047 // ranges with their neighbors.
1048 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1049 llvm::APSInt &CRLo = CaseRanges[i].first;
1050 llvm::APSInt &CRHi = HiVals[i];
1051 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001053 // Check to see whether the case range overlaps with any
1054 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001055 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001056 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001058 // Find the smallest value >= the lower bound. If I is in the
1059 // case range, then we have overlap.
1060 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1061 CaseVals.end(), CRLo,
1062 CaseCompareFunctor());
1063 if (I != CaseVals.end() && I->first < CRHi) {
1064 OverlapVal = I->first; // Found overlap with scalar.
1065 OverlapStmt = I->second;
1066 }
Mike Stump11289f42009-09-09 15:08:12 +00001067
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001068 // Find the smallest value bigger than the upper bound.
1069 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1070 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1071 OverlapVal = (I-1)->first; // Found overlap with scalar.
1072 OverlapStmt = (I-1)->second;
1073 }
Mike Stump11289f42009-09-09 15:08:12 +00001074
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001075 // Check to see if this case stmt overlaps with the subsequent
1076 // case range.
1077 if (i && CRLo <= HiVals[i-1]) {
1078 OverlapVal = HiVals[i-1]; // Found overlap with range.
1079 OverlapStmt = CaseRanges[i-1].second;
1080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001082 if (OverlapStmt) {
1083 // If we have a duplicate, report it.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001084 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1085 << OverlapVal.toString(10);
1086 Diag(OverlapStmt->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001087 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001088 // FIXME: We really want to remove the bogus case stmt from the
1089 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001090 CaseListIsErroneous = true;
1091 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001092 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001093 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001094
John McCalld3dfbd62010-05-18 03:19:21 +00001095 // Complain if we have a constant condition and we didn't find a match.
Richard Smithef6c43d2018-07-26 18:41:30 +00001096 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1097 ShouldCheckConstantCond) {
John McCalld3dfbd62010-05-18 03:19:21 +00001098 // TODO: it would be nice if we printed enums as enums, chars as
1099 // chars, etc.
1100 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1101 << ConstantCondValue.toString(10)
1102 << CondExpr->getSourceRange();
1103 }
1104
1105 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001106 // values. We only issue a warning if there is not 'default:', but
1107 // we still do the analysis to preserve this information in the AST
1108 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001109 //
Chris Lattner51679082010-09-16 17:09:42 +00001110 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001111
Douglas Gregorbd6839732010-02-08 22:24:16 +00001112 // If switch has default case, then ignore it.
Richard Smithef6c43d2018-07-26 18:41:30 +00001113 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1114 ET && ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001115 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001116 EnumValsTy EnumVals;
1117
John McCalld3dfbd62010-05-18 03:19:21 +00001118 // Gather all enum values, set their type and sort them,
1119 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001120 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001121 llvm::APSInt Val = EDI->getInitVal();
1122 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001123 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001124 }
1125 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001126 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001127 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001128
1129 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001130 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001131 CI != CaseVals.end(); CI++) {
1132 Expr *CaseExpr = CI->second->getLHS();
1133 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1134 CI->first))
1135 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1136 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001137 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001138
David Blaikiee476f972012-01-22 02:31:55 +00001139 // See which of case ranges aren't in enum
1140 EI = EnumVals.begin();
1141 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001142 RI != CaseRanges.end(); RI++) {
1143 Expr *CaseExpr = RI->second->getLHS();
1144 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1145 RI->first))
1146 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1147 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001148
Chad Rosier02a84392012-08-10 17:56:09 +00001149 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001150 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1151 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001152
1153 CaseExpr = RI->second->getRHS();
1154 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1155 Hi))
1156 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1157 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001159
Ted Kremenekc42f3452010-09-09 00:05:53 +00001160 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001161 auto CI = CaseVals.begin();
1162 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001163 bool hasCasesNotInSwitch = false;
1164
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001165 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166
Alexis Hunt724f14e2014-11-28 00:53:20 +00001167 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001168 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001169 while (CI != CaseVals.end() && CI->first < EI->first)
1170 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001171
Douglas Gregorbd6839732010-02-08 22:24:16 +00001172 if (CI != CaseVals.end() && CI->first == EI->first)
1173 continue;
1174
Ted Kremenekc42f3452010-09-09 00:05:53 +00001175 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001176 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001177 llvm::APSInt Hi =
1178 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001179 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001180 if (EI->first <= Hi)
1181 break;
1182 }
1183
Ted Kremenekc42f3452010-09-09 00:05:53 +00001184 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001185 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001186 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001187 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001189
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001190 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001191 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001192
Chris Lattner51679082010-09-16 17:09:42 +00001193 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001194 if (!UnhandledNames.empty()) {
1195 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1196 TheDefaultStmt ? diag::warn_def_missing_case
1197 : diag::warn_missing_case)
1198 << (int)UnhandledNames.size();
1199
1200 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1201 I != E; ++I)
1202 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001203 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001204
1205 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001206 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001207 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001208 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001209
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001210 if (BodyStmt)
1211 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1212 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001213
Mike Stump87c57ac2009-05-16 07:39:55 +00001214 // FIXME: If the case list was broken is some way, we don't have a good system
1215 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001216 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001217 return StmtError();
1218
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001219 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001220}
1221
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001222void
1223Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1224 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001225 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001226 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001227
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001228 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001229 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001230 SrcType->isIntegerType()) {
1231 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1232 SrcExpr->isIntegerConstantExpr(Context)) {
1233 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001234 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001235 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1236
1237 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001238 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001239 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001240
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001241 if (!ED->isClosed())
1242 return;
1243
Alexis Hunt724f14e2014-11-28 00:53:20 +00001244 if (ED->hasAttr<FlagEnumAttr>()) {
1245 if (!IsValueInFlagEnum(ED, RhsVal, true))
1246 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001247 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001248 } else {
1249 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1250 EnumValsTy;
1251 EnumValsTy EnumVals;
1252
1253 // Gather all enum values, set their type and sort them,
1254 // allowing easier comparison with rhs constant.
1255 for (auto *EDI : ED->enumerators()) {
1256 llvm::APSInt Val = EDI->getInitVal();
1257 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1258 EnumVals.push_back(std::make_pair(Val, EDI));
1259 }
1260 if (EnumVals.empty())
1261 return;
1262 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1263 EnumValsTy::iterator EIend =
1264 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1265
1266 // See which values aren't in the enum.
1267 EnumValsTy::const_iterator EI = EnumVals.begin();
1268 while (EI != EIend && EI->first < RhsVal)
1269 EI++;
1270 if (EI == EIend || EI->first != RhsVal) {
1271 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1272 << DstType.getUnqualifiedType();
1273 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001274 }
1275 }
1276 }
1277}
1278
Richard Smith03a4aa32016-06-23 19:02:52 +00001279StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1280 Stmt *Body) {
1281 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001282 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283
Richard Smith03a4aa32016-06-23 19:02:52 +00001284 auto CondVal = Cond.get();
1285 CheckBreakContinueBinding(CondVal.second);
1286
1287 if (CondVal.second &&
1288 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1289 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001290
John McCallb268a282010-08-23 23:25:46 +00001291 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001292
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001293 if (isa<NullStmt>(Body))
1294 getCurCompoundScope().setHasEmptyLoopBodies();
1295
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001296 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001297 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001298}
1299
John McCalldadc5752010-08-24 06:29:42 +00001300StmtResult
John McCallb268a282010-08-23 23:25:46 +00001301Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001302 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001303 Expr *Cond, SourceLocation CondRParen) {
1304 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001305
Serge Pavlov09f99242014-01-23 15:05:00 +00001306 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001307 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001308 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001309 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001310 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001311
Richard Smith945f8d32013-01-14 22:39:08 +00001312 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001313 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001314 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001315 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001316
John McCallb268a282010-08-23 23:25:46 +00001317 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001318
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001319 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001320}
1321
Richard Trieu451a5db2012-04-30 18:01:30 +00001322namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001323 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1324 using DeclSetVector =
1325 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1326 llvm::SmallPtrSet<VarDecl *, 8>>;
1327
Richard Trieu451a5db2012-04-30 18:01:30 +00001328 // This visitor will traverse a conditional statement and store all
1329 // the evaluated decls into a vector. Simple is set to true if none
1330 // of the excluded constructs are used.
1331 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001332 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001333 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001334 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001335 public:
1336 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001337
Richard Trieu5fb874a2017-06-02 04:24:46 +00001338 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001339 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001340 Inherited(S.Context),
1341 Decls(Decls),
1342 Ranges(Ranges),
1343 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001344
Richard Trieu9d228802013-05-31 22:46:45 +00001345 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 // Replaces the method in EvaluatedExprVisitor.
1348 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001349 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001350 }
1351
1352 // Any Stmt not whitelisted will cause the condition to be marked complex.
1353 void VisitStmt(Stmt *S) {
1354 Simple = false;
1355 }
1356
1357 void VisitBinaryOperator(BinaryOperator *E) {
1358 Visit(E->getLHS());
1359 Visit(E->getRHS());
1360 }
1361
1362 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001363 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001364 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001365
Richard Trieu9d228802013-05-31 22:46:45 +00001366 void VisitUnaryOperator(UnaryOperator *E) {
1367 // Skip checking conditionals with derefernces.
1368 if (E->getOpcode() == UO_Deref)
1369 Simple = false;
1370 else
1371 Visit(E->getSubExpr());
1372 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001373
Richard Trieu9d228802013-05-31 22:46:45 +00001374 void VisitConditionalOperator(ConditionalOperator *E) {
1375 Visit(E->getCond());
1376 Visit(E->getTrueExpr());
1377 Visit(E->getFalseExpr());
1378 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001379
Richard Trieu9d228802013-05-31 22:46:45 +00001380 void VisitParenExpr(ParenExpr *E) {
1381 Visit(E->getSubExpr());
1382 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001383
Richard Trieu9d228802013-05-31 22:46:45 +00001384 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1385 Visit(E->getOpaqueValue()->getSourceExpr());
1386 Visit(E->getFalseExpr());
1387 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001388
Richard Trieu9d228802013-05-31 22:46:45 +00001389 void VisitIntegerLiteral(IntegerLiteral *E) { }
1390 void VisitFloatingLiteral(FloatingLiteral *E) { }
1391 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1392 void VisitCharacterLiteral(CharacterLiteral *E) { }
1393 void VisitGNUNullExpr(GNUNullExpr *E) { }
1394 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001395
Richard Trieu9d228802013-05-31 22:46:45 +00001396 void VisitDeclRefExpr(DeclRefExpr *E) {
1397 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1398 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001399
Richard Trieu9d228802013-05-31 22:46:45 +00001400 Ranges.push_back(E->getSourceRange());
1401
1402 Decls.insert(VD);
1403 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001404
1405 }; // end class DeclExtractor
1406
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001407 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001408 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001409 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001410 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001411 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001412
Richard Trieu9d228802013-05-31 22:46:45 +00001413 public:
1414 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001415
Richard Trieu5fb874a2017-06-02 04:24:46 +00001416 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001417 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1418 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001419
Richard Trieu9d228802013-05-31 22:46:45 +00001420 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001421 }
1422
Richard Trieu9d228802013-05-31 22:46:45 +00001423 void VisitReturnStmt(ReturnStmt *S) {
1424 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001425 }
1426
Richard Trieu9d228802013-05-31 22:46:45 +00001427 void VisitBreakStmt(BreakStmt *S) {
1428 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001429 }
1430
Richard Trieu9d228802013-05-31 22:46:45 +00001431 void VisitGotoStmt(GotoStmt *S) {
1432 FoundDecl = true;
1433 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001434
Richard Trieu9d228802013-05-31 22:46:45 +00001435 void VisitCastExpr(CastExpr *E) {
1436 if (E->getCastKind() == CK_LValueToRValue)
1437 CheckLValueToRValueCast(E->getSubExpr());
1438 else
1439 Visit(E->getSubExpr());
1440 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001441
Richard Trieu9d228802013-05-31 22:46:45 +00001442 void CheckLValueToRValueCast(Expr *E) {
1443 E = E->IgnoreParenImpCasts();
1444
1445 if (isa<DeclRefExpr>(E)) {
1446 return;
1447 }
1448
1449 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1450 Visit(CO->getCond());
1451 CheckLValueToRValueCast(CO->getTrueExpr());
1452 CheckLValueToRValueCast(CO->getFalseExpr());
1453 return;
1454 }
1455
1456 if (BinaryConditionalOperator *BCO =
1457 dyn_cast<BinaryConditionalOperator>(E)) {
1458 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1459 CheckLValueToRValueCast(BCO->getFalseExpr());
1460 return;
1461 }
1462
1463 Visit(E);
1464 }
1465
1466 void VisitDeclRefExpr(DeclRefExpr *E) {
1467 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1468 if (Decls.count(VD))
1469 FoundDecl = true;
1470 }
1471
Steven Wu92910f62016-03-10 02:02:48 +00001472 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1473 // Only need to visit the semantics for POE.
1474 // SyntaticForm doesn't really use the Decal.
1475 for (auto *S : POE->semantics()) {
1476 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1477 // Look past the OVE into the expression it binds.
1478 Visit(OVE->getSourceExpr());
1479 else
1480 Visit(S);
1481 }
1482 }
1483
Richard Trieu9d228802013-05-31 22:46:45 +00001484 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001485
1486 }; // end class DeclMatcher
1487
1488 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1489 Expr *Third, Stmt *Body) {
1490 // Condition is empty
1491 if (!Second) return;
1492
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001493 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001494 Second->getBeginLoc()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001495 return;
1496
1497 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001498 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001499 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001500 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001501 DE.Visit(Second);
1502
1503 // Don't analyze complex conditionals.
1504 if (!DE.isSimple()) return;
1505
1506 // No decls found.
1507 if (Decls.size() == 0) return;
1508
Richard Trieu0030f1d2012-05-04 03:01:54 +00001509 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001510 for (auto *VD : Decls)
1511 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1512 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001513
1514 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1515 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1516 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1517 return;
1518
1519 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001520 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001521 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001522 } else {
1523 PDiag << (unsigned)Decls.size();
1524 for (auto *VD : Decls)
1525 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001526 }
1527
Richard Trieu5fb874a2017-06-02 04:24:46 +00001528 for (auto Range : Ranges)
1529 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001530
1531 S.Diag(Ranges.begin()->getBegin(), PDiag);
1532 }
1533
Richard Trieu4e7c9622013-08-06 21:31:54 +00001534 // If Statement is an incemement or decrement, return true and sets the
1535 // variables Increment and DRE.
1536 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1537 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001538 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1539 if (!Cleanups->cleanupsHaveSideEffects())
1540 Statement = Cleanups->getSubExpr();
1541
Richard Trieu4e7c9622013-08-06 21:31:54 +00001542 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1543 switch (UO->getOpcode()) {
1544 default: return false;
1545 case UO_PostInc:
1546 case UO_PreInc:
1547 Increment = true;
1548 break;
1549 case UO_PostDec:
1550 case UO_PreDec:
1551 Increment = false;
1552 break;
1553 }
1554 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1555 return DRE;
1556 }
1557
1558 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1559 FunctionDecl *FD = Call->getDirectCallee();
1560 if (!FD || !FD->isOverloadedOperator()) return false;
1561 switch (FD->getOverloadedOperator()) {
1562 default: return false;
1563 case OO_PlusPlus:
1564 Increment = true;
1565 break;
1566 case OO_MinusMinus:
1567 Increment = false;
1568 break;
1569 }
1570 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1571 return DRE;
1572 }
1573
1574 return false;
1575 }
1576
Serge Pavlov09f99242014-01-23 15:05:00 +00001577 // A visitor to determine if a continue or break statement is a
1578 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001579 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001580 SourceLocation BreakLoc;
1581 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001582 bool InSwitch = false;
1583
Richard Trieu4e7c9622013-08-06 21:31:54 +00001584 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001585 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001586 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001587 Visit(Body);
1588 }
1589
Eli Friedmane91b2e62017-07-04 00:52:24 +00001590 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001591
Eli Friedmane91b2e62017-07-04 00:52:24 +00001592 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001593 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001594 }
1595
Eli Friedmane91b2e62017-07-04 00:52:24 +00001596 void VisitBreakStmt(const BreakStmt* E) {
1597 if (!InSwitch)
1598 BreakLoc = E->getBreakLoc();
1599 }
1600
1601 void VisitSwitchStmt(const SwitchStmt* S) {
1602 if (const Stmt *Init = S->getInit())
1603 Visit(Init);
1604 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1605 Visit(CondVar);
1606 if (const Stmt *Cond = S->getCond())
1607 Visit(Cond);
1608
1609 // Don't return break statements from the body of a switch.
1610 InSwitch = true;
1611 if (const Stmt *Body = S->getBody())
1612 Visit(Body);
1613 InSwitch = false;
1614 }
1615
1616 void VisitForStmt(const ForStmt *S) {
1617 // Only visit the init statement of a for loop; the body
1618 // has a different break/continue scope.
1619 if (const Stmt *Init = S->getInit())
1620 Visit(Init);
1621 }
1622
1623 void VisitWhileStmt(const WhileStmt *) {
1624 // Do nothing; the children of a while loop have a different
1625 // break/continue scope.
1626 }
1627
1628 void VisitDoStmt(const DoStmt *) {
1629 // Do nothing; the children of a while loop have a different
1630 // break/continue scope.
1631 }
1632
1633 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1634 // Only visit the initialization of a for loop; the body
1635 // has a different break/continue scope.
1636 if (const Stmt *Range = S->getRangeStmt())
1637 Visit(Range);
1638 if (const Stmt *Begin = S->getBeginStmt())
1639 Visit(Begin);
1640 if (const Stmt *End = S->getEndStmt())
1641 Visit(End);
1642 }
1643
1644 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1645 // Only visit the initialization of a for loop; the body
1646 // has a different break/continue scope.
1647 if (const Stmt *Element = S->getElement())
1648 Visit(Element);
1649 if (const Stmt *Collection = S->getCollection())
1650 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001651 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001652
Serge Pavlov09f99242014-01-23 15:05:00 +00001653 bool ContinueFound() { return ContinueLoc.isValid(); }
1654 bool BreakFound() { return BreakLoc.isValid(); }
1655 SourceLocation GetContinueLoc() { return ContinueLoc; }
1656 SourceLocation GetBreakLoc() { return BreakLoc; }
1657
1658 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001659
1660 // Emit a warning when a loop increment/decrement appears twice per loop
1661 // iteration. The conditions which trigger this warning are:
1662 // 1) The last statement in the loop body and the third expression in the
1663 // for loop are both increment or both decrement of the same variable
1664 // 2) No continue statements in the loop body.
1665 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1666 // Return when there is nothing to check.
1667 if (!Body || !Third) return;
1668
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001669 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001670 Third->getBeginLoc()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001671 return;
1672
1673 // Get the last statement from the loop body.
1674 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1675 if (!CS || CS->body_empty()) return;
1676 Stmt *LastStmt = CS->body_back();
1677 if (!LastStmt) return;
1678
1679 bool LoopIncrement, LastIncrement;
1680 DeclRefExpr *LoopDRE, *LastDRE;
1681
1682 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1683 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1684
1685 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001686 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001687 if (LoopIncrement != LastIncrement ||
1688 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1689
Serge Pavlov09f99242014-01-23 15:05:00 +00001690 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001691
1692 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1693 << LastDRE->getDecl() << LastIncrement;
1694 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1695 << LoopIncrement;
1696 }
1697
Richard Trieu451a5db2012-04-30 18:01:30 +00001698} // end namespace
1699
Serge Pavlov09f99242014-01-23 15:05:00 +00001700
1701void Sema::CheckBreakContinueBinding(Expr *E) {
1702 if (!E || getLangOpts().CPlusPlus)
1703 return;
1704 BreakContinueFinder BCFinder(*this, E);
1705 Scope *BreakParent = CurScope->getBreakParent();
1706 if (BCFinder.BreakFound() && BreakParent) {
1707 if (BreakParent->getFlags() & Scope::SwitchScope) {
1708 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1709 } else {
1710 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1711 << "break";
1712 }
1713 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1714 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1715 << "continue";
1716 }
1717}
1718
Richard Smith03a4aa32016-06-23 19:02:52 +00001719StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1720 Stmt *First, ConditionResult Second,
1721 FullExprArg third, SourceLocation RParenLoc,
1722 Stmt *Body) {
1723 if (Second.isInvalid())
1724 return StmtError();
1725
David Blaikiebbafb8a2012-03-11 07:00:24 +00001726 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001727 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001728 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1729 // declare identifiers for objects having storage class 'auto' or
1730 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001731 for (auto *DI : DS->decls()) {
1732 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001733 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001734 VD = nullptr;
1735 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001736 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1737 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001738 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001739 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001740 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001741 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001742
Richard Smith03a4aa32016-06-23 19:02:52 +00001743 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001744 CheckBreakContinueBinding(third.get());
1745
Richard Smith03a4aa32016-06-23 19:02:52 +00001746 if (!Second.get().first)
1747 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1748 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001749 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001750
Richard Smith03a4aa32016-06-23 19:02:52 +00001751 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001752 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001753 Second.get().second->getExprLoc()))
1754 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001755
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001756 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757
Anders Carlsson1682af52009-08-01 01:39:59 +00001758 DiagnoseUnusedExprResult(First);
1759 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001760 DiagnoseUnusedExprResult(Body);
1761
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001762 if (isa<NullStmt>(Body))
1763 getCurCompoundScope().setHasEmptyLoopBodies();
1764
Richard Smith03a4aa32016-06-23 19:02:52 +00001765 return new (Context)
1766 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1767 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001768}
1769
John McCall34376a62010-12-04 03:47:34 +00001770/// In an Objective C collection iteration statement:
1771/// for (x in y)
1772/// x can be an arbitrary l-value expression. Bind it up as a
1773/// full-expression.
1774StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001775 // Reduce placeholder expressions here. Note that this rejects the
1776 // use of pseudo-object l-values in this position.
1777 ExprResult result = CheckPlaceholderExpr(E);
1778 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001779 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001780
Richard Smith945f8d32013-01-14 22:39:08 +00001781 ExprResult FullExpr = ActOnFinishFullExpr(E);
1782 if (FullExpr.isInvalid())
1783 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001784 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001785}
1786
John McCall53848232011-07-27 01:07:15 +00001787ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001788Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1789 if (!collection)
1790 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001791
Kaelyn Takata15867822014-11-21 18:48:04 +00001792 ExprResult result = CorrectDelayedTyposInExpr(collection);
1793 if (!result.isUsable())
1794 return ExprError();
1795 collection = result.get();
1796
John McCall53848232011-07-27 01:07:15 +00001797 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001798 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001799
1800 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001801 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001802 if (result.isInvalid())
1803 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001804 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001805
1806 // The operand needs to have object-pointer type.
1807 // TODO: should we do a contextual conversion?
1808 const ObjCObjectPointerType *pointerType =
1809 collection->getType()->getAs<ObjCObjectPointerType>();
1810 if (!pointerType)
1811 return Diag(forLoc, diag::err_collection_expr_type)
1812 << collection->getType() << collection->getSourceRange();
1813
1814 // Check that the operand provides
1815 // - countByEnumeratingWithState:objects:count:
1816 const ObjCObjectType *objectType = pointerType->getObjectType();
1817 ObjCInterfaceDecl *iface = objectType->getInterface();
1818
1819 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001820 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001821 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001822 (getLangOpts().ObjCAutoRefCount
1823 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1824 diag::err_arc_collection_forward, collection)
1825 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001826 // Otherwise, if we have any useful type information, check that
1827 // the type declares the appropriate method.
1828 } else if (iface || !objectType->qual_empty()) {
1829 IdentifierInfo *selectorIdents[] = {
1830 &Context.Idents.get("countByEnumeratingWithState"),
1831 &Context.Idents.get("objects"),
1832 &Context.Idents.get("count")
1833 };
1834 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1835
Craig Topperc3ec1492014-05-26 06:22:03 +00001836 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001837
1838 // If there's an interface, look in both the public and private APIs.
1839 if (iface) {
1840 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001841 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001842 }
1843
1844 // Also check protocol qualifiers.
1845 if (!method)
1846 method = LookupMethodInQualifiedType(selector, pointerType,
1847 /*instance*/ true);
1848
1849 // If we didn't find it anywhere, give up.
1850 if (!method) {
1851 Diag(forLoc, diag::warn_collection_expr_type)
1852 << collection->getType() << selector << collection->getSourceRange();
1853 }
1854
1855 // TODO: check for an incompatible signature?
1856 }
1857
1858 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001859 return collection;
John McCall53848232011-07-27 01:07:15 +00001860}
1861
John McCalldadc5752010-08-24 06:29:42 +00001862StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001863Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001864 Stmt *First, Expr *collection,
1865 SourceLocation RParenLoc) {
Reid Kleckner87a31802018-03-12 21:43:02 +00001866 setFunctionHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001867
1868 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001869 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001870
Fariborz Jahanian93977672008-01-10 20:33:58 +00001871 if (First) {
1872 QualType FirstType;
1873 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001874 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001875 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1876 diag::err_toomany_element_decls));
1877
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001878 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1879 if (!D || D->isInvalidDecl())
1880 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001881
John McCall31168b02011-06-15 23:02:42 +00001882 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001883 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1884 // declare identifiers for objects having storage class 'auto' or
1885 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001886 if (!D->hasLocalStorage())
1887 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001888 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001889
1890 // If the type contained 'auto', deduce the 'auto' to 'id'.
1891 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001892 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1893 VK_RValue);
1894 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001895 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1896 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001897 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001898 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001899 D->setInvalidDecl();
1900 return StmtError();
1901 }
1902
Richard Smith061f1e22013-04-30 21:23:01 +00001903 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001904
Richard Smith51ec0cf2017-02-21 01:17:38 +00001905 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001906 SourceLocation Loc =
1907 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001908 Diag(Loc, diag::warn_auto_var_is_id)
1909 << D->getDeclName();
1910 }
1911 }
1912
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001913 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001914 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001915 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001916 return StmtError(
1917 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1918 << First->getSourceRange());
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001919
Mike Stump11289f42009-09-09 15:08:12 +00001920 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001921 if (FirstType.isConstQualified())
1922 Diag(ForLoc, diag::err_selector_element_const_type)
1923 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001924 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001925 if (!FirstType->isDependentType() &&
1926 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001927 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001928 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1929 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001930 }
Chad Rosier02a84392012-08-10 17:56:09 +00001931
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001932 if (CollectionExprResult.isInvalid())
1933 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001934
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001935 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
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,
2054 SourceLocation CoawaitLoc, Stmt *First,
2055 SourceLocation ColonLoc, Expr *Range,
2056 SourceLocation RParenLoc,
2057 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 Smith3249fed2013-08-21 01:40:36 +00002061 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002062 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002063
2064 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2065 assert(DS && "first part of for range not a decl stmt");
2066
2067 if (!DS->isSingleDecl()) {
Stephen Kellya6e43582018-08-09 21:05:56 +00002068 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
Richard Smith02e85f32011-04-14 22:09:26 +00002069 return StmtError();
2070 }
Richard Smith02e85f32011-04-14 22:09:26 +00002071
Richard Smith3249fed2013-08-21 01:40:36 +00002072 Decl *LoopVar = DS->getSingleDecl();
2073 if (LoopVar->isInvalidDecl() || !Range ||
2074 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2075 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002076 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002077 }
Richard Smith02e85f32011-04-14 22:09:26 +00002078
Eric Fiselierb936a392017-06-14 03:24:55 +00002079 // Build the coroutine state immediately and not later during template
2080 // instantiation
2081 if (!CoawaitLoc.isInvalid()) {
2082 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2083 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002084 }
2085
Richard Smith02e85f32011-04-14 22:09:26 +00002086 // Build auto && __range = range-init
Matt Davisb8402ef2018-02-14 21:22:11 +00002087 // Divide by 2, since the variables are in the inner scope (loop body).
2088 const auto DepthStr = std::to_string(S->getDepth() / 2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002089 SourceLocation RangeLoc = Range->getBeginLoc();
Richard Smith02e85f32011-04-14 22:09:26 +00002090 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2091 Context.getAutoRRefDeductType(),
Matt Davisb8402ef2018-02-14 21:22:11 +00002092 std::string("__range") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002093 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002094 diag::err_for_range_deduction_failure)) {
2095 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002096 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002097 }
Richard Smith02e85f32011-04-14 22:09:26 +00002098
2099 // Claim the type doesn't contain auto: we've already done the checking.
2100 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002101 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002102 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002103 if (RangeDecl.isInvalid()) {
2104 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002105 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002106 }
Richard Smith02e85f32011-04-14 22:09:26 +00002107
Richard Smithcfd53b42015-10-22 06:13:50 +00002108 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002109 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2110 /*Cond=*/nullptr, /*Inc=*/nullptr,
2111 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002112}
2113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002114/// Create the initialization, compare, and increment steps for
Sam Panzer0f384432012-08-21 00:52:01 +00002115/// the range-based for loop expression.
2116/// This function does not handle array-based for loops,
2117/// which are created in Sema::BuildCXXForRangeStmt.
2118///
2119/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2120/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2121/// CandidateSet and BEF are set and some non-success value is returned on
2122/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002123static Sema::ForRangeStatus
2124BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2125 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2126 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2127 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2128 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002129 DeclarationNameInfo BeginNameInfo(
2130 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2131 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2132 ColonLoc);
2133
2134 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2135 Sema::LookupMemberName);
2136 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2137
2138 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2139 // - if _RangeT is a class type, the unqualified-ids begin and end are
2140 // looked up in the scope of class _RangeT as if by class member access
2141 // lookup (3.4.5), and if either (or both) finds at least one
2142 // declaration, begin-expr and end-expr are __range.begin() and
2143 // __range.end(), respectively;
2144 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2145 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2146
2147 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2148 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002149 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002150
2151 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2152 << RangeLoc << BeginRange->getType() << *BEF;
2153 return Sema::FRS_DiagnosticIssued;
2154 }
2155 } else {
2156 // - otherwise, begin-expr and end-expr are begin(__range) and
2157 // end(__range), respectively, where begin and end are looked up with
2158 // argument-dependent lookup (3.4.2). For the purposes of this name
2159 // lookup, namespace std is an associated namespace.
2160
2161 }
2162
Richard Smith9f690bd2015-10-27 06:02:45 +00002163 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002164 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002165 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002166 BeginMemberLookup, CandidateSet,
2167 BeginRange, BeginExpr);
2168
Richard Smith9f690bd2015-10-27 06:02:45 +00002169 if (RangeStatus != Sema::FRS_Success) {
2170 if (RangeStatus == Sema::FRS_DiagnosticIssued)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002171 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
Richard Smith9f690bd2015-10-27 06:02:45 +00002172 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002173 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002174 }
Eric Fiselierb936a392017-06-14 03:24:55 +00002175 if (!CoawaitLoc.isInvalid()) {
2176 // FIXME: getCurScope() should not be used during template instantiation.
2177 // We should pick up the set of unqualified lookup results for operator
2178 // co_await during the initial parse.
2179 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2180 BeginExpr->get());
2181 if (BeginExpr->isInvalid())
2182 return Sema::FRS_DiagnosticIssued;
2183 }
Sam Panzer0f384432012-08-21 00:52:01 +00002184 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2185 diag::err_for_range_iter_deduction_failure)) {
2186 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2187 return Sema::FRS_DiagnosticIssued;
2188 }
2189
Richard Smith9f690bd2015-10-27 06:02:45 +00002190 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002191 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002192 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002193 EndMemberLookup, CandidateSet,
2194 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002195 if (RangeStatus != Sema::FRS_Success) {
2196 if (RangeStatus == Sema::FRS_DiagnosticIssued)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002197 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
Richard Smith9f690bd2015-10-27 06:02:45 +00002198 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002199 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002200 }
Sam Panzer0f384432012-08-21 00:52:01 +00002201 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2202 diag::err_for_range_iter_deduction_failure)) {
2203 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2204 return Sema::FRS_DiagnosticIssued;
2205 }
2206 return Sema::FRS_Success;
2207}
2208
2209/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002210/// If the attempt fails, this function will return a valid, null StmtResult
2211/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002212static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2213 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002214 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002215 Stmt *LoopVarDecl,
2216 SourceLocation ColonLoc,
2217 Expr *Range,
2218 SourceLocation RangeLoc,
2219 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002220 // Determine whether we can rebuild the for-range statement with a
2221 // dereferenced range expression.
2222 ExprResult AdjustedRange;
2223 {
2224 Sema::SFINAETrap Trap(SemaRef);
2225
2226 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2227 if (AdjustedRange.isInvalid())
2228 return StmtResult();
2229
Richard Smith9f690bd2015-10-27 06:02:45 +00002230 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2231 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2232 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002233 if (SR.isInvalid())
2234 return StmtResult();
2235 }
2236
2237 // The attempt to dereference worked well enough that it could produce a valid
2238 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2239 // case there are any other (non-fatal) problems with it.
2240 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2241 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002242 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2243 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002244 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002245}
2246
Richard Smith3249fed2013-08-21 01:40:36 +00002247namespace {
2248/// RAII object to automatically invalidate a declaration if an error occurs.
2249struct InvalidateOnErrorScope {
2250 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2251 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2252 ~InvalidateOnErrorScope() {
2253 if (Enabled && Trap.hasErrorOccurred())
2254 D->setInvalidDecl();
2255 }
2256
2257 DiagnosticErrorTrap Trap;
2258 Decl *D;
2259 bool Enabled;
2260};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002261}
Richard Smith3249fed2013-08-21 01:40:36 +00002262
Richard Smitha05b3b52012-09-20 21:52:32 +00002263/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002264StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002265Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002266 SourceLocation ColonLoc, Stmt *RangeDecl,
2267 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002268 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002269 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002270 // FIXME: This should not be used during template instantiation. We should
2271 // pick up the set of unqualified lookup results for the != and + operators
2272 // in the initial parse.
2273 //
2274 // Testcase (accepts-invalid):
2275 // template<typename T> void f() { for (auto x : T()) {} }
2276 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2277 // bool operator!=(N::X, N::X); void operator++(N::X);
2278 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002279 Scope *S = getCurScope();
2280
2281 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2282 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2283 QualType RangeVarType = RangeVar->getType();
2284
2285 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2286 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2287
Richard Smith3249fed2013-08-21 01:40:36 +00002288 // If we hit any errors, mark the loop variable as invalid if its type
2289 // contains 'auto'.
2290 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2291 LoopVar->getType()->isUndeducedType());
2292
Richard Smith01694c32016-03-20 10:33:40 +00002293 StmtResult BeginDeclStmt = Begin;
2294 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002295 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2296
Richard Smith27d807c2013-04-30 13:56:41 +00002297 if (RangeVarType->isDependentType()) {
2298 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002299 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002300
2301 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2302 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002303 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2304 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2305 for (auto *Binding : DD->bindings())
2306 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002307 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002308 }
Richard Smith01694c32016-03-20 10:33:40 +00002309 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002310 SourceLocation RangeLoc = RangeVar->getLocation();
2311
Ted Kremenekbed648e2011-10-10 22:36:28 +00002312 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2313
2314 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2315 VK_LValue, ColonLoc);
2316 if (BeginRangeRef.isInvalid())
2317 return StmtError();
2318
2319 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2320 VK_LValue, ColonLoc);
2321 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002322 return StmtError();
2323
2324 QualType AutoType = Context.getAutoDeductType();
2325 Expr *Range = RangeVar->getInit();
2326 if (!Range)
2327 return StmtError();
2328 QualType RangeType = Range->getType();
2329
2330 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002331 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002332 return StmtError();
2333
2334 // Build auto __begin = begin-expr, __end = end-expr.
Matt Davisb8402ef2018-02-14 21:22:11 +00002335 // Divide by 2, since the variables are in the inner scope (loop body).
2336 const auto DepthStr = std::to_string(S->getDepth() / 2);
Richard Smith02e85f32011-04-14 22:09:26 +00002337 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002338 std::string("__begin") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002339 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002340 std::string("__end") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002341
2342 // Build begin-expr and end-expr and attach to __begin and __end variables.
2343 ExprResult BeginExpr, EndExpr;
2344 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2345 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2346 // __range + __bound, respectively, where __bound is the array bound. If
2347 // _RangeT is an array of unknown size or an array of incomplete type,
2348 // the program is ill-formed;
2349
2350 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002351 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002352 if (!CoawaitLoc.isInvalid()) {
2353 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2354 if (BeginExpr.isInvalid())
2355 return StmtError();
2356 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002357 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002358 diag::err_for_range_iter_deduction_failure)) {
2359 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2360 return StmtError();
2361 }
2362
2363 // Find the array bound.
2364 ExprResult BoundExpr;
2365 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002366 BoundExpr = IntegerLiteral::Create(
2367 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002368 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002369 dyn_cast<VariableArrayType>(UnqAT)) {
2370 // For a variably modified type we can't just use the expression within
2371 // the array bounds, since we don't want that to be re-evaluated here.
2372 // Rather, we need to determine what it was when the array was first
2373 // created - so we resort to using sizeof(vla)/sizeof(element).
2374 // For e.g.
Fangrui Song6907ce22018-07-30 19:24:48 +00002375 // void f(int b) {
Faisal Vali1ca2d962017-05-15 01:49:19 +00002376 // int vla[b];
2377 // b = -1; <-- This should not affect the num of iterations below
2378 // for (int &c : vla) { .. }
2379 // }
2380
2381 // FIXME: This results in codegen generating IR that recalculates the
2382 // run-time number of elements (as opposed to just using the IR Value
2383 // that corresponds to the run-time value of each bound that was
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002384 // generated when the array was created.) If this proves too embarrassing
Faisal Vali1ca2d962017-05-15 01:49:19 +00002385 // even for unoptimized IR, consider passing a magic-value/cookie to
2386 // codegen that then knows to simply use that initial llvm::Value (that
2387 // corresponds to the bound at time of array creation) within
2388 // getelementptr. But be prepared to pay the price of increasing a
2389 // customized form of coupling between the two components - which could
2390 // be hard to maintain as the codebase evolves.
2391
2392 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2393 EndVar->getLocation(), UETT_SizeOf,
2394 /*isType=*/true,
2395 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2396 VAT->desugar(), RangeLoc))
2397 .getAsOpaquePtr(),
2398 EndVar->getSourceRange());
2399 if (SizeOfVLAExprR.isInvalid())
2400 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002401
Faisal Vali1ca2d962017-05-15 01:49:19 +00002402 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2403 EndVar->getLocation(), UETT_SizeOf,
2404 /*isType=*/true,
2405 CreateParsedType(VAT->desugar(),
2406 Context.getTrivialTypeSourceInfo(
2407 VAT->getElementType(), RangeLoc))
2408 .getAsOpaquePtr(),
2409 EndVar->getSourceRange());
2410 if (SizeOfEachElementExprR.isInvalid())
2411 return StmtError();
2412
2413 BoundExpr =
2414 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2415 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2416 if (BoundExpr.isInvalid())
2417 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002418
Faisal Vali1ca2d962017-05-15 01:49:19 +00002419 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002420 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2421 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002422 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002423 }
2424
2425 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002426 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002427 BoundExpr.get());
2428 if (EndExpr.isInvalid())
2429 return StmtError();
2430 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2431 diag::err_for_range_iter_deduction_failure)) {
2432 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2433 return StmtError();
2434 }
2435 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002436 OverloadCandidateSet CandidateSet(RangeLoc,
2437 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002438 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002439 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2440 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2441 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2442 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002443
Richard Smitha05b3b52012-09-20 21:52:32 +00002444 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002445 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002446 // If the range is being built from an array parameter, emit a
2447 // a diagnostic that it is being treated as a pointer.
2448 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2449 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2450 QualType ArrayTy = PVD->getOriginalType();
2451 QualType PointerTy = PVD->getType();
2452 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002453 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2454 << RangeLoc << PVD << ArrayTy << PointerTy;
Richard Trieu08254692013-10-11 22:16:04 +00002455 Diag(PVD->getLocation(), diag::note_declared_at);
2456 return StmtError();
2457 }
2458 }
2459 }
2460
2461 // If building the range failed, try dereferencing the range expression
2462 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002463 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002464 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002465 LoopVarDecl, ColonLoc,
2466 Range, RangeLoc,
2467 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002468 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002469 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002470 }
2471
Sam Panzer0f384432012-08-21 00:52:01 +00002472 // Otherwise, emit diagnostics if we haven't already.
2473 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002474 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002475 Diag(Range->getBeginLoc(), diag::err_for_range_invalid)
Sam Panzer0f384432012-08-21 00:52:01 +00002476 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002477 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002478 }
2479 // Return an error if no fix was discovered.
2480 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002481 return StmtError();
2482 }
2483
Sam Panzer0f384432012-08-21 00:52:01 +00002484 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2485 "invalid range expression in for loop");
2486
2487 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002488 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002489 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2490 if (!Context.hasSameType(BeginType, EndType)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002491 Diag(RangeLoc, getLangOpts().CPlusPlus17
Richard Smith01694c32016-03-20 10:33:40 +00002492 ? diag::warn_for_range_begin_end_types_differ
2493 : diag::ext_for_range_begin_end_types_differ)
2494 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002495 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2496 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2497 }
2498
Richard Smith01694c32016-03-20 10:33:40 +00002499 BeginDeclStmt =
2500 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2501 EndDeclStmt =
2502 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002503
Ted Kremenekbed648e2011-10-10 22:36:28 +00002504 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2505 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002506 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002507 if (BeginRef.isInvalid())
2508 return StmtError();
2509
Richard Smith02e85f32011-04-14 22:09:26 +00002510 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2511 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002512 if (EndRef.isInvalid())
2513 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002514
2515 // Build and check __begin != __end expression.
2516 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2517 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002518 if (!NotEqExpr.isInvalid())
2519 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2520 if (!NotEqExpr.isInvalid())
2521 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002522 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002523 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2524 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002525 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2526 if (!Context.hasSameType(BeginType, EndType))
2527 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2528 return StmtError();
2529 }
2530
2531 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002532 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2533 VK_LValue, ColonLoc);
2534 if (BeginRef.isInvalid())
2535 return StmtError();
2536
Richard Smith02e85f32011-04-14 22:09:26 +00002537 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002538 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002539 // FIXME: getCurScope() should not be used during template instantiation.
2540 // We should pick up the set of unqualified lookup results for operator
2541 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002542 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002543 if (!IncrExpr.isInvalid())
2544 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002545 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002546 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2547 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002548 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2549 return StmtError();
2550 }
2551
2552 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002553 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2554 VK_LValue, ColonLoc);
2555 if (BeginRef.isInvalid())
2556 return StmtError();
2557
Richard Smith02e85f32011-04-14 22:09:26 +00002558 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2559 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002560 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2561 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002562 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2563 return StmtError();
2564 }
2565
Richard Smitha05b3b52012-09-20 21:52:32 +00002566 // Attach *__begin as initializer for VD. Don't touch it if we're just
2567 // trying to determine whether this would be a valid range.
2568 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002569 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002570 if (LoopVar->isInvalidDecl())
2571 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2572 }
2573 }
2574
Richard Smitha05b3b52012-09-20 21:52:32 +00002575 // Don't bother to actually allocate the result if we're just trying to
2576 // determine whether it would be valid.
2577 if (Kind == BFRK_Check)
2578 return StmtResult();
2579
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002580 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002581 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2582 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002583 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2584 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002585}
2586
Chad Rosier02a84392012-08-10 17:56:09 +00002587/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002588/// statement.
2589StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2590 if (!S || !B)
2591 return StmtError();
2592 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002593
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002594 ForStmt->setBody(B);
2595 return S;
2596}
2597
Richard Trieu3e1d4832015-04-13 22:08:55 +00002598// Warn when the loop variable is a const reference that creates a copy.
2599// Suggest using the non-reference type for copies. If a copy can be prevented
2600// suggest the const reference type that would do so.
2601// For instance, given "for (const &Foo : Range)", suggest
2602// "for (const Foo : Range)" to denote a copy is made for the loop. If
2603// possible, also suggest "for (const &Bar : Range)" if this type prevents
2604// the copy altogether.
2605static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2606 const VarDecl *VD,
2607 QualType RangeInitType) {
2608 const Expr *InitExpr = VD->getInit();
2609 if (!InitExpr)
2610 return;
2611
2612 QualType VariableType = VD->getType();
2613
Tim Shen4a05bb82016-06-21 20:29:17 +00002614 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2615 if (!Cleanups->cleanupsHaveSideEffects())
2616 InitExpr = Cleanups->getSubExpr();
2617
Richard Trieu3e1d4832015-04-13 22:08:55 +00002618 const MaterializeTemporaryExpr *MTE =
2619 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2620
2621 // No copy made.
2622 if (!MTE)
2623 return;
2624
2625 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2626
2627 // Searching for either UnaryOperator for dereference of a pointer or
2628 // CXXOperatorCallExpr for handling iterators.
2629 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2630 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2631 E = CCE->getArg(0);
2632 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2633 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2634 E = ME->getBase();
2635 } else {
2636 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2637 E = MTE->GetTemporaryExpr();
2638 }
2639 E = E->IgnoreImpCasts();
2640 }
2641
2642 bool ReturnsReference = false;
2643 if (isa<UnaryOperator>(E)) {
2644 ReturnsReference = true;
2645 } else {
2646 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2647 const FunctionDecl *FD = Call->getDirectCallee();
2648 QualType ReturnType = FD->getReturnType();
2649 ReturnsReference = ReturnType->isReferenceType();
2650 }
2651
2652 if (ReturnsReference) {
2653 // Loop variable creates a temporary. Suggest either to go with
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002654 // non-reference loop variable to indicate a copy is made, or
Richard Trieu3e1d4832015-04-13 22:08:55 +00002655 // the correct time to bind a const reference.
2656 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2657 << VD << VariableType << E->getType();
2658 QualType NonReferenceType = VariableType.getNonReferenceType();
2659 NonReferenceType.removeLocalConst();
2660 QualType NewReferenceType =
2661 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002662 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002663 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2664 } else {
2665 // The range always returns a copy, so a temporary is always created.
2666 // Suggest removing the reference from the loop variable.
2667 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2668 << VD << RangeInitType;
2669 QualType NonReferenceType = VariableType.getNonReferenceType();
2670 NonReferenceType.removeLocalConst();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002671 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002672 << NonReferenceType << VD->getSourceRange();
2673 }
2674}
2675
2676// Warns when the loop variable can be changed to a reference type to
2677// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2678// "for (const Foo &x : Range)" if this form does not make a copy.
2679static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2680 const VarDecl *VD) {
2681 const Expr *InitExpr = VD->getInit();
2682 if (!InitExpr)
2683 return;
2684
2685 QualType VariableType = VD->getType();
2686
2687 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2688 if (!CE->getConstructor()->isCopyConstructor())
2689 return;
2690 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2691 if (CE->getCastKind() != CK_LValueToRValue)
2692 return;
2693 } else {
2694 return;
2695 }
2696
2697 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2698 // should be emitted. Also, only ignore POD types with trivial copy
2699 // constructors.
2700 if (VariableType.isPODType(SemaRef.Context))
2701 return;
2702
2703 // Suggest changing from a const variable to a const reference variable
2704 // if doing so will prevent a copy.
2705 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2706 << VD << VariableType << InitExpr->getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002707 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002708 << SemaRef.Context.getLValueReferenceType(VariableType)
2709 << VD->getSourceRange();
2710}
2711
2712/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2713/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2714/// using "const foo x" to show that a copy is made
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002715/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
Richard Trieu3e1d4832015-04-13 22:08:55 +00002716/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2717/// prevent the copy.
2718/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2719/// Suggest "const foo &x" to prevent the copy.
2720static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2721 const CXXForRangeStmt *ForStmt) {
2722 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002723 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002724 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002725 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002726 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002727 ForStmt->getBeginLoc())) {
Richard Trieu3e1d4832015-04-13 22:08:55 +00002728 return;
2729 }
2730
2731 const VarDecl *VD = ForStmt->getLoopVariable();
2732 if (!VD)
2733 return;
2734
2735 QualType VariableType = VD->getType();
2736
2737 if (VariableType->isIncompleteType())
2738 return;
2739
2740 const Expr *InitExpr = VD->getInit();
2741 if (!InitExpr)
2742 return;
2743
2744 if (VariableType->isReferenceType()) {
2745 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2746 ForStmt->getRangeInit()->getType());
2747 } else if (VariableType.isConstQualified()) {
2748 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2749 }
2750}
2751
Richard Smith02e85f32011-04-14 22:09:26 +00002752/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2753/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2754/// body cannot be performed until after the type of the range variable is
2755/// determined.
2756StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2757 if (!S || !B)
2758 return StmtError();
2759
Fariborz Jahanian00213472012-07-06 19:04:04 +00002760 if (isa<ObjCForCollectionStmt>(S))
2761 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002762
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002763 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2764 ForStmt->setBody(B);
2765
2766 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2767 diag::warn_empty_range_based_for_body);
2768
Richard Trieu3e1d4832015-04-13 22:08:55 +00002769 DiagnoseForRangeVariableCopies(*this, ForStmt);
2770
Richard Smith02e85f32011-04-14 22:09:26 +00002771 return S;
2772}
2773
Chris Lattnercab02a62011-02-17 20:34:02 +00002774StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2775 SourceLocation LabelLoc,
2776 LabelDecl *TheDecl) {
Reid Kleckner87a31802018-03-12 21:43:02 +00002777 setFunctionHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002778 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002779 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002780}
Chris Lattner1c310502007-05-31 06:00:00 +00002781
John McCalldadc5752010-08-24 06:29:42 +00002782StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002783Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002784 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002785 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002786 if (!E->isTypeDependent()) {
2787 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002788 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002789 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002790 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002791 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2792 if (ExprRes.isInvalid())
2793 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002794 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002795 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002796 return StmtError();
2797 }
John McCalla95172b2010-08-01 00:26:45 +00002798
Richard Smith945f8d32013-01-14 22:39:08 +00002799 ExprResult ExprRes = ActOnFinishFullExpr(E);
2800 if (ExprRes.isInvalid())
2801 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002802 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002803
Reid Kleckner87a31802018-03-12 21:43:02 +00002804 setFunctionHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002805
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002806 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002807}
2808
Nico Weberd64657f2015-03-09 02:47:59 +00002809static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2810 const Scope &DestScope) {
2811 if (!S.CurrentSEHFinally.empty() &&
2812 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2813 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2814 }
2815}
2816
John McCalldadc5752010-08-24 06:29:42 +00002817StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002818Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002819 Scope *S = CurScope->getContinueParent();
2820 if (!S) {
2821 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002822 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002823 }
Nico Weberd64657f2015-03-09 02:47:59 +00002824 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002825
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002826 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002827}
2828
John McCalldadc5752010-08-24 06:29:42 +00002829StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002830Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002831 Scope *S = CurScope->getBreakParent();
2832 if (!S) {
2833 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002834 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002835 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002836 if (S->isOpenMPLoopScope())
2837 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2838 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002839 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002840
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002841 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002842}
2843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002844/// Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002845/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002846///
Douglas Gregor5d369002011-01-21 18:05:27 +00002847/// \param ReturnType If we're determining the copy elision candidate for
2848/// a return statement, this is the return type of the function. If we're
2849/// determining the copy elision candidate for a throw expression, this will
2850/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002851///
Douglas Gregor5d369002011-01-21 18:05:27 +00002852/// \param E The expression being returned from the function or block, or
2853/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002854///
Richard Trieu09c163b2018-03-15 03:00:55 +00002855/// \param CESK Whether we allow function parameters or
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002856/// id-expressions that could be moved out of the function to be considered NRVO
2857/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2858/// determine whether we should try to move as part of a return or throw (which
2859/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002860///
2861/// \returns The NRVO candidate variable, if the return statement may use the
2862/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002863VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
Richard Trieu09c163b2018-03-15 03:00:55 +00002864 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002865 // - in a return statement in a function [where] ...
2866 // ... the expression is the name of a non-volatile automatic object ...
2867 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002868 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002869 return nullptr;
2870 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2871 if (!VD)
2872 return nullptr;
2873
Richard Trieu09c163b2018-03-15 03:00:55 +00002874 if (isCopyElisionCandidate(ReturnType, VD, CESK))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002875 return VD;
2876 return nullptr;
2877}
2878
2879bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Richard Trieu09c163b2018-03-15 03:00:55 +00002880 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002881 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002882 // - in a return statement in a function with ...
2883 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002884 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002885 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002886 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002887 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002888 // When considering moving this expression out, allow dissimilar types.
Richard Trieu09c163b2018-03-15 03:00:55 +00002889 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002890 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2891 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893
John McCall03318c12011-11-11 03:57:31 +00002894 // ...object (other than a function or catch-clause parameter)...
2895 if (VD->getKind() != Decl::Var &&
Richard Trieu09c163b2018-03-15 03:00:55 +00002896 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002897 return false;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002898 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2899 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900
John McCall03318c12011-11-11 03:57:31 +00002901 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002902 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002903
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002904 // Return false if VD is a __block variable. We don't want to implicitly move
2905 // out of a __block variable during a return because we cannot assume the
2906 // variable will no longer be used.
2907 if (VD->hasAttr<BlocksAttr>()) return false;
2908
Richard Trieu09c163b2018-03-15 03:00:55 +00002909 if (CESK & CES_AllowDifferentTypes)
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002910 return true;
2911
John McCall03318c12011-11-11 03:57:31 +00002912 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002913 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002914
John McCall03318c12011-11-11 03:57:31 +00002915 // Variables with higher required alignment than their type's ABI
2916 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002917 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002918 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002919 return false;
John McCall03318c12011-11-11 03:57:31 +00002920
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002921 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002922}
2923
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002924/// Try to perform the initialization of a potentially-movable value,
Richard Trieu09c163b2018-03-15 03:00:55 +00002925/// which is the operand to a return or throw statement.
2926///
2927/// This routine implements C++14 [class.copy]p32, which attempts to treat
2928/// returned lvalues as rvalues in certain cases (to prefer move construction),
2929/// then falls back to treating them as lvalues if that failed.
2930///
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002931/// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
2932/// resolutions that find non-constructors, such as derived-to-base conversions
2933/// or `operator T()&&` member functions. If false, do consider such
2934/// conversion sequences.
2935///
Richard Trieu09c163b2018-03-15 03:00:55 +00002936/// \param Res We will fill this in if move-initialization was possible.
2937/// If move-initialization is not possible, such that we must fall back to
2938/// treating the operand as an lvalue, we will leave Res in its original
2939/// invalid state.
2940static void TryMoveInitialization(Sema& S,
2941 const InitializedEntity &Entity,
2942 const VarDecl *NRVOCandidate,
2943 QualType ResultType,
2944 Expr *&Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002945 bool ConvertingConstructorsOnly,
Richard Trieu09c163b2018-03-15 03:00:55 +00002946 ExprResult &Res) {
2947 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2948 CK_NoOp, Value, VK_XValue);
2949
2950 Expr *InitExpr = &AsRvalue;
2951
2952 InitializationKind Kind = InitializationKind::CreateCopy(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002953 Value->getBeginLoc(), Value->getBeginLoc());
Richard Trieu09c163b2018-03-15 03:00:55 +00002954
2955 InitializationSequence Seq(S, Entity, Kind, InitExpr);
2956
2957 if (!Seq)
2958 return;
2959
2960 for (const InitializationSequence::Step &Step : Seq.steps()) {
2961 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
2962 Step.Kind != InitializationSequence::SK_UserConversion)
2963 continue;
2964
2965 FunctionDecl *FD = Step.Function.Function;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002966 if (ConvertingConstructorsOnly) {
2967 if (isa<CXXConstructorDecl>(FD)) {
2968 // C++14 [class.copy]p32:
2969 // [...] If the first overload resolution fails or was not performed,
2970 // or if the type of the first parameter of the selected constructor
2971 // is not an rvalue reference to the object's type (possibly
2972 // cv-qualified), overload resolution is performed again, considering
2973 // the object as an lvalue.
2974 const RValueReferenceType *RRefType =
2975 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
2976 if (!RRefType)
2977 break;
2978 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2979 NRVOCandidate->getType()))
2980 break;
2981 } else {
2982 continue;
2983 }
Richard Trieu09c163b2018-03-15 03:00:55 +00002984 } else {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002985 if (isa<CXXConstructorDecl>(FD)) {
2986 // Check that overload resolution selected a constructor taking an
2987 // rvalue reference. If it selected an lvalue reference, then we
2988 // didn't need to cast this thing to an rvalue in the first place.
2989 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
2990 break;
2991 } else if (isa<CXXMethodDecl>(FD)) {
2992 // Check that overload resolution selected a conversion operator
2993 // taking an rvalue reference.
2994 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
2995 break;
2996 } else {
2997 continue;
2998 }
Richard Trieu09c163b2018-03-15 03:00:55 +00002999 }
3000
3001 // Promote "AsRvalue" to the heap, since we now need this
3002 // expression node to persist.
3003 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3004 Value, nullptr, VK_XValue);
3005
3006 // Complete type-checking the initialization of the return type
3007 // using the constructor we found.
3008 Res = Seq.Perform(S, Entity, Kind, Value);
3009 }
3010}
3011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003012/// Perform the initialization of a potentially-movable value, which
Douglas Gregor626fbed2011-01-21 21:08:57 +00003013/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00003014///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003015/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00003016/// returned lvalues as rvalues in certain cases (to prefer move construction),
3017/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003018ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00003019Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3020 const VarDecl *NRVOCandidate,
3021 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00003022 Expr *Value,
3023 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003024 // C++14 [class.copy]p32:
3025 // When the criteria for elision of a copy/move operation are met, but not for
3026 // an exception-declaration, and the object to be copied is designated by an
3027 // lvalue, or when the expression in a return statement is a (possibly
3028 // parenthesized) id-expression that names an object with automatic storage
3029 // duration declared in the body or parameter-declaration-clause of the
3030 // innermost enclosing function or lambda-expression, overload resolution to
3031 // select the constructor for the copy is first performed as if the object
3032 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00003033 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003034
Richard Trieu09c163b2018-03-15 03:00:55 +00003035 if (AllowNRVO) {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003036 bool AffectedByCWG1579 = false;
3037
Richard Trieu09c163b2018-03-15 03:00:55 +00003038 if (!NRVOCandidate) {
3039 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003040 if (NRVOCandidate &&
3041 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3042 Value->getExprLoc())) {
3043 const VarDecl *NRVOCandidateInCXX11 =
3044 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3045 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3046 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003047 }
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003048
Richard Trieu09c163b2018-03-15 03:00:55 +00003049 if (NRVOCandidate) {
3050 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003051 true, Res);
3052 }
3053
3054 if (!Res.isInvalid() && AffectedByCWG1579) {
3055 QualType QT = NRVOCandidate->getType();
3056 if (QT.getNonReferenceType()
3057 .getUnqualifiedType()
3058 .isTriviallyCopyableType(Context)) {
3059 // Adding 'std::move' around a trivially copyable variable is probably
3060 // pointless. Don't suggest it.
3061 } else {
3062 // Common cases for this are returning unique_ptr<Derived> from a
3063 // function of return type unique_ptr<Base>, or returning T from a
3064 // function of return type Expected<T>. This is totally fine in a
3065 // post-CWG1579 world, but was not fine before.
3066 assert(!ResultType.isNull());
3067 SmallString<32> Str;
3068 Str += "std::move(";
3069 Str += NRVOCandidate->getDeclName().getAsString();
3070 Str += ")";
3071 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3072 << Value->getSourceRange()
3073 << NRVOCandidate->getDeclName() << ResultType << QT;
3074 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3075 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3076 }
3077 } else if (Res.isInvalid() &&
3078 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3079 Value->getExprLoc())) {
3080 const VarDecl *FakeNRVOCandidate =
3081 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3082 if (FakeNRVOCandidate) {
3083 QualType QT = FakeNRVOCandidate->getType();
3084 if (QT->isLValueReferenceType()) {
3085 // Adding 'std::move' around an lvalue reference variable's name is
3086 // dangerous. Don't suggest it.
3087 } else if (QT.getNonReferenceType()
3088 .getUnqualifiedType()
3089 .isTriviallyCopyableType(Context)) {
3090 // Adding 'std::move' around a trivially copyable variable is probably
3091 // pointless. Don't suggest it.
3092 } else {
3093 ExprResult FakeRes = ExprError();
3094 Expr *FakeValue = Value;
3095 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3096 FakeValue, false, FakeRes);
3097 if (!FakeRes.isInvalid()) {
3098 bool IsThrow =
3099 (Entity.getKind() == InitializedEntity::EK_Exception);
3100 SmallString<32> Str;
3101 Str += "std::move(";
3102 Str += FakeNRVOCandidate->getDeclName().getAsString();
3103 Str += ")";
3104 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3105 << Value->getSourceRange()
3106 << FakeNRVOCandidate->getDeclName() << IsThrow;
3107 Diag(Value->getExprLoc(), diag::note_add_std_move)
3108 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3109 }
3110 }
3111 }
Douglas Gregorf282a762011-01-21 19:38:21 +00003112 }
3113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114
Douglas Gregorf282a762011-01-21 19:38:21 +00003115 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00003117 // (again) now with the return value expression as written.
3118 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00003119 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120
Douglas Gregorf282a762011-01-21 19:38:21 +00003121 return Res;
3122}
3123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003124/// Determine whether the declared return type of the specified function
Richard Smith4db51c22013-09-25 05:02:54 +00003125/// contains 'auto'.
3126static bool hasDeducedReturnType(FunctionDecl *FD) {
3127 const FunctionProtoType *FPT =
3128 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003129 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003130}
3131
Eli Friedman34b49062012-01-26 03:00:14 +00003132/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3133/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003134///
John McCalldadc5752010-08-24 06:29:42 +00003135StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003136Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3137 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003138 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003139 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003140 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003141 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003142 bool HasDeducedReturnType =
3143 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003144
Faisal Valid143a0c2017-04-01 21:30:49 +00003145 if (ExprEvalContexts.back().Context ==
3146 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003147 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3148 if (RetValExp) {
3149 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3150 if (ER.isInvalid())
3151 return StmtError();
3152 RetValExp = ER.get();
3153 }
3154 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3155 }
3156
3157 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003158 // In C++1y, the return type may involve 'auto'.
3159 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3160 FunctionDecl *FD = CurLambda->CallOperator;
3161 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003162 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003163
3164 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3165 assert(AT && "lost auto type from lambda return type");
3166 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3167 FD->setInvalidDecl();
3168 return StmtError();
3169 }
Alp Toker314cc812014-01-25 16:55:45 +00003170 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003171 } else if (CurCap->HasImplicitReturnType) {
3172 // For blocks/lambdas with implicit return types, we check each return
3173 // statement individually, and deduce the common return type when the block
3174 // or lambda is completed.
3175 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003176 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003177 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3178 if (Result.isInvalid())
3179 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003180 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003181
Richard Smith5a0e50c2014-12-19 22:10:51 +00003182 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3183 // when deducing a return type for a lambda-expression (or by extension
3184 // for a block). These rules differ from the stated C++11 rules only in
3185 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003186 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003187 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003188 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003189 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003190 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003191 if (RetValExp) {
3192 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3193 // initializer list, because it is not an expression (even
3194 // though we represent it as one). We still deduce 'void'.
3195 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3196 << RetValExp->getSourceRange();
3197 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003198
Jordan Rosed39e5f12012-07-02 21:19:23 +00003199 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003200 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003201
3202 // Although we'll properly infer the type of the block once it's completed,
3203 // make sure we provide a return type now for better error recovery.
3204 if (CurCap->ReturnType.isNull())
3205 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003206 }
Eli Friedman34b49062012-01-26 03:00:14 +00003207 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003208
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003209 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00003210 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3211 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3212 return StmtError();
3213 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003214 } else if (CapturedRegionScopeInfo *CurRegion =
3215 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3216 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3217 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003218 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003219 assert(CurLambda && "unknown kind of captured scope");
3220 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3221 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003222 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3223 return StmtError();
3224 }
3225 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003226
Steve Naroffc540d662008-09-03 18:15:37 +00003227 // Otherwise, verify that this result type matches the previous one. We are
3228 // pickier with blocks than for normal functions because we don't have GCC
3229 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003230 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003231 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003232 // Delay processing for now. TODO: there are lots of dependent
3233 // types we can conclusively prove aren't void.
3234 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003235 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003236 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003237 (RetValExp->isTypeDependent() ||
3238 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003239 if (!getLangOpts().CPlusPlus &&
3240 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003241 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003242 else {
3243 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003244 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003245 }
Steve Naroffc540d662008-09-03 18:15:37 +00003246 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003247 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003248 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3249 } else if (!RetValExp->isTypeDependent()) {
3250 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003251
John McCall5500ef22011-08-17 22:09:46 +00003252 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3253 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3254 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003255
John McCall5500ef22011-08-17 22:09:46 +00003256 // In C++ the return statement is handled via a copy initialization.
3257 // the C version of which boils down to CheckSingleAssignmentConstraints.
Richard Trieu09c163b2018-03-15 03:00:55 +00003258 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
John McCall5500ef22011-08-17 22:09:46 +00003259 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3260 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003261 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003262 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3263 FnRetType, RetValExp);
3264 if (Res.isInvalid()) {
3265 // FIXME: Cleanup temporaries here, anyway?
3266 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003267 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003268 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003269 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003270 } else {
Richard Trieu09c163b2018-03-15 03:00:55 +00003271 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Steve Naroffc540d662008-09-03 18:15:37 +00003272 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003273
John McCall75f92b52011-08-17 21:34:14 +00003274 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003275 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3276 if (ER.isInvalid())
3277 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003278 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003279 }
John McCall5500ef22011-08-17 22:09:46 +00003280 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3281 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003282
Jordan Rosed39e5f12012-07-02 21:19:23 +00003283 // If we need to check for the named return value optimization,
3284 // or if we need to infer the return type,
3285 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003286 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003287 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288
Richard Smith9f690bd2015-10-27 06:02:45 +00003289 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3290 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3291
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003292 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003293}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003294
Nico Weber72889432014-09-06 01:25:55 +00003295namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003296/// Marks all typedefs in all local classes in a type referenced.
Nico Weber72889432014-09-06 01:25:55 +00003297///
3298/// In a function like
3299/// auto f() {
3300/// struct S { typedef int a; };
3301/// return S();
3302/// }
3303///
3304/// the local type escapes and could be referenced in some TUs but not in
3305/// others. Pretend that all local typedefs are always referenced, to not warn
3306/// on this. This isn't necessary if f has internal linkage, or the typedef
3307/// is private.
3308class LocalTypedefNameReferencer
3309 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3310public:
3311 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3312 bool VisitRecordType(const RecordType *RT);
3313private:
3314 Sema &S;
3315};
3316bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3317 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3318 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3319 R->isDependentType())
3320 return true;
3321 for (auto *TmpD : R->decls())
3322 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3323 if (T->getAccess() != AS_private || R->hasFriends())
3324 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3325 return true;
3326}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003327}
Nico Weber72889432014-09-06 01:25:55 +00003328
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003329TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003330 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003331 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3332 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003333 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003334}
3335
Richard Smith2a7d4812013-05-04 07:00:32 +00003336/// Deduce the return type for a function from a returned expression, per
3337/// C++1y [dcl.spec.auto]p6.
3338bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3339 SourceLocation ReturnLoc,
3340 Expr *&RetExpr,
3341 AutoType *AT) {
Richard Smith50e291e2018-01-02 23:52:42 +00003342 // If this is the conversion function for a lambda, we choose to deduce it
3343 // type from the corresponding call operator, not from the synthesized return
3344 // statement within it. See Sema::DeduceReturnType.
3345 if (isLambdaConversionOperator(FD))
3346 return false;
3347
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003348 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003349 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003350
Richard Smithc58f38f2013-08-14 20:16:31 +00003351 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3352 // If the deduction is for a return statement and the initializer is
3353 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003354 Diag(RetExpr->getExprLoc(),
3355 getCurLambda() ? diag::err_lambda_return_init_list
3356 : diag::err_auto_fn_return_init_list)
3357 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003358 return true;
3359 }
3360
3361 if (FD->isDependentContext()) {
3362 // C++1y [dcl.spec.auto]p12:
3363 // Return type deduction [...] occurs when the definition is
3364 // instantiated even if the function body contains a return
3365 // statement with a non-type-dependent operand.
3366 assert(AT->isDeduced() && "should have deduced to dependent type");
3367 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003368 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003369
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003370 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003371 // Otherwise, [...] deduce a value for U using the rules of template
3372 // argument deduction.
3373 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3374
3375 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3376 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3377 << OrigResultType.getType() << RetExpr->getType();
3378
3379 if (DAR != DAR_Succeeded)
3380 return true;
Nico Weber72889432014-09-06 01:25:55 +00003381
3382 // If a local type is part of the returned type, mark its fields as
3383 // referenced.
3384 LocalTypedefNameReferencer Referencer(*this);
3385 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003386 } else {
3387 // In the case of a return with no operand, the initializer is considered
3388 // to be void().
3389 //
3390 // Deduction here can only succeed if the return type is exactly 'cv auto'
3391 // or 'decltype(auto)', so just check for that case directly.
3392 if (!OrigResultType.getType()->getAs<AutoType>()) {
3393 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3394 << OrigResultType.getType();
3395 return true;
3396 }
3397 // We always deduce U = void in this case.
3398 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3399 if (Deduced.isNull())
3400 return true;
3401 }
3402
3403 // If a function with a declared return type that contains a placeholder type
3404 // has multiple return statements, the return type is deduced for each return
3405 // statement. [...] if the type deduced is not the same in each deduction,
3406 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003407 QualType DeducedT = AT->getDeducedType();
3408 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003409 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003410 // It is possible that NewAT->getDeducedType() is null. When that happens,
3411 // we should not crash, instead we ignore this deduction.
3412 if (NewAT->getDeducedType().isNull())
3413 return false;
3414
Douglas Gregora602a152015-10-01 20:20:47 +00003415 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003416 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003417 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3418 NewAT->getDeducedType());
3419 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003420 const LambdaScopeInfo *LambdaSI = getCurLambda();
3421 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3422 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003423 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003424 << true /*IsLambda*/;
3425 } else {
3426 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3427 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003428 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003429 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003430 return true;
3431 }
3432 } else if (!FD->isInvalidDecl()) {
3433 // Update all declarations of the function to have the deduced return type.
3434 Context.adjustDeducedFunctionResultType(FD, Deduced);
3435 }
3436
3437 return false;
3438}
3439
John McCalldadc5752010-08-24 06:29:42 +00003440StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003441Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3442 Scope *CurScope) {
3443 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Faisal Valid143a0c2017-04-01 21:30:49 +00003444 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3445 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003446 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003447
Taiju Tsuiki3be68e12018-06-19 05:35:30 +00003448 if (VarDecl *VD =
3449 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3450 CurScope->addNRVOCandidate(VD);
3451 } else {
3452 CurScope->setNoNRVO();
3453 }
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003454
Nico Weberd64657f2015-03-09 02:47:59 +00003455 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3456
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003457 return R;
3458}
3459
3460StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003461 // Check for unexpanded parameter packs.
3462 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3463 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003464
Eli Friedman34b49062012-01-26 03:00:14 +00003465 if (isa<CapturingScopeInfo>(getCurFunction()))
3466 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003467
Chris Lattner79413952008-12-04 23:50:19 +00003468 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003469 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003470 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003471 bool isObjCMethod = false;
3472
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003473 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003474 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003475 if (FD->hasAttrs())
3476 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003477 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003478 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003479 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003480 if (FD->isMain() && RetValExp)
3481 if (isa<CXXBoolLiteralExpr>(RetValExp))
3482 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3483 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003484 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003485 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003486 isObjCMethod = true;
3487 if (MD->hasAttrs())
3488 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003489 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3490 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003491 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003492 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003493 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3494 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003495 }
3496 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003497 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003498
Richard Smithb130fe72016-06-23 19:16:49 +00003499 // C++1z: discarded return statements are not considered when deducing a
3500 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003501 if (ExprEvalContexts.back().Context ==
3502 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003503 FnRetType->getContainedAutoType()) {
3504 if (RetValExp) {
3505 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3506 if (ER.isInvalid())
3507 return StmtError();
3508 RetValExp = ER.get();
3509 }
3510 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3511 }
3512
Richard Smith2a7d4812013-05-04 07:00:32 +00003513 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3514 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003515 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003516 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3517 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003518 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003519 FD->setInvalidDecl();
3520 return StmtError();
3521 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003522 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003523 }
3524 }
3525 }
3526
Richard Smithc58f38f2013-08-14 20:16:31 +00003527 bool HasDependentReturnType = FnRetType->isDependentType();
3528
Craig Topperc3ec1492014-05-26 06:22:03 +00003529 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003530 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003531 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003532 if (isa<InitListExpr>(RetValExp)) {
3533 // We simply never allow init lists as the return value of void
3534 // functions. This is compatible because this was never allowed before,
3535 // so there's no legacy code to deal with.
3536 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3537 int FunctionKind = 0;
3538 if (isa<ObjCMethodDecl>(CurDecl))
3539 FunctionKind = 1;
3540 else if (isa<CXXConstructorDecl>(CurDecl))
3541 FunctionKind = 2;
3542 else if (isa<CXXDestructorDecl>(CurDecl))
3543 FunctionKind = 3;
3544
3545 Diag(ReturnLoc, diag::err_return_init_list)
3546 << CurDecl->getDeclName() << FunctionKind
3547 << RetValExp->getSourceRange();
3548
3549 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003550 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003551 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003552 // C99 6.8.6.4p1 (ext_ since GCC warns)
3553 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003554 if (RetValExp->getType()->isVoidType()) {
3555 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3556 if (isa<CXXConstructorDecl>(CurDecl) ||
3557 isa<CXXDestructorDecl>(CurDecl))
3558 D = diag::err_ctor_dtor_returns_void;
3559 else
3560 D = diag::ext_return_has_void_expr;
3561 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003562 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003563 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003564 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003565 if (Result.isInvalid())
3566 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003567 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003568 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003569 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003570 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003571 // return of void in constructor/destructor is illegal in C++.
3572 if (D == diag::err_ctor_dtor_returns_void) {
3573 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3574 Diag(ReturnLoc, D)
3575 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3576 << RetValExp->getSourceRange();
3577 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003578 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003579 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003580 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003581 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003582
3583 int FunctionKind = 0;
3584 if (isa<ObjCMethodDecl>(CurDecl))
3585 FunctionKind = 1;
3586 else if (isa<CXXConstructorDecl>(CurDecl))
3587 FunctionKind = 2;
3588 else if (isa<CXXDestructorDecl>(CurDecl))
3589 FunctionKind = 3;
3590
Nick Lewycky1be750a2011-06-01 07:44:31 +00003591 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003592 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003593 << RetValExp->getSourceRange();
3594 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003595 }
Mike Stump11289f42009-09-09 15:08:12 +00003596
Sebastian Redleef474c2012-02-22 10:50:08 +00003597 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003598 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3599 if (ER.isInvalid())
3600 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003601 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003602 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604
Craig Topperc3ec1492014-05-26 06:22:03 +00003605 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003606 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003607 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003608
David Majnemer2887ad32014-12-13 08:12:56 +00003609 unsigned DiagID;
3610 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3611 // C++11 [stmt.return]p2
3612 DiagID = diag::err_constexpr_return_missing_expr;
3613 FD->setInvalidDecl();
3614 } else if (getLangOpts().C99) {
3615 // C99 6.8.6.4p1 (ext_ since GCC warns)
3616 DiagID = diag::ext_return_missing_expr;
3617 } else {
3618 // C90 6.6.6.4p4
3619 DiagID = diag::warn_return_missing_expr;
3620 }
3621
3622 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003623 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003624 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003625 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003626
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003627 Result = new (Context) ReturnStmt(ReturnLoc);
3628 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003629 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003630 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003631
3632 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3633
3634 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3635 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3636 // function return.
3637
3638 // In C++ the return statement is handled via a copy initialization,
3639 // the C version of which boils down to CheckSingleAssignmentConstraints.
3640 if (RetValExp)
Richard Trieu09c163b2018-03-15 03:00:55 +00003641 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Richard Smith2a7d4812013-05-04 07:00:32 +00003642 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003643 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003645 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003646 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003648 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003649 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003650 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003651 return StmtError();
3652 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003653 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003654
3655 // If we have a related result type, we need to implicitly
3656 // convert back to the formal result type. We can't pretend to
3657 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003658 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003659 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003660 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3661 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003662 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3663 if (Res.isInvalid()) {
3664 // FIXME: Clean up temporaries here anyway?
3665 return StmtError();
3666 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003667 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003668 }
3669
Artyom Skrobov9f213442014-01-24 11:10:39 +00003670 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3671 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
John McCallacf0ee52010-10-08 02:01:28 +00003674 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003675 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3676 if (ER.isInvalid())
3677 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003678 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003679 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003680 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682
3683 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003684 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003685 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003686 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003687
Richard Smith9f690bd2015-10-27 06:02:45 +00003688 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3689 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3690
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003691 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003692}
3693
John McCalldadc5752010-08-24 06:29:42 +00003694StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003695Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003696 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003697 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003698 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003699 if (Var && Var->isInvalidDecl())
3700 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003702 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003703}
3704
John McCalldadc5752010-08-24 06:29:42 +00003705StmtResult
John McCallb268a282010-08-23 23:25:46 +00003706Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003707 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003708}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003709
John McCalldadc5752010-08-24 06:29:42 +00003710StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003712 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003713 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003714 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3715
Reid Kleckner87a31802018-03-12 21:43:02 +00003716 setFunctionHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003717 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003718 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3719 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003720}
3721
John McCall0bd3e402012-05-08 21:41:25 +00003722StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003723 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003724 ExprResult Result = DefaultLvalueConversion(Throw);
3725 if (Result.isInvalid())
3726 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003727
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003728 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003729 if (Result.isInvalid())
3730 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003731 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003732
Douglas Gregor2900c162010-04-22 21:44:01 +00003733 QualType ThrowType = Throw->getType();
3734 // Make sure the expression type is an ObjC pointer or "void *".
3735 if (!ThrowType->isDependentType() &&
3736 !ThrowType->isObjCObjectPointerType()) {
3737 const PointerType *PT = ThrowType->getAs<PointerType>();
3738 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003739 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003740 << Throw->getType() << Throw->getSourceRange());
3741 }
3742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003744 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003745}
3746
John McCalldadc5752010-08-24 06:29:42 +00003747StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003749 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003750 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003751 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3752
John McCallb268a282010-08-23 23:25:46 +00003753 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003754 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003755 // in the context of an @catch clause).
3756 Scope *AtCatchParent = CurScope;
3757 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3758 AtCatchParent = AtCatchParent->getParent();
3759 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003760 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 }
John McCallb268a282010-08-23 23:25:46 +00003762 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003763}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003764
John McCalld9bb7432011-07-27 21:50:02 +00003765ExprResult
3766Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3767 ExprResult result = DefaultLvalueConversion(operand);
3768 if (result.isInvalid())
3769 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003770 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003771
3772 // Make sure the expression type is an ObjC pointer or "void *".
3773 QualType type = operand->getType();
3774 if (!type->isDependentType() &&
3775 !type->isObjCObjectPointerType()) {
3776 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003777 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3778 if (getLangOpts().CPlusPlus) {
3779 if (RequireCompleteType(atLoc, type,
3780 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003781 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003782 << type << operand->getSourceRange();
3783
3784 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003785 if (result.isInvalid())
3786 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003787 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003788 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003789 << type << operand->getSourceRange();
3790
3791 operand = result.get();
3792 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003793 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003794 << type << operand->getSourceRange();
3795 }
3796 }
John McCalld9bb7432011-07-27 21:50:02 +00003797 }
3798
3799 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003800 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003801}
3802
John McCalldadc5752010-08-24 06:29:42 +00003803StmtResult
John McCallb268a282010-08-23 23:25:46 +00003804Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3805 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003806 // We can't jump into or indirect-jump out of a @synchronized block.
Reid Kleckner87a31802018-03-12 21:43:02 +00003807 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003808 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003809}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003810
3811/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3812/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003813StmtResult
John McCall48871652010-08-21 09:40:31 +00003814Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003815 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003816 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003817 return new (Context)
3818 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003819}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003820
John McCall31168b02011-06-15 23:02:42 +00003821StmtResult
3822Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
Reid Kleckner87a31802018-03-12 21:43:02 +00003823 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003824 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003825}
3826
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003827namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003828class CatchHandlerType {
3829 QualType QT;
3830 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003831
Aaron Ballman8aee642902015-04-08 00:05:29 +00003832 // This is a special constructor to be used only with DenseMapInfo's
3833 // getEmptyKey() and getTombstoneKey() functions.
3834 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3835 enum Unique { ForDenseMap };
3836 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3837
Sebastian Redl63c4da02009-07-29 17:15:45 +00003838public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003839 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003840 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003841 /// level pointer and cv-qualifiers.
3842 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3843 if (QT->isPointerType())
3844 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003845
Aaron Ballman8aee642902015-04-08 00:05:29 +00003846 if (IsPointer || QT->isReferenceType())
3847 QT = QT->getPointeeType();
3848 QT = QT.getUnqualifiedType();
3849 }
3850
3851 /// Used when creating a CatchHandlerType from a base class type; pretends the
3852 /// type passed in had the pointer qualifier, does not need to get an
3853 /// unqualified type.
3854 CatchHandlerType(QualType QT, bool IsPointer)
3855 : QT(QT), IsPointer(IsPointer) {}
3856
3857 QualType underlying() const { return QT; }
3858 bool isPointer() const { return IsPointer; }
3859
3860 friend bool operator==(const CatchHandlerType &LHS,
3861 const CatchHandlerType &RHS) {
3862 // If the pointer qualification does not match, we can return early.
3863 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003864 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003865 // Otherwise, check the underlying type without cv-qualifiers.
3866 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003867 }
3868};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003869} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003870
Aaron Ballman8aee642902015-04-08 00:05:29 +00003871namespace llvm {
3872template <> struct DenseMapInfo<CatchHandlerType> {
3873 static CatchHandlerType getEmptyKey() {
3874 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3875 CatchHandlerType::ForDenseMap);
3876 }
3877
3878 static CatchHandlerType getTombstoneKey() {
3879 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3880 CatchHandlerType::ForDenseMap);
3881 }
3882
3883 static unsigned getHashValue(const CatchHandlerType &Base) {
3884 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3885 }
3886
3887 static bool isEqual(const CatchHandlerType &LHS,
3888 const CatchHandlerType &RHS) {
3889 return LHS == RHS;
3890 }
3891};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003892}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003893
3894namespace {
3895class CatchTypePublicBases {
3896 ASTContext &Ctx;
3897 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3898 const bool CheckAgainstPointer;
3899
3900 CXXCatchStmt *FoundHandler;
3901 CanQualType FoundHandlerType;
3902
3903public:
3904 CatchTypePublicBases(
3905 ASTContext &Ctx,
3906 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3907 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3908 FoundHandler(nullptr) {}
3909
3910 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3911 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3912
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003913 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003914 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003915 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003916 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003917 auto I = M.find(Check);
3918 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003919 FoundHandler = I->second;
3920 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003921 return true;
3922 }
3923 }
3924 return false;
3925 }
3926};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003927}
Dan Gohman28ade552010-07-26 21:25:24 +00003928
Sebastian Redl9b244a82008-12-22 21:35:02 +00003929/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3930/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003931StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3932 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003933 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003934 if (!getLangOpts().CXXExceptions &&
Alexey Bataev1ab34572018-05-02 16:52:07 +00003935 !getSourceManager().isInSystemHeader(TryLoc) &&
3936 (!getLangOpts().OpenMPIsDevice ||
3937 !getLangOpts().OpenMPHostCXXExceptions ||
3938 isInOpenMPTargetExecutionDirective() ||
3939 isInOpenMPDeclareTargetContext()))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003940 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003941
Justin Lebar2a8db342016-09-28 22:45:54 +00003942 // Exceptions aren't allowed in CUDA device code.
3943 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00003944 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3945 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00003946
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003947 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3948 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3949
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003950 sema::FunctionScopeInfo *FSI = getCurFunction();
3951
Reid Klecknere7175912015-02-02 22:15:31 +00003952 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003953 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003954 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003955 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003956 }
3957
Robert Wilhelmcafda822013-08-22 09:20:03 +00003958 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003959 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003960 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003961
Aaron Ballman8aee642902015-04-08 00:05:29 +00003962 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003963 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003964 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003965
Aaron Ballman8aee642902015-04-08 00:05:29 +00003966 // Diagnose when the handler is a catch-all handler, but it isn't the last
3967 // handler for the try block. [except.handle]p5. Also, skip exception
3968 // declarations that are invalid, since we can't usefully report on them.
3969 if (!H->getExceptionDecl()) {
3970 if (i < NumHandlers - 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003971 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003972 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003973 } else if (H->getExceptionDecl()->isInvalidDecl())
3974 continue;
3975
3976 // Walk the type hierarchy to diagnose when this type has already been
3977 // handled (duplication), or cannot be handled (derivation inversion). We
3978 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003979 CatchHandlerType HandlerCHT =
3980 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003981
3982 // We can ignore whether the type is a reference or a pointer; we need the
3983 // underlying declaration type in order to get at the underlying record
3984 // decl, if there is one.
3985 QualType Underlying = HandlerCHT.underlying();
3986 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3987 if (!RD->hasDefinition())
3988 continue;
3989 // Check that none of the public, unambiguous base classes are in the
3990 // map ([except.handle]p1). Give the base classes the same pointer
3991 // qualification as the original type we are basing off of. This allows
3992 // comparison against the handler type using the same top-level pointer
3993 // as the original type.
3994 CXXBasePaths Paths;
3995 Paths.setOrigin(RD);
3996 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003997 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003998 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3999 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4000 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4001 diag::warn_exception_caught_by_earlier_handler)
4002 << H->getCaughtType();
4003 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4004 diag::note_previous_exception_handler)
4005 << Problem->getCaughtType();
4006 }
4007 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00004008 }
Mike Stump11289f42009-09-09 15:08:12 +00004009
Aaron Ballman8aee642902015-04-08 00:05:29 +00004010 // Add the type the list of ones we have handled; diagnose if we've already
4011 // handled it.
4012 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4013 if (!R.second) {
4014 const CXXCatchStmt *Problem = R.first->second;
4015 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4016 diag::warn_exception_caught_by_earlier_handler)
4017 << H->getCaughtType();
4018 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4019 diag::note_previous_exception_handler)
4020 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00004021 }
4022 }
Mike Stump11289f42009-09-09 15:08:12 +00004023
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004024 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00004025
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004026 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00004027}
John Wiegley1c0675e2011-04-28 01:08:34 +00004028
Reid Klecknere7175912015-02-02 22:15:31 +00004029StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4030 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004031 assert(TryBlock && Handler);
4032
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004033 sema::FunctionScopeInfo *FSI = getCurFunction();
4034
Reid Klecknere7175912015-02-02 22:15:31 +00004035 // SEH __try is incompatible with C++ try. Borland appears to support this,
4036 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004037 if (!getLangOpts().Borland) {
4038 if (FSI->FirstCXXTryLoc.isValid()) {
4039 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4040 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4041 }
Reid Klecknere7175912015-02-02 22:15:31 +00004042 }
John Wiegley1c0675e2011-04-28 01:08:34 +00004043
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004044 FSI->setHasSEHTry(TryLoc);
4045
4046 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4047 // track if they use SEH.
4048 DeclContext *DC = CurContext;
4049 while (DC && !DC->isFunctionOrMethod())
4050 DC = DC->getParent();
4051 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4052 if (FD)
4053 FD->setUsesSEHTry(true);
4054 else
4055 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00004056
Reid Kleckner8819a402015-07-10 00:16:25 +00004057 // Reject __try on unsupported targets.
4058 if (!Context.getTargetInfo().isSEHTrySupported())
4059 Diag(TryLoc, diag::err_seh_try_unsupported);
4060
Reid Klecknere7175912015-02-02 22:15:31 +00004061 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00004062}
4063
4064StmtResult
4065Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4066 Expr *FilterExpr,
4067 Stmt *Block) {
4068 assert(FilterExpr && Block);
4069
4070 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00004071 return StmtError(Diag(FilterExpr->getExprLoc(),
4072 diag::err_filter_expression_integral)
4073 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00004074 }
4075
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004076 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004077}
4078
Nico Weberd64657f2015-03-09 02:47:59 +00004079void Sema::ActOnStartSEHFinallyBlock() {
4080 CurrentSEHFinally.push_back(CurScope);
4081}
4082
Nico Weberce903292015-03-09 03:17:15 +00004083void Sema::ActOnAbortSEHFinallyBlock() {
4084 CurrentSEHFinally.pop_back();
4085}
4086
Nico Weberd64657f2015-03-09 02:47:59 +00004087StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004088 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00004089 CurrentSEHFinally.pop_back();
4090 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004091}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004092
Nico Weberc7d05962014-07-06 22:32:59 +00004093StmtResult
4094Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00004095 Scope *SEHTryParent = CurScope;
4096 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4097 SEHTryParent = SEHTryParent->getParent();
4098 if (!SEHTryParent)
4099 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00004100 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00004101
Nico Weber9b982072014-07-07 00:12:30 +00004102 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00004103}
4104
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004105StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4106 bool IsIfExists,
4107 NestedNameSpecifierLoc QualifierLoc,
4108 DeclarationNameInfo NameInfo,
4109 Stmt *Nested)
4110{
4111 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004112 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004113 cast<CompoundStmt>(Nested));
4114}
4115
4116
Chad Rosier02a84392012-08-10 17:56:09 +00004117StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004118 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004119 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004120 UnqualifiedId &Name,
4121 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00004122 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004123 SS.getWithLocInContext(Context),
4124 GetNameFromUnqualifiedId(Name),
4125 Nested);
4126}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004127
4128RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00004129Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4130 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004131 DeclContext *DC = CurContext;
4132 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4133 DC = DC->getParent();
4134
Craig Topperc3ec1492014-05-26 06:22:03 +00004135 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004136 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004137 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4138 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004139 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004140 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004141
Alexey Bataev330de032014-10-29 12:21:55 +00004142 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004143 DC->addDecl(RD);
4144 RD->setImplicit();
4145 RD->startDefinition();
4146
Alexey Bataev9959db52014-05-06 10:08:46 +00004147 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004148 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004149 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004150 return RD;
4151}
4152
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004153static void
4154buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
4155 SmallVectorImpl<Expr *> &CaptureInits,
4156 ArrayRef<sema::Capture> Candidates) {
4157 for (const sema::Capture &Cap : Candidates) {
4158 if (Cap.isThisCapture()) {
4159 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004160 CapturedStmt::VCK_This));
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004161 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004162 continue;
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004163 } else if (Cap.isVLATypeCapture()) {
Alexey Bataev330de032014-10-29 12:21:55 +00004164 Captures.push_back(
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004165 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
Alexey Bataev330de032014-10-29 12:21:55 +00004166 CaptureInits.push_back(nullptr);
4167 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004168 }
4169
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004170 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4171 Cap.isReferenceCapture()
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004172 ? CapturedStmt::VCK_ByRef
4173 : CapturedStmt::VCK_ByCopy,
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004174 Cap.getVariable()));
4175 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004176 }
4177}
4178
4179void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004180 CapturedRegionKind Kind,
4181 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004182 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004183 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004184
Alexey Bataev9959db52014-05-06 10:08:46 +00004185 // Build the context parameter
4186 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4187 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4188 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004189 auto *Param =
4190 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4191 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004192 DC->addDecl(Param);
4193
4194 CD->setContextParam(0, Param);
4195
4196 // Enter the capturing scope for this captured region.
4197 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4198
4199 if (CurScope)
4200 PushDeclContext(CurScope, CD);
4201 else
4202 CurContext = CD;
4203
Faisal Valid143a0c2017-04-01 21:30:49 +00004204 PushExpressionEvaluationContext(
4205 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004206}
4207
4208void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4209 CapturedRegionKind Kind,
4210 ArrayRef<CapturedParamNameType> Params) {
4211 CapturedDecl *CD = nullptr;
4212 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4213
4214 // Build the context parameter
4215 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4216 bool ContextIsFound = false;
4217 unsigned ParamNum = 0;
4218 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4219 E = Params.end();
4220 I != E; ++I, ++ParamNum) {
4221 if (I->second.isNull()) {
4222 assert(!ContextIsFound &&
4223 "null type has been found already for '__context' parameter");
4224 IdentifierInfo *ParamName = &Context.Idents.get("__context");
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004225 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4226 .withConst()
4227 .withRestrict();
Alexey Bataev56223232017-06-09 13:40:18 +00004228 auto *Param =
4229 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4230 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004231 DC->addDecl(Param);
4232 CD->setContextParam(ParamNum, Param);
4233 ContextIsFound = true;
4234 } else {
4235 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004236 auto *Param =
4237 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4238 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004239 DC->addDecl(Param);
4240 CD->setParam(ParamNum, Param);
4241 }
4242 }
4243 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004244 if (!ContextIsFound) {
4245 // Add __context implicitly if it is not specified.
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 Bataev301a2d92014-05-14 10:40:54 +00004251 DC->addDecl(Param);
4252 CD->setContextParam(ParamNum, Param);
4253 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004254 // Enter the capturing scope for this captured region.
4255 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4256
4257 if (CurScope)
4258 PushDeclContext(CurScope, CD);
4259 else
4260 CurContext = CD;
4261
Faisal Valid143a0c2017-04-01 21:30:49 +00004262 PushExpressionEvaluationContext(
4263 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004264}
4265
Wei Pan17fbf6e2013-05-04 03:59:06 +00004266void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004267 DiscardCleanupsInEvaluationContext();
4268 PopExpressionEvaluationContext();
4269
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004270 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4271 RecordDecl *Record = RSI->TheRecordDecl;
4272 Record->setInvalidDecl();
4273
Aaron Ballman62e47c42014-03-10 13:43:55 +00004274 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004275 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00004276 SourceLocation(), SourceLocation(), ParsedAttributesView());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004277
Wei Pan17fbf6e2013-05-04 03:59:06 +00004278 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004279 PopFunctionScopeInfo();
4280}
4281
4282StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4283 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4284
4285 SmallVector<CapturedStmt::Capture, 4> Captures;
4286 SmallVector<Expr *, 4> CaptureInits;
4287 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4288
4289 CapturedDecl *CD = RSI->TheCapturedDecl;
4290 RecordDecl *RD = RSI->TheRecordDecl;
4291
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004292 CapturedStmt *Res = CapturedStmt::Create(
4293 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4294 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004295
4296 CD->setBody(Res->getCapturedStmt());
4297 RD->completeDefinition();
4298
Wei Pan17fbf6e2013-05-04 03:59:06 +00004299 DiscardCleanupsInEvaluationContext();
4300 PopExpressionEvaluationContext();
4301
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004302 PopDeclContext();
4303 PopFunctionScopeInfo();
4304
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004305 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004306}