blob: 7f1e4d527d255e3a5401773e4bd345fae85fb71e [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
Richard Trieu99e1c952014-03-11 03:11:08 +0000124/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
125/// 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.
219 bool ShouldSuppress =
220 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
John McCalldadc5752010-08-24 06:29:42 +0000395StmtResult
John McCallb268a282010-08-23 23:25:46 +0000396Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
397 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000398 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000399 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000400
John McCallaab3e412010-08-25 08:40:02 +0000401 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000402 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000403 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000404 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000405
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000406 ExprResult LHS =
407 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
408 if (!getLangOpts().CPlusPlus11)
409 return VerifyIntegerConstantExpression(E);
410 if (Expr *CondExpr =
411 getCurFunction()->SwitchStack.back()->getCond()) {
412 QualType CondType = CondExpr->getType();
413 llvm::APSInt TempVal;
414 return CheckConvertedConstantExpression(E, CondType, TempVal,
415 CCEK_CaseValue);
416 }
417 return ExprError();
418 });
419 if (LHS.isInvalid())
420 return StmtError();
421 LHSVal = LHS.get();
422
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000423 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000424 // C99 6.8.4.2p3: The expression shall be an integer constant.
425 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000426 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000427 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000428 if (!LHSVal)
429 return StmtError();
430 }
Richard Smithf8379a02012-01-18 23:55:52 +0000431
432 // GCC extension: The expression shall be an integer constant.
433
Richard Smithf4c51d92012-02-04 09:53:13 +0000434 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000435 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000436 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000437 }
438 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000439
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000440 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000441 getLangOpts().CPlusPlus11);
442 if (LHS.isInvalid())
443 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000444
Richard Smith5b555da2014-11-20 01:24:12 +0000445 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
446 getLangOpts().CPlusPlus11)
447 : ExprResult();
448 if (RHS.isInvalid())
449 return StmtError();
450
451 CaseStmt *CS = new (Context)
452 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000453 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000454 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000455}
456
Chris Lattner34a22092009-03-04 04:23:07 +0000457/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000458void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000459 DiagnoseUnusedExprResult(SubStmt);
460
Chris Lattner34a22092009-03-04 04:23:07 +0000461 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000462 CS->setSubStmt(SubStmt);
463}
464
John McCalldadc5752010-08-24 06:29:42 +0000465StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000466Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000467 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000468 DiagnoseUnusedExprResult(SubStmt);
469
John McCallaab3e412010-08-25 08:40:02 +0000470 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000471 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000472 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000473 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000474
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000475 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000476 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000477 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000478}
479
John McCalldadc5752010-08-24 06:29:42 +0000480StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000481Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
482 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000483 // If the label was multiply defined, reject it now.
484 if (TheDecl->getStmt()) {
485 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
486 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000487 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000488 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000489
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000490 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000491 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
492 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000493 if (!TheDecl->isGnuLocal()) {
494 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000495 if (!TheDecl->isMSAsmLabel()) {
496 // Don't update the location of MS ASM labels. These will result in
497 // a diagnostic, and changing the location here will mess that up.
498 TheDecl->setLocation(IdentLoc);
499 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000500 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000501 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000502}
503
Richard Smithc202b282012-04-14 00:33:13 +0000504StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000505 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000506 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000507 // Fill in the declaration and return it.
508 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000509 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000510}
511
Richard Trieufaca2d82016-02-18 23:58:40 +0000512namespace {
513class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
514 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
515 Sema &SemaRef;
516public:
517 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
518 void VisitBinaryOperator(BinaryOperator *E) {
519 if (E->getOpcode() == BO_Comma)
520 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
521 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
522 }
523};
524}
525
John McCalldadc5752010-08-24 06:29:42 +0000526StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000527Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
528 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000529 Stmt *thenStmt, SourceLocation ElseLoc,
530 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000531 if (Cond.isInvalid())
532 Cond = ConditionResult(
533 *this, nullptr,
534 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
535 Context.BoolTy, VK_RValue),
536 IfLoc),
537 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000538
Richard Smithb130fe72016-06-23 19:16:49 +0000539 Expr *CondExpr = Cond.get().second;
Richard Smith03a4aa32016-06-23 19:02:52 +0000540 if (!Diags.isIgnored(diag::warn_comma_operator,
Richard Smithb130fe72016-06-23 19:16:49 +0000541 CondExpr->getExprLoc()))
542 CommaVisitor(*this).Visit(CondExpr);
543
Hans Wennborg59ad1502017-11-20 17:48:54 +0000544 if (!elseStmt)
Hans Wennborg95419752017-11-20 17:38:16 +0000545 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
546 diag::warn_empty_if_body);
Richard Smithb130fe72016-06-23 19:16:49 +0000547
Richard Smitha547eb22016-07-14 00:11:03 +0000548 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
549 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000550}
551
552StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000553 Stmt *InitStmt, ConditionResult Cond,
554 Stmt *thenStmt, SourceLocation ElseLoc,
555 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000556 if (Cond.isInvalid())
557 return StmtError();
558
Erik Pilkington5cd57172016-08-16 17:44:11 +0000559 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Reid Kleckner87a31802018-03-12 21:43:02 +0000560 setFunctionHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000561
562 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000563 DiagnoseUnusedExprResult(elseStmt);
564
Richard Smitha547eb22016-07-14 00:11:03 +0000565 return new (Context)
566 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
567 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000568}
Steve Naroff86272ea2007-05-29 02:14:17 +0000569
Chris Lattner67998452007-08-23 18:29:20 +0000570namespace {
571 struct CaseCompareFunctor {
572 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
573 const llvm::APSInt &RHS) {
574 return LHS.first < RHS;
575 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000576 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
577 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
578 return LHS.first < RHS.first;
579 }
Chris Lattner67998452007-08-23 18:29:20 +0000580 bool operator()(const llvm::APSInt &LHS,
581 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
582 return LHS < RHS.first;
583 }
584 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000585}
Chris Lattner67998452007-08-23 18:29:20 +0000586
Chris Lattner4b2ff022007-09-21 18:15:22 +0000587/// CmpCaseVals - Comparison predicate for sorting case values.
588///
589static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
590 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
591 if (lhs.first < rhs.first)
592 return true;
593
594 if (lhs.first == rhs.first &&
595 lhs.second->getCaseLoc().getRawEncoding()
596 < rhs.second->getCaseLoc().getRawEncoding())
597 return true;
598 return false;
599}
600
Douglas Gregorbd6839732010-02-08 22:24:16 +0000601/// CmpEnumVals - Comparison predicate for sorting enumeration values.
602///
603static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
604 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
605{
606 return lhs.first < rhs.first;
607}
608
609/// EqEnumVals - Comparison preficate for uniqing enumeration values.
610///
611static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
612 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
613{
614 return lhs.first == rhs.first;
615}
616
Chris Lattnera96d4272009-10-16 16:45:22 +0000617/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
618/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000619static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
620 if (const auto *CleanUps = dyn_cast<ExprWithCleanups>(E))
621 E = CleanUps->getSubExpr();
622 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
623 if (ImpCast->getCastKind() != CK_IntegralCast) break;
624 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000625 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000626 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000627}
628
Richard Smith03a4aa32016-06-23 19:02:52 +0000629ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000630 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
631 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000632
Douglas Gregore2b37442012-05-04 22:38:52 +0000633 public:
634 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000635 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
636 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000637
Craig Toppere14c0f82014-03-12 04:55:44 +0000638 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
639 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000640 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
641 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000642
Craig Toppere14c0f82014-03-12 04:55:44 +0000643 SemaDiagnosticBuilder diagnoseIncomplete(
644 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000645 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
646 << T << Cond->getSourceRange();
647 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000648
Craig Toppere14c0f82014-03-12 04:55:44 +0000649 SemaDiagnosticBuilder diagnoseExplicitConv(
650 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000651 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
652 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000653
Craig Toppere14c0f82014-03-12 04:55:44 +0000654 SemaDiagnosticBuilder noteExplicitConv(
655 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000656 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
657 << ConvTy->isEnumeralType() << ConvTy;
658 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000659
Craig Toppere14c0f82014-03-12 04:55:44 +0000660 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
661 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000662 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
663 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000664
Craig Toppere14c0f82014-03-12 04:55:44 +0000665 SemaDiagnosticBuilder noteAmbiguous(
666 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000667 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
668 << ConvTy->isEnumeralType() << ConvTy;
669 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000670
Craig Toppere14c0f82014-03-12 04:55:44 +0000671 SemaDiagnosticBuilder diagnoseConversion(
672 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000673 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000674 }
675 } SwitchDiagnoser(Cond);
676
Richard Smith03a4aa32016-06-23 19:02:52 +0000677 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000678 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000679 if (CondResult.isInvalid())
680 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
John McCall5939b162011-08-06 07:30:58 +0000682 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smith03a4aa32016-06-23 19:02:52 +0000683 return UsualUnaryConversions(CondResult.get());
684}
John McCall5939b162011-08-06 07:30:58 +0000685
Richard Smithc7a05a92016-06-29 21:17:59 +0000686StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
687 Stmt *InitStmt, ConditionResult Cond) {
Richard Smith03a4aa32016-06-23 19:02:52 +0000688 if (Cond.isInvalid())
Meador Ingef0af05c2015-06-25 22:06:40 +0000689 return StmtError();
John McCalla95172b2010-08-01 00:26:45 +0000690
Reid Kleckner87a31802018-03-12 21:43:02 +0000691 setFunctionHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692
Richard Smitha547eb22016-07-14 00:11:03 +0000693 SwitchStmt *SS = new (Context)
694 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
John McCallaab3e412010-08-25 08:40:02 +0000695 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000696 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000697}
698
Gabor Greif16e02862010-10-01 22:05:14 +0000699static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000700 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000701 Val.setIsSigned(IsSigned);
702}
703
Richard Smith077d0832014-08-04 00:40:48 +0000704/// Check the specified case value is in range for the given unpromoted switch
705/// type.
706static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
707 unsigned UnpromotedWidth, bool UnpromotedSign) {
708 // If the case value was signed and negative and the switch expression is
709 // unsigned, don't bother to warn: this is implementation-defined behavior.
710 // FIXME: Introduce a second, default-ignored warning for this case?
711 if (UnpromotedWidth < Val.getBitWidth()) {
712 llvm::APSInt ConvVal(Val);
713 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
714 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
715 // FIXME: Use different diagnostics for overflow in conversion to promoted
716 // type versus "switch expression cannot have this value". Use proper
717 // IntRange checking rather than just looking at the unpromoted type here.
718 if (ConvVal != Val)
719 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
720 << ConvVal.toString(10);
721 }
722}
723
Alexis Hunt724f14e2014-11-28 00:53:20 +0000724typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
725
Dmitri Gribenko58683752013-12-05 22:52:07 +0000726/// Returns true if we should emit a diagnostic about this case expression not
727/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000728static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000729 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000730 const Expr *CaseExpr,
731 EnumValsTy::iterator &EI,
732 EnumValsTy::iterator &EIEnd,
733 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000734 if (!ED->isClosed())
735 return false;
736
Alexis Hunt724f14e2014-11-28 00:53:20 +0000737 if (const DeclRefExpr *DRE =
738 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000739 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000740 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000741 QualType EnumType = S.Context.getTypeDeclType(ED);
742 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
743 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000744 return false;
745 }
746 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000747
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000748 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000749 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000750
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000751 while (EI != EIEnd && EI->first < Val)
752 EI++;
753
754 if (EI != EIEnd && EI->first == Val)
755 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000756
Dmitri Gribenko58683752013-12-05 22:52:07 +0000757 return true;
758}
759
Gabor Horvath64c32412017-08-09 08:57:09 +0000760static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
761 const Expr *Case) {
762 QualType CondType = GetTypeBeforeIntegralPromotion(Cond);
763 QualType CaseType = Case->getType();
764
765 const EnumType *CondEnumType = CondType->getAs<EnumType>();
766 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
767 if (!CondEnumType || !CaseEnumType)
768 return;
769
Gabor Horvathb57e2642017-08-09 12:34:58 +0000770 // Ignore anonymous enums.
Richard Trieu285c9362017-09-09 00:25:05 +0000771 if (!CondEnumType->getDecl()->getIdentifier() &&
772 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000773 return;
Richard Trieu285c9362017-09-09 00:25:05 +0000774 if (!CaseEnumType->getDecl()->getIdentifier() &&
775 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000776 return;
777
Gabor Horvath64c32412017-08-09 08:57:09 +0000778 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
779 return;
780
Gabor Horvath0284a202017-08-09 20:56:43 +0000781 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000782 << CondType << CaseType << Cond->getSourceRange()
783 << Case->getSourceRange();
784}
785
John McCalldadc5752010-08-24 06:29:42 +0000786StmtResult
John McCallb268a282010-08-23 23:25:46 +0000787Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
788 Stmt *BodyStmt) {
789 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000790 assert(SS == getCurFunction()->SwitchStack.back() &&
791 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000792
David Majnemer418ad3f2014-12-15 07:46:12 +0000793 getCurFunction()->SwitchStack.pop_back();
794
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000795 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000796 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000797
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000798 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000799 if (!CondExpr) return StmtError();
800
801 QualType CondType = CondExpr->getType();
802
Gabor Horvath64c32412017-08-09 08:57:09 +0000803 const Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000804 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000805 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000806
Chris Lattnera96d4272009-10-16 16:45:22 +0000807 // C++ 6.4.2.p2:
808 // Integral promotions are performed (on the switch condition).
809 //
810 // A case value unrepresentable by the original switch condition
811 // type (before the promotion) doesn't make sense, even when it can
812 // be represented by the promoted type. Therefore we need to find
813 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000814 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000815 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000817 // appropriate type now, just return an error.
818 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000819 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000820
Chris Lattner4ebae652010-04-16 23:34:13 +0000821 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000822 // switch(bool_expr) {...} is often a programmer error, e.g.
823 // switch(n && mask) { ... } // Doh - should be "n & mask".
824 // One can always use an if statement instead of switch(bool_expr).
825 Diag(SwitchLoc, diag::warn_bool_switch_condition)
826 << CondExpr->getSourceRange();
827 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000828 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000829
Richard Smith077d0832014-08-04 00:40:48 +0000830 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000831 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000832 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000833 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000834 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
835 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
836
837 // Get the width and signedness that the condition might actually have, for
838 // warning purposes.
839 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
840 // type.
841 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000842 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000843 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000844 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000846 // Accumulate all of the case values in a vector so that we can sort them
847 // and detect duplicates. This vector contains the APInt for the case after
848 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000849 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000850 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000852 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000853 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
854 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000855
Craig Topperc3ec1492014-05-26 06:22:03 +0000856 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000857
Chris Lattner10cb5e52007-08-23 06:23:56 +0000858 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000860 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000861 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000862
Anders Carlsson51873c22007-07-22 07:07:56 +0000863 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000864 if (TheDefaultStmt) {
865 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000866 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000867
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000868 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000869 // we'll return a valid AST. This requires recursing down the AST and
870 // finding it, not something we are set up to do right now. For now,
871 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000872 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000873 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000874 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000875
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000876 } else {
877 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000878
Chris Lattnera65e1f32008-01-16 19:17:22 +0000879 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000880
881 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
882 HasDependentValue = true;
883 break;
884 }
Mike Stump11289f42009-09-09 15:08:12 +0000885
Gabor Horvath64c32412017-08-09 08:57:09 +0000886 checkEnumTypesInSwitchStmt(*this, CondExpr, Lo);
887
Richard Smithf8379a02012-01-18 23:55:52 +0000888 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000889
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000890 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000891 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
892 // constant expression of the promoted type of the switch condition.
893 ExprResult ConvLo =
894 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
895 if (ConvLo.isInvalid()) {
896 CaseListIsErroneous = true;
897 continue;
898 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000899 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000900 } else {
901 // We already verified that the expression has a i-c-e value (C99
902 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000903 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000904
905 // If the LHS is not the same type as the condition, insert an implicit
906 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000907 Lo = DefaultLvalueConversion(Lo).get();
908 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000909 }
910
Richard Smith077d0832014-08-04 00:40:48 +0000911 // Check the unconverted value is within the range of possible values of
912 // the switch expression.
913 checkCaseValue(*this, Lo->getLocStart(), LoVal,
914 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
915
916 // Convert the value to the same width/sign as the condition.
917 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000918
Chris Lattnera65e1f32008-01-16 19:17:22 +0000919 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattner10cb5e52007-08-23 06:23:56 +0000921 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000922 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000923 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000924 CS->getRHS()->isValueDependent()) {
925 HasDependentValue = true;
926 break;
927 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000928 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000929 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000930 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000931 }
932 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000933
934 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000935 // If we don't have a default statement, check whether the
936 // condition is constant.
937 llvm::APSInt ConstantCondValue;
938 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000939 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000940 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
941 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000942 assert(!HasConstantCond ||
943 (ConstantCondValue.getBitWidth() == CondWidth &&
944 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000945 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000946 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000947
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000948 // Sort all the scalar case values so we can easily detect duplicates.
949 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
950
951 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000952 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
953 if (ShouldCheckConstantCond &&
954 CaseVals[i].first == ConstantCondValue)
955 ShouldCheckConstantCond = false;
956
957 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000958 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000959 // First, determine if either case value has a name
960 StringRef PrevString, CurrString;
961 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
962 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
963 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
964 PrevString = DeclRef->getDecl()->getName();
965 }
966 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
967 CurrString = DeclRef->getDecl()->getName();
968 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000969 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000970 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000971
972 if (PrevString == CurrString)
973 Diag(CaseVals[i].second->getLHS()->getLocStart(),
974 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000975 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000976 else
977 Diag(CaseVals[i].second->getLHS()->getLocStart(),
978 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000979 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
980 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000981 CaseValStr;
982
John McCalld3dfbd62010-05-18 03:19:21 +0000983 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000984 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000985 // FIXME: We really want to remove the bogus case stmt from the
986 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000987 CaseListIsErroneous = true;
988 }
989 }
990 }
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 // Detect duplicate case ranges, which usually don't exist at all in
993 // the first place.
994 if (!CaseRanges.empty()) {
995 // Sort all the case ranges by their low value so we can easily detect
996 // overlaps between ranges.
997 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000998
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000999 // Scan the ranges, computing the high values and removing empty ranges.
1000 std::vector<llvm::APSInt> HiVals;
1001 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +00001002 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 CaseStmt *CR = CaseRanges[i].second;
1004 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +00001005 llvm::APSInt HiVal;
1006
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001007 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00001008 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
1009 // constant expression of the promoted type of the switch condition.
1010 ExprResult ConvHi =
1011 CheckConvertedConstantExpression(Hi, CondType, HiVal,
1012 CCEK_CaseValue);
1013 if (ConvHi.isInvalid()) {
1014 CaseListIsErroneous = true;
1015 continue;
1016 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001017 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +00001018 } else {
1019 HiVal = Hi->EvaluateKnownConstInt(Context);
1020
1021 // If the RHS is not the same type as the condition, insert an
1022 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001023 Hi = DefaultLvalueConversion(Hi).get();
1024 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +00001025 }
Mike Stump11289f42009-09-09 15:08:12 +00001026
Richard Smith077d0832014-08-04 00:40:48 +00001027 // Check the unconverted value is within the range of possible values of
1028 // the switch expression.
1029 checkCaseValue(*this, Hi->getLocStart(), HiVal,
1030 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1031
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001032 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001033 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001034
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001035 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +00001036
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001037 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001038 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001039 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
1040 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +00001041 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001042 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001043 --i;
1044 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001045 continue;
1046 }
John McCalld3dfbd62010-05-18 03:19:21 +00001047
1048 if (ShouldCheckConstantCond &&
1049 LoVal <= ConstantCondValue &&
1050 ConstantCondValue <= HiVal)
1051 ShouldCheckConstantCond = false;
1052
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001053 HiVals.push_back(HiVal);
1054 }
Mike Stump11289f42009-09-09 15:08:12 +00001055
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001056 // Rescan the ranges, looking for overlap with singleton values and other
1057 // ranges. Since the range list is sorted, we only need to compare case
1058 // ranges with their neighbors.
1059 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1060 llvm::APSInt &CRLo = CaseRanges[i].first;
1061 llvm::APSInt &CRHi = HiVals[i];
1062 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001063
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001064 // Check to see whether the case range overlaps with any
1065 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001066 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001067 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001068
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001069 // Find the smallest value >= the lower bound. If I is in the
1070 // case range, then we have overlap.
1071 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1072 CaseVals.end(), CRLo,
1073 CaseCompareFunctor());
1074 if (I != CaseVals.end() && I->first < CRHi) {
1075 OverlapVal = I->first; // Found overlap with scalar.
1076 OverlapStmt = I->second;
1077 }
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001079 // Find the smallest value bigger than the upper bound.
1080 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1081 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1082 OverlapVal = (I-1)->first; // Found overlap with scalar.
1083 OverlapStmt = (I-1)->second;
1084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001086 // Check to see if this case stmt overlaps with the subsequent
1087 // case range.
1088 if (i && CRLo <= HiVals[i-1]) {
1089 OverlapVal = HiVals[i-1]; // Found overlap with range.
1090 OverlapStmt = CaseRanges[i-1].second;
1091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001093 if (OverlapStmt) {
1094 // If we have a duplicate, report it.
1095 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1096 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001097 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001098 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001099 // FIXME: We really want to remove the bogus case stmt from the
1100 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001101 CaseListIsErroneous = true;
1102 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001103 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001104 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001105
John McCalld3dfbd62010-05-18 03:19:21 +00001106 // Complain if we have a constant condition and we didn't find a match.
1107 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1108 // TODO: it would be nice if we printed enums as enums, chars as
1109 // chars, etc.
1110 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1111 << ConstantCondValue.toString(10)
1112 << CondExpr->getSourceRange();
1113 }
1114
1115 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001116 // values. We only issue a warning if there is not 'default:', but
1117 // we still do the analysis to preserve this information in the AST
1118 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001119 //
Chris Lattner51679082010-09-16 17:09:42 +00001120 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001121
Douglas Gregorbd6839732010-02-08 22:24:16 +00001122 // If switch has default case, then ignore it.
Alex Lorenz660195f2016-12-08 14:46:05 +00001123 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1124 ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001125 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001126 EnumValsTy EnumVals;
1127
John McCalld3dfbd62010-05-18 03:19:21 +00001128 // Gather all enum values, set their type and sort them,
1129 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001130 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001131 llvm::APSInt Val = EDI->getInitVal();
1132 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001133 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001134 }
1135 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001136 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001137 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001138
1139 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001140 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001141 CI != CaseVals.end(); CI++) {
1142 Expr *CaseExpr = CI->second->getLHS();
1143 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1144 CI->first))
1145 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1146 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001147 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001148
David Blaikiee476f972012-01-22 02:31:55 +00001149 // See which of case ranges aren't in enum
1150 EI = EnumVals.begin();
1151 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001152 RI != CaseRanges.end(); RI++) {
1153 Expr *CaseExpr = RI->second->getLHS();
1154 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1155 RI->first))
1156 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1157 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001158
Chad Rosier02a84392012-08-10 17:56:09 +00001159 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001160 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1161 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001162
1163 CaseExpr = RI->second->getRHS();
1164 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1165 Hi))
1166 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1167 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169
Ted Kremenekc42f3452010-09-09 00:05:53 +00001170 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001171 auto CI = CaseVals.begin();
1172 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001173 bool hasCasesNotInSwitch = false;
1174
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001175 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001176
Alexis Hunt724f14e2014-11-28 00:53:20 +00001177 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001178 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001179 while (CI != CaseVals.end() && CI->first < EI->first)
1180 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Douglas Gregorbd6839732010-02-08 22:24:16 +00001182 if (CI != CaseVals.end() && CI->first == EI->first)
1183 continue;
1184
Ted Kremenekc42f3452010-09-09 00:05:53 +00001185 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001186 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001187 llvm::APSInt Hi =
1188 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001189 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001190 if (EI->first <= Hi)
1191 break;
1192 }
1193
Ted Kremenekc42f3452010-09-09 00:05:53 +00001194 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001195 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001196 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001197 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001200 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001201 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001202
Chris Lattner51679082010-09-16 17:09:42 +00001203 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001204 if (!UnhandledNames.empty()) {
1205 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1206 TheDefaultStmt ? diag::warn_def_missing_case
1207 : diag::warn_missing_case)
1208 << (int)UnhandledNames.size();
1209
1210 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1211 I != E; ++I)
1212 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001213 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001214
1215 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001216 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001217 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001218 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001219
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001220 if (BodyStmt)
1221 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1222 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001223
Mike Stump87c57ac2009-05-16 07:39:55 +00001224 // FIXME: If the case list was broken is some way, we don't have a good system
1225 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001226 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001227 return StmtError();
1228
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001229 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001230}
1231
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001232void
1233Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1234 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001235 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001236 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001237
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001238 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001239 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001240 SrcType->isIntegerType()) {
1241 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1242 SrcExpr->isIntegerConstantExpr(Context)) {
1243 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001244 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001245 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1246
1247 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001248 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001249 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001250
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001251 if (!ED->isClosed())
1252 return;
1253
Alexis Hunt724f14e2014-11-28 00:53:20 +00001254 if (ED->hasAttr<FlagEnumAttr>()) {
1255 if (!IsValueInFlagEnum(ED, RhsVal, true))
1256 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001257 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001258 } else {
1259 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1260 EnumValsTy;
1261 EnumValsTy EnumVals;
1262
1263 // Gather all enum values, set their type and sort them,
1264 // allowing easier comparison with rhs constant.
1265 for (auto *EDI : ED->enumerators()) {
1266 llvm::APSInt Val = EDI->getInitVal();
1267 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1268 EnumVals.push_back(std::make_pair(Val, EDI));
1269 }
1270 if (EnumVals.empty())
1271 return;
1272 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1273 EnumValsTy::iterator EIend =
1274 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1275
1276 // See which values aren't in the enum.
1277 EnumValsTy::const_iterator EI = EnumVals.begin();
1278 while (EI != EIend && EI->first < RhsVal)
1279 EI++;
1280 if (EI == EIend || EI->first != RhsVal) {
1281 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1282 << DstType.getUnqualifiedType();
1283 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001284 }
1285 }
1286 }
1287}
1288
Richard Smith03a4aa32016-06-23 19:02:52 +00001289StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1290 Stmt *Body) {
1291 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001292 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001293
Richard Smith03a4aa32016-06-23 19:02:52 +00001294 auto CondVal = Cond.get();
1295 CheckBreakContinueBinding(CondVal.second);
1296
1297 if (CondVal.second &&
1298 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1299 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001300
John McCallb268a282010-08-23 23:25:46 +00001301 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001302
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001303 if (isa<NullStmt>(Body))
1304 getCurCompoundScope().setHasEmptyLoopBodies();
1305
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001306 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001307 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001308}
1309
John McCalldadc5752010-08-24 06:29:42 +00001310StmtResult
John McCallb268a282010-08-23 23:25:46 +00001311Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001312 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001313 Expr *Cond, SourceLocation CondRParen) {
1314 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001315
Serge Pavlov09f99242014-01-23 15:05:00 +00001316 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001317 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001318 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001319 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001320 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001321
Richard Smith945f8d32013-01-14 22:39:08 +00001322 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001323 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001324 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001325 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001326
John McCallb268a282010-08-23 23:25:46 +00001327 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001328
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001329 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001330}
1331
Richard Trieu451a5db2012-04-30 18:01:30 +00001332namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001333 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1334 using DeclSetVector =
1335 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1336 llvm::SmallPtrSet<VarDecl *, 8>>;
1337
Richard Trieu451a5db2012-04-30 18:01:30 +00001338 // This visitor will traverse a conditional statement and store all
1339 // the evaluated decls into a vector. Simple is set to true if none
1340 // of the excluded constructs are used.
1341 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001342 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001343 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001344 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001345 public:
1346 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001347
Richard Trieu5fb874a2017-06-02 04:24:46 +00001348 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001349 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001350 Inherited(S.Context),
1351 Decls(Decls),
1352 Ranges(Ranges),
1353 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001354
Richard Trieu9d228802013-05-31 22:46:45 +00001355 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001356
Richard Trieu9d228802013-05-31 22:46:45 +00001357 // Replaces the method in EvaluatedExprVisitor.
1358 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001359 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001360 }
1361
1362 // Any Stmt not whitelisted will cause the condition to be marked complex.
1363 void VisitStmt(Stmt *S) {
1364 Simple = false;
1365 }
1366
1367 void VisitBinaryOperator(BinaryOperator *E) {
1368 Visit(E->getLHS());
1369 Visit(E->getRHS());
1370 }
1371
1372 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001373 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001374 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001375
Richard Trieu9d228802013-05-31 22:46:45 +00001376 void VisitUnaryOperator(UnaryOperator *E) {
1377 // Skip checking conditionals with derefernces.
1378 if (E->getOpcode() == UO_Deref)
1379 Simple = false;
1380 else
1381 Visit(E->getSubExpr());
1382 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001383
Richard Trieu9d228802013-05-31 22:46:45 +00001384 void VisitConditionalOperator(ConditionalOperator *E) {
1385 Visit(E->getCond());
1386 Visit(E->getTrueExpr());
1387 Visit(E->getFalseExpr());
1388 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001389
Richard Trieu9d228802013-05-31 22:46:45 +00001390 void VisitParenExpr(ParenExpr *E) {
1391 Visit(E->getSubExpr());
1392 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001393
Richard Trieu9d228802013-05-31 22:46:45 +00001394 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1395 Visit(E->getOpaqueValue()->getSourceExpr());
1396 Visit(E->getFalseExpr());
1397 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001398
Richard Trieu9d228802013-05-31 22:46:45 +00001399 void VisitIntegerLiteral(IntegerLiteral *E) { }
1400 void VisitFloatingLiteral(FloatingLiteral *E) { }
1401 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1402 void VisitCharacterLiteral(CharacterLiteral *E) { }
1403 void VisitGNUNullExpr(GNUNullExpr *E) { }
1404 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001405
Richard Trieu9d228802013-05-31 22:46:45 +00001406 void VisitDeclRefExpr(DeclRefExpr *E) {
1407 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1408 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001409
Richard Trieu9d228802013-05-31 22:46:45 +00001410 Ranges.push_back(E->getSourceRange());
1411
1412 Decls.insert(VD);
1413 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001414
1415 }; // end class DeclExtractor
1416
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001417 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001418 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001419 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001420 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001421 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001422
Richard Trieu9d228802013-05-31 22:46:45 +00001423 public:
1424 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001425
Richard Trieu5fb874a2017-06-02 04:24:46 +00001426 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001427 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1428 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001429
Richard Trieu9d228802013-05-31 22:46:45 +00001430 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001431 }
1432
Richard Trieu9d228802013-05-31 22:46:45 +00001433 void VisitReturnStmt(ReturnStmt *S) {
1434 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001435 }
1436
Richard Trieu9d228802013-05-31 22:46:45 +00001437 void VisitBreakStmt(BreakStmt *S) {
1438 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001439 }
1440
Richard Trieu9d228802013-05-31 22:46:45 +00001441 void VisitGotoStmt(GotoStmt *S) {
1442 FoundDecl = true;
1443 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001444
Richard Trieu9d228802013-05-31 22:46:45 +00001445 void VisitCastExpr(CastExpr *E) {
1446 if (E->getCastKind() == CK_LValueToRValue)
1447 CheckLValueToRValueCast(E->getSubExpr());
1448 else
1449 Visit(E->getSubExpr());
1450 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001451
Richard Trieu9d228802013-05-31 22:46:45 +00001452 void CheckLValueToRValueCast(Expr *E) {
1453 E = E->IgnoreParenImpCasts();
1454
1455 if (isa<DeclRefExpr>(E)) {
1456 return;
1457 }
1458
1459 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1460 Visit(CO->getCond());
1461 CheckLValueToRValueCast(CO->getTrueExpr());
1462 CheckLValueToRValueCast(CO->getFalseExpr());
1463 return;
1464 }
1465
1466 if (BinaryConditionalOperator *BCO =
1467 dyn_cast<BinaryConditionalOperator>(E)) {
1468 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1469 CheckLValueToRValueCast(BCO->getFalseExpr());
1470 return;
1471 }
1472
1473 Visit(E);
1474 }
1475
1476 void VisitDeclRefExpr(DeclRefExpr *E) {
1477 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1478 if (Decls.count(VD))
1479 FoundDecl = true;
1480 }
1481
Steven Wu92910f62016-03-10 02:02:48 +00001482 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1483 // Only need to visit the semantics for POE.
1484 // SyntaticForm doesn't really use the Decal.
1485 for (auto *S : POE->semantics()) {
1486 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1487 // Look past the OVE into the expression it binds.
1488 Visit(OVE->getSourceExpr());
1489 else
1490 Visit(S);
1491 }
1492 }
1493
Richard Trieu9d228802013-05-31 22:46:45 +00001494 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001495
1496 }; // end class DeclMatcher
1497
1498 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1499 Expr *Third, Stmt *Body) {
1500 // Condition is empty
1501 if (!Second) return;
1502
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001503 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1504 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001505 return;
1506
1507 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001508 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001509 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001510 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001511 DE.Visit(Second);
1512
1513 // Don't analyze complex conditionals.
1514 if (!DE.isSimple()) return;
1515
1516 // No decls found.
1517 if (Decls.size() == 0) return;
1518
Richard Trieu0030f1d2012-05-04 03:01:54 +00001519 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001520 for (auto *VD : Decls)
1521 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1522 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001523
1524 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1525 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1526 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1527 return;
1528
1529 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001530 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001531 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001532 } else {
1533 PDiag << (unsigned)Decls.size();
1534 for (auto *VD : Decls)
1535 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001536 }
1537
Richard Trieu5fb874a2017-06-02 04:24:46 +00001538 for (auto Range : Ranges)
1539 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001540
1541 S.Diag(Ranges.begin()->getBegin(), PDiag);
1542 }
1543
Richard Trieu4e7c9622013-08-06 21:31:54 +00001544 // If Statement is an incemement or decrement, return true and sets the
1545 // variables Increment and DRE.
1546 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1547 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001548 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1549 if (!Cleanups->cleanupsHaveSideEffects())
1550 Statement = Cleanups->getSubExpr();
1551
Richard Trieu4e7c9622013-08-06 21:31:54 +00001552 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1553 switch (UO->getOpcode()) {
1554 default: return false;
1555 case UO_PostInc:
1556 case UO_PreInc:
1557 Increment = true;
1558 break;
1559 case UO_PostDec:
1560 case UO_PreDec:
1561 Increment = false;
1562 break;
1563 }
1564 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1565 return DRE;
1566 }
1567
1568 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1569 FunctionDecl *FD = Call->getDirectCallee();
1570 if (!FD || !FD->isOverloadedOperator()) return false;
1571 switch (FD->getOverloadedOperator()) {
1572 default: return false;
1573 case OO_PlusPlus:
1574 Increment = true;
1575 break;
1576 case OO_MinusMinus:
1577 Increment = false;
1578 break;
1579 }
1580 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1581 return DRE;
1582 }
1583
1584 return false;
1585 }
1586
Serge Pavlov09f99242014-01-23 15:05:00 +00001587 // A visitor to determine if a continue or break statement is a
1588 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001589 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001590 SourceLocation BreakLoc;
1591 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001592 bool InSwitch = false;
1593
Richard Trieu4e7c9622013-08-06 21:31:54 +00001594 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001595 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001596 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001597 Visit(Body);
1598 }
1599
Eli Friedmane91b2e62017-07-04 00:52:24 +00001600 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001601
Eli Friedmane91b2e62017-07-04 00:52:24 +00001602 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001603 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001604 }
1605
Eli Friedmane91b2e62017-07-04 00:52:24 +00001606 void VisitBreakStmt(const BreakStmt* E) {
1607 if (!InSwitch)
1608 BreakLoc = E->getBreakLoc();
1609 }
1610
1611 void VisitSwitchStmt(const SwitchStmt* S) {
1612 if (const Stmt *Init = S->getInit())
1613 Visit(Init);
1614 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1615 Visit(CondVar);
1616 if (const Stmt *Cond = S->getCond())
1617 Visit(Cond);
1618
1619 // Don't return break statements from the body of a switch.
1620 InSwitch = true;
1621 if (const Stmt *Body = S->getBody())
1622 Visit(Body);
1623 InSwitch = false;
1624 }
1625
1626 void VisitForStmt(const ForStmt *S) {
1627 // Only visit the init statement of a for loop; the body
1628 // has a different break/continue scope.
1629 if (const Stmt *Init = S->getInit())
1630 Visit(Init);
1631 }
1632
1633 void VisitWhileStmt(const WhileStmt *) {
1634 // Do nothing; the children of a while loop have a different
1635 // break/continue scope.
1636 }
1637
1638 void VisitDoStmt(const DoStmt *) {
1639 // Do nothing; the children of a while loop have a different
1640 // break/continue scope.
1641 }
1642
1643 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1644 // Only visit the initialization of a for loop; the body
1645 // has a different break/continue scope.
1646 if (const Stmt *Range = S->getRangeStmt())
1647 Visit(Range);
1648 if (const Stmt *Begin = S->getBeginStmt())
1649 Visit(Begin);
1650 if (const Stmt *End = S->getEndStmt())
1651 Visit(End);
1652 }
1653
1654 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1655 // Only visit the initialization of a for loop; the body
1656 // has a different break/continue scope.
1657 if (const Stmt *Element = S->getElement())
1658 Visit(Element);
1659 if (const Stmt *Collection = S->getCollection())
1660 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001661 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001662
Serge Pavlov09f99242014-01-23 15:05:00 +00001663 bool ContinueFound() { return ContinueLoc.isValid(); }
1664 bool BreakFound() { return BreakLoc.isValid(); }
1665 SourceLocation GetContinueLoc() { return ContinueLoc; }
1666 SourceLocation GetBreakLoc() { return BreakLoc; }
1667
1668 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001669
1670 // Emit a warning when a loop increment/decrement appears twice per loop
1671 // iteration. The conditions which trigger this warning are:
1672 // 1) The last statement in the loop body and the third expression in the
1673 // for loop are both increment or both decrement of the same variable
1674 // 2) No continue statements in the loop body.
1675 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1676 // Return when there is nothing to check.
1677 if (!Body || !Third) return;
1678
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001679 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1680 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001681 return;
1682
1683 // Get the last statement from the loop body.
1684 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1685 if (!CS || CS->body_empty()) return;
1686 Stmt *LastStmt = CS->body_back();
1687 if (!LastStmt) return;
1688
1689 bool LoopIncrement, LastIncrement;
1690 DeclRefExpr *LoopDRE, *LastDRE;
1691
1692 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1693 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1694
1695 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001696 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001697 if (LoopIncrement != LastIncrement ||
1698 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1699
Serge Pavlov09f99242014-01-23 15:05:00 +00001700 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001701
1702 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1703 << LastDRE->getDecl() << LastIncrement;
1704 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1705 << LoopIncrement;
1706 }
1707
Richard Trieu451a5db2012-04-30 18:01:30 +00001708} // end namespace
1709
Serge Pavlov09f99242014-01-23 15:05:00 +00001710
1711void Sema::CheckBreakContinueBinding(Expr *E) {
1712 if (!E || getLangOpts().CPlusPlus)
1713 return;
1714 BreakContinueFinder BCFinder(*this, E);
1715 Scope *BreakParent = CurScope->getBreakParent();
1716 if (BCFinder.BreakFound() && BreakParent) {
1717 if (BreakParent->getFlags() & Scope::SwitchScope) {
1718 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1719 } else {
1720 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1721 << "break";
1722 }
1723 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1724 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1725 << "continue";
1726 }
1727}
1728
Richard Smith03a4aa32016-06-23 19:02:52 +00001729StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1730 Stmt *First, ConditionResult Second,
1731 FullExprArg third, SourceLocation RParenLoc,
1732 Stmt *Body) {
1733 if (Second.isInvalid())
1734 return StmtError();
1735
David Blaikiebbafb8a2012-03-11 07:00:24 +00001736 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001737 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001738 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1739 // declare identifiers for objects having storage class 'auto' or
1740 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001741 for (auto *DI : DS->decls()) {
1742 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001743 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001744 VD = nullptr;
1745 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001746 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1747 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001748 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001749 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001750 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001751 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001752
Richard Smith03a4aa32016-06-23 19:02:52 +00001753 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001754 CheckBreakContinueBinding(third.get());
1755
Richard Smith03a4aa32016-06-23 19:02:52 +00001756 if (!Second.get().first)
1757 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1758 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001759 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001760
Richard Smith03a4aa32016-06-23 19:02:52 +00001761 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001762 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001763 Second.get().second->getExprLoc()))
1764 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001765
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001766 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001767
Anders Carlsson1682af52009-08-01 01:39:59 +00001768 DiagnoseUnusedExprResult(First);
1769 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001770 DiagnoseUnusedExprResult(Body);
1771
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001772 if (isa<NullStmt>(Body))
1773 getCurCompoundScope().setHasEmptyLoopBodies();
1774
Richard Smith03a4aa32016-06-23 19:02:52 +00001775 return new (Context)
1776 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1777 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001778}
1779
John McCall34376a62010-12-04 03:47:34 +00001780/// In an Objective C collection iteration statement:
1781/// for (x in y)
1782/// x can be an arbitrary l-value expression. Bind it up as a
1783/// full-expression.
1784StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001785 // Reduce placeholder expressions here. Note that this rejects the
1786 // use of pseudo-object l-values in this position.
1787 ExprResult result = CheckPlaceholderExpr(E);
1788 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001789 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001790
Richard Smith945f8d32013-01-14 22:39:08 +00001791 ExprResult FullExpr = ActOnFinishFullExpr(E);
1792 if (FullExpr.isInvalid())
1793 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001794 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001795}
1796
John McCall53848232011-07-27 01:07:15 +00001797ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001798Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1799 if (!collection)
1800 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001801
Kaelyn Takata15867822014-11-21 18:48:04 +00001802 ExprResult result = CorrectDelayedTyposInExpr(collection);
1803 if (!result.isUsable())
1804 return ExprError();
1805 collection = result.get();
1806
John McCall53848232011-07-27 01:07:15 +00001807 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001808 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001809
1810 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001811 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001812 if (result.isInvalid())
1813 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001814 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001815
1816 // The operand needs to have object-pointer type.
1817 // TODO: should we do a contextual conversion?
1818 const ObjCObjectPointerType *pointerType =
1819 collection->getType()->getAs<ObjCObjectPointerType>();
1820 if (!pointerType)
1821 return Diag(forLoc, diag::err_collection_expr_type)
1822 << collection->getType() << collection->getSourceRange();
1823
1824 // Check that the operand provides
1825 // - countByEnumeratingWithState:objects:count:
1826 const ObjCObjectType *objectType = pointerType->getObjectType();
1827 ObjCInterfaceDecl *iface = objectType->getInterface();
1828
1829 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001830 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001831 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001832 (getLangOpts().ObjCAutoRefCount
1833 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1834 diag::err_arc_collection_forward, collection)
1835 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001836 // Otherwise, if we have any useful type information, check that
1837 // the type declares the appropriate method.
1838 } else if (iface || !objectType->qual_empty()) {
1839 IdentifierInfo *selectorIdents[] = {
1840 &Context.Idents.get("countByEnumeratingWithState"),
1841 &Context.Idents.get("objects"),
1842 &Context.Idents.get("count")
1843 };
1844 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1845
Craig Topperc3ec1492014-05-26 06:22:03 +00001846 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001847
1848 // If there's an interface, look in both the public and private APIs.
1849 if (iface) {
1850 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001851 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001852 }
1853
1854 // Also check protocol qualifiers.
1855 if (!method)
1856 method = LookupMethodInQualifiedType(selector, pointerType,
1857 /*instance*/ true);
1858
1859 // If we didn't find it anywhere, give up.
1860 if (!method) {
1861 Diag(forLoc, diag::warn_collection_expr_type)
1862 << collection->getType() << selector << collection->getSourceRange();
1863 }
1864
1865 // TODO: check for an incompatible signature?
1866 }
1867
1868 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001869 return collection;
John McCall53848232011-07-27 01:07:15 +00001870}
1871
John McCalldadc5752010-08-24 06:29:42 +00001872StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001873Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001874 Stmt *First, Expr *collection,
1875 SourceLocation RParenLoc) {
Reid Kleckner87a31802018-03-12 21:43:02 +00001876 setFunctionHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001877
1878 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001879 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001880
Fariborz Jahanian93977672008-01-10 20:33:58 +00001881 if (First) {
1882 QualType FirstType;
1883 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001884 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001885 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1886 diag::err_toomany_element_decls));
1887
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001888 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1889 if (!D || D->isInvalidDecl())
1890 return StmtError();
1891
John McCall31168b02011-06-15 23:02:42 +00001892 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001893 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1894 // declare identifiers for objects having storage class 'auto' or
1895 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001896 if (!D->hasLocalStorage())
1897 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001898 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001899
1900 // If the type contained 'auto', deduce the 'auto' to 'id'.
1901 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001902 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1903 VK_RValue);
1904 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001905 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1906 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001907 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001908 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001909 D->setInvalidDecl();
1910 return StmtError();
1911 }
1912
Richard Smith061f1e22013-04-30 21:23:01 +00001913 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001914
Richard Smith51ec0cf2017-02-21 01:17:38 +00001915 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001916 SourceLocation Loc =
1917 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001918 Diag(Loc, diag::warn_auto_var_is_id)
1919 << D->getDeclName();
1920 }
1921 }
1922
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001923 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001924 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001925 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001926 return StmtError(Diag(First->getLocStart(),
1927 diag::err_selector_element_not_lvalue)
1928 << First->getSourceRange());
1929
Mike Stump11289f42009-09-09 15:08:12 +00001930 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001931 if (FirstType.isConstQualified())
1932 Diag(ForLoc, diag::err_selector_element_const_type)
1933 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001934 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001935 if (!FirstType->isDependentType() &&
1936 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001937 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001938 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1939 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001940 }
Chad Rosier02a84392012-08-10 17:56:09 +00001941
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001942 if (CollectionExprResult.isInvalid())
1943 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001944
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001945 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001946 if (CollectionExprResult.isInvalid())
1947 return StmtError();
1948
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001949 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1950 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001951}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001952
Richard Smith02e85f32011-04-14 22:09:26 +00001953/// Finish building a variable declaration for a for-range statement.
1954/// \return true if an error occurs.
1955static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001956 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001957 if (Decl->getType()->isUndeducedType()) {
1958 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1959 if (!Res.isUsable()) {
1960 Decl->setInvalidDecl();
1961 return true;
1962 }
1963 Init = Res.get();
1964 }
1965
Richard Smith02e85f32011-04-14 22:09:26 +00001966 // Deduce the type for the iterator variable now rather than leaving it to
1967 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001968 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001969 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001970 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001971 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001972 SemaRef.Diag(Loc, DiagID) << Init->getType();
1973 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001974 Decl->setInvalidDecl();
1975 return true;
1976 }
Richard Smith061f1e22013-04-30 21:23:01 +00001977 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001978
John McCall31168b02011-06-15 23:02:42 +00001979 // In ARC, infer lifetime.
1980 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1981 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001982 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001983 SemaRef.inferObjCARCLifetime(Decl))
1984 Decl->setInvalidDecl();
1985
Richard Smith3beb7c62017-01-12 02:27:38 +00001986 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001987 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001988 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001989 return false;
1990}
1991
Sam Panzer0f384432012-08-21 00:52:01 +00001992namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001993// An enum to represent whether something is dealing with a call to begin()
1994// or a call to end() in a range-based for loop.
1995enum BeginEndFunction {
1996 BEF_begin,
1997 BEF_end
1998};
Sam Panzer0f384432012-08-21 00:52:01 +00001999
Richard Smith02e85f32011-04-14 22:09:26 +00002000/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00002001/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00002002/// nor from the diagnostics produced when analysing the implicit expressions
2003/// required in a for-range statement.
2004void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00002005 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00002006 CallExpr *CE = dyn_cast<CallExpr>(E);
2007 if (!CE)
2008 return;
2009 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2010 if (!D)
2011 return;
2012 SourceLocation Loc = D->getLocation();
2013
2014 std::string Description;
2015 bool IsTemplate = false;
2016 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2017 Description = SemaRef.getTemplateArgumentBindingsText(
2018 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2019 IsTemplate = true;
2020 }
2021
2022 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2023 << BEF << IsTemplate << Description << E->getType();
2024}
2025
Sam Panzer0f384432012-08-21 00:52:01 +00002026/// Build a variable declaration for a for-range statement.
2027VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
Matt Davisb8402ef2018-02-14 21:22:11 +00002028 QualType Type, StringRef Name) {
Sam Panzer0f384432012-08-21 00:52:01 +00002029 DeclContext *DC = SemaRef.CurContext;
2030 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2031 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2032 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002033 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00002034 Decl->setImplicit();
2035 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00002036}
2037
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002038}
Richard Smith02e85f32011-04-14 22:09:26 +00002039
Fariborz Jahanian00213472012-07-06 19:04:04 +00002040static bool ObjCEnumerationCollection(Expr *Collection) {
2041 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00002042 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00002043}
2044
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002045/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002046///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002047/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00002048/// A range-based for statement is equivalent to
2049///
2050/// {
2051/// auto && __range = range-init;
2052/// for ( auto __begin = begin-expr,
2053/// __end = end-expr;
2054/// __begin != __end;
2055/// ++__begin ) {
2056/// for-range-declaration = *__begin;
2057/// statement
2058/// }
2059/// }
2060///
2061/// The body of the loop is not available yet, since it cannot be analysed until
2062/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00002063StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2064 SourceLocation CoawaitLoc, Stmt *First,
2065 SourceLocation ColonLoc, Expr *Range,
2066 SourceLocation RParenLoc,
2067 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00002068 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00002069 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002070
Richard Smith3249fed2013-08-21 01:40:36 +00002071 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002072 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002073
2074 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2075 assert(DS && "first part of for range not a decl stmt");
2076
2077 if (!DS->isSingleDecl()) {
2078 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
2079 return StmtError();
2080 }
Richard Smith02e85f32011-04-14 22:09:26 +00002081
Richard Smith3249fed2013-08-21 01:40:36 +00002082 Decl *LoopVar = DS->getSingleDecl();
2083 if (LoopVar->isInvalidDecl() || !Range ||
2084 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2085 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002086 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002087 }
Richard Smith02e85f32011-04-14 22:09:26 +00002088
Eric Fiselierb936a392017-06-14 03:24:55 +00002089 // Build the coroutine state immediately and not later during template
2090 // instantiation
2091 if (!CoawaitLoc.isInvalid()) {
2092 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2093 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002094 }
2095
Richard Smith02e85f32011-04-14 22:09:26 +00002096 // Build auto && __range = range-init
Matt Davisb8402ef2018-02-14 21:22:11 +00002097 // Divide by 2, since the variables are in the inner scope (loop body).
2098 const auto DepthStr = std::to_string(S->getDepth() / 2);
Richard Smith02e85f32011-04-14 22:09:26 +00002099 SourceLocation RangeLoc = Range->getLocStart();
2100 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2101 Context.getAutoRRefDeductType(),
Matt Davisb8402ef2018-02-14 21:22:11 +00002102 std::string("__range") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002103 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002104 diag::err_for_range_deduction_failure)) {
2105 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002106 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002107 }
Richard Smith02e85f32011-04-14 22:09:26 +00002108
2109 // Claim the type doesn't contain auto: we've already done the checking.
2110 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002111 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002112 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002113 if (RangeDecl.isInvalid()) {
2114 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002115 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002116 }
Richard Smith02e85f32011-04-14 22:09:26 +00002117
Richard Smithcfd53b42015-10-22 06:13:50 +00002118 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002119 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2120 /*Cond=*/nullptr, /*Inc=*/nullptr,
2121 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002122}
2123
2124/// \brief Create the initialization, compare, and increment steps for
2125/// the range-based for loop expression.
2126/// This function does not handle array-based for loops,
2127/// which are created in Sema::BuildCXXForRangeStmt.
2128///
2129/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2130/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2131/// CandidateSet and BEF are set and some non-success value is returned on
2132/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002133static Sema::ForRangeStatus
2134BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2135 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2136 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2137 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2138 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002139 DeclarationNameInfo BeginNameInfo(
2140 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2141 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2142 ColonLoc);
2143
2144 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2145 Sema::LookupMemberName);
2146 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2147
2148 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2149 // - if _RangeT is a class type, the unqualified-ids begin and end are
2150 // looked up in the scope of class _RangeT as if by class member access
2151 // lookup (3.4.5), and if either (or both) finds at least one
2152 // declaration, begin-expr and end-expr are __range.begin() and
2153 // __range.end(), respectively;
2154 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2155 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2156
2157 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2158 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002159 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002160
2161 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2162 << RangeLoc << BeginRange->getType() << *BEF;
2163 return Sema::FRS_DiagnosticIssued;
2164 }
2165 } else {
2166 // - otherwise, begin-expr and end-expr are begin(__range) and
2167 // end(__range), respectively, where begin and end are looked up with
2168 // argument-dependent lookup (3.4.2). For the purposes of this name
2169 // lookup, namespace std is an associated namespace.
2170
2171 }
2172
Richard Smith9f690bd2015-10-27 06:02:45 +00002173 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002174 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002175 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002176 BeginMemberLookup, CandidateSet,
2177 BeginRange, BeginExpr);
2178
Richard Smith9f690bd2015-10-27 06:02:45 +00002179 if (RangeStatus != Sema::FRS_Success) {
2180 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2181 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2182 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002183 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002184 }
Eric Fiselierb936a392017-06-14 03:24:55 +00002185 if (!CoawaitLoc.isInvalid()) {
2186 // FIXME: getCurScope() should not be used during template instantiation.
2187 // We should pick up the set of unqualified lookup results for operator
2188 // co_await during the initial parse.
2189 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2190 BeginExpr->get());
2191 if (BeginExpr->isInvalid())
2192 return Sema::FRS_DiagnosticIssued;
2193 }
Sam Panzer0f384432012-08-21 00:52:01 +00002194 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2195 diag::err_for_range_iter_deduction_failure)) {
2196 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2197 return Sema::FRS_DiagnosticIssued;
2198 }
2199
Richard Smith9f690bd2015-10-27 06:02:45 +00002200 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002201 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002202 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002203 EndMemberLookup, CandidateSet,
2204 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002205 if (RangeStatus != Sema::FRS_Success) {
2206 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2207 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2208 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002209 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002210 }
Sam Panzer0f384432012-08-21 00:52:01 +00002211 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2212 diag::err_for_range_iter_deduction_failure)) {
2213 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2214 return Sema::FRS_DiagnosticIssued;
2215 }
2216 return Sema::FRS_Success;
2217}
2218
2219/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002220/// If the attempt fails, this function will return a valid, null StmtResult
2221/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002222static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2223 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002224 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002225 Stmt *LoopVarDecl,
2226 SourceLocation ColonLoc,
2227 Expr *Range,
2228 SourceLocation RangeLoc,
2229 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002230 // Determine whether we can rebuild the for-range statement with a
2231 // dereferenced range expression.
2232 ExprResult AdjustedRange;
2233 {
2234 Sema::SFINAETrap Trap(SemaRef);
2235
2236 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2237 if (AdjustedRange.isInvalid())
2238 return StmtResult();
2239
Richard Smith9f690bd2015-10-27 06:02:45 +00002240 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2241 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2242 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002243 if (SR.isInvalid())
2244 return StmtResult();
2245 }
2246
2247 // The attempt to dereference worked well enough that it could produce a valid
2248 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2249 // case there are any other (non-fatal) problems with it.
2250 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2251 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002252 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2253 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002254 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002255}
2256
Richard Smith3249fed2013-08-21 01:40:36 +00002257namespace {
2258/// RAII object to automatically invalidate a declaration if an error occurs.
2259struct InvalidateOnErrorScope {
2260 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2261 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2262 ~InvalidateOnErrorScope() {
2263 if (Enabled && Trap.hasErrorOccurred())
2264 D->setInvalidDecl();
2265 }
2266
2267 DiagnosticErrorTrap Trap;
2268 Decl *D;
2269 bool Enabled;
2270};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002271}
Richard Smith3249fed2013-08-21 01:40:36 +00002272
Richard Smitha05b3b52012-09-20 21:52:32 +00002273/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002274StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002275Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002276 SourceLocation ColonLoc, Stmt *RangeDecl,
2277 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002278 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002279 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002280 // FIXME: This should not be used during template instantiation. We should
2281 // pick up the set of unqualified lookup results for the != and + operators
2282 // in the initial parse.
2283 //
2284 // Testcase (accepts-invalid):
2285 // template<typename T> void f() { for (auto x : T()) {} }
2286 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2287 // bool operator!=(N::X, N::X); void operator++(N::X);
2288 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002289 Scope *S = getCurScope();
2290
2291 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2292 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2293 QualType RangeVarType = RangeVar->getType();
2294
2295 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2296 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2297
Richard Smith3249fed2013-08-21 01:40:36 +00002298 // If we hit any errors, mark the loop variable as invalid if its type
2299 // contains 'auto'.
2300 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2301 LoopVar->getType()->isUndeducedType());
2302
Richard Smith01694c32016-03-20 10:33:40 +00002303 StmtResult BeginDeclStmt = Begin;
2304 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002305 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2306
Richard Smith27d807c2013-04-30 13:56:41 +00002307 if (RangeVarType->isDependentType()) {
2308 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002309 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002310
2311 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2312 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002313 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2314 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2315 for (auto *Binding : DD->bindings())
2316 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002317 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002318 }
Richard Smith01694c32016-03-20 10:33:40 +00002319 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002320 SourceLocation RangeLoc = RangeVar->getLocation();
2321
Ted Kremenekbed648e2011-10-10 22:36:28 +00002322 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2323
2324 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2325 VK_LValue, ColonLoc);
2326 if (BeginRangeRef.isInvalid())
2327 return StmtError();
2328
2329 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2330 VK_LValue, ColonLoc);
2331 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002332 return StmtError();
2333
2334 QualType AutoType = Context.getAutoDeductType();
2335 Expr *Range = RangeVar->getInit();
2336 if (!Range)
2337 return StmtError();
2338 QualType RangeType = Range->getType();
2339
2340 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002341 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002342 return StmtError();
2343
2344 // Build auto __begin = begin-expr, __end = end-expr.
Matt Davisb8402ef2018-02-14 21:22:11 +00002345 // Divide by 2, since the variables are in the inner scope (loop body).
2346 const auto DepthStr = std::to_string(S->getDepth() / 2);
Richard Smith02e85f32011-04-14 22:09:26 +00002347 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002348 std::string("__begin") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002349 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002350 std::string("__end") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002351
2352 // Build begin-expr and end-expr and attach to __begin and __end variables.
2353 ExprResult BeginExpr, EndExpr;
2354 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2355 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2356 // __range + __bound, respectively, where __bound is the array bound. If
2357 // _RangeT is an array of unknown size or an array of incomplete type,
2358 // the program is ill-formed;
2359
2360 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002361 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002362 if (!CoawaitLoc.isInvalid()) {
2363 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2364 if (BeginExpr.isInvalid())
2365 return StmtError();
2366 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002367 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002368 diag::err_for_range_iter_deduction_failure)) {
2369 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2370 return StmtError();
2371 }
2372
2373 // Find the array bound.
2374 ExprResult BoundExpr;
2375 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002376 BoundExpr = IntegerLiteral::Create(
2377 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002378 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002379 dyn_cast<VariableArrayType>(UnqAT)) {
2380 // For a variably modified type we can't just use the expression within
2381 // the array bounds, since we don't want that to be re-evaluated here.
2382 // Rather, we need to determine what it was when the array was first
2383 // created - so we resort to using sizeof(vla)/sizeof(element).
2384 // For e.g.
2385 // void f(int b) {
2386 // int vla[b];
2387 // b = -1; <-- This should not affect the num of iterations below
2388 // for (int &c : vla) { .. }
2389 // }
2390
2391 // FIXME: This results in codegen generating IR that recalculates the
2392 // run-time number of elements (as opposed to just using the IR Value
2393 // that corresponds to the run-time value of each bound that was
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002394 // generated when the array was created.) If this proves too embarrassing
Faisal Vali1ca2d962017-05-15 01:49:19 +00002395 // even for unoptimized IR, consider passing a magic-value/cookie to
2396 // codegen that then knows to simply use that initial llvm::Value (that
2397 // corresponds to the bound at time of array creation) within
2398 // getelementptr. But be prepared to pay the price of increasing a
2399 // customized form of coupling between the two components - which could
2400 // be hard to maintain as the codebase evolves.
2401
2402 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2403 EndVar->getLocation(), UETT_SizeOf,
2404 /*isType=*/true,
2405 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2406 VAT->desugar(), RangeLoc))
2407 .getAsOpaquePtr(),
2408 EndVar->getSourceRange());
2409 if (SizeOfVLAExprR.isInvalid())
2410 return StmtError();
2411
2412 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2413 EndVar->getLocation(), UETT_SizeOf,
2414 /*isType=*/true,
2415 CreateParsedType(VAT->desugar(),
2416 Context.getTrivialTypeSourceInfo(
2417 VAT->getElementType(), RangeLoc))
2418 .getAsOpaquePtr(),
2419 EndVar->getSourceRange());
2420 if (SizeOfEachElementExprR.isInvalid())
2421 return StmtError();
2422
2423 BoundExpr =
2424 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2425 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2426 if (BoundExpr.isInvalid())
2427 return StmtError();
2428
2429 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002430 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2431 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002432 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002433 }
2434
2435 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002436 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002437 BoundExpr.get());
2438 if (EndExpr.isInvalid())
2439 return StmtError();
2440 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2441 diag::err_for_range_iter_deduction_failure)) {
2442 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2443 return StmtError();
2444 }
2445 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002446 OverloadCandidateSet CandidateSet(RangeLoc,
2447 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002448 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002449 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2450 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2451 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2452 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002453
Richard Smitha05b3b52012-09-20 21:52:32 +00002454 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002455 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002456 // If the range is being built from an array parameter, emit a
2457 // a diagnostic that it is being treated as a pointer.
2458 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2459 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2460 QualType ArrayTy = PVD->getOriginalType();
2461 QualType PointerTy = PVD->getType();
2462 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2463 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2464 << RangeLoc << PVD << ArrayTy << PointerTy;
2465 Diag(PVD->getLocation(), diag::note_declared_at);
2466 return StmtError();
2467 }
2468 }
2469 }
2470
2471 // If building the range failed, try dereferencing the range expression
2472 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002473 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002474 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002475 LoopVarDecl, ColonLoc,
2476 Range, RangeLoc,
2477 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002478 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002479 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002480 }
2481
Sam Panzer0f384432012-08-21 00:52:01 +00002482 // Otherwise, emit diagnostics if we haven't already.
2483 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002484 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002485 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2486 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002487 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002488 }
2489 // Return an error if no fix was discovered.
2490 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002491 return StmtError();
2492 }
2493
Sam Panzer0f384432012-08-21 00:52:01 +00002494 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2495 "invalid range expression in for loop");
2496
2497 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002498 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002499 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2500 if (!Context.hasSameType(BeginType, EndType)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002501 Diag(RangeLoc, getLangOpts().CPlusPlus17
Richard Smith01694c32016-03-20 10:33:40 +00002502 ? diag::warn_for_range_begin_end_types_differ
2503 : diag::ext_for_range_begin_end_types_differ)
2504 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002505 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2506 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2507 }
2508
Richard Smith01694c32016-03-20 10:33:40 +00002509 BeginDeclStmt =
2510 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2511 EndDeclStmt =
2512 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002513
Ted Kremenekbed648e2011-10-10 22:36:28 +00002514 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2515 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002516 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002517 if (BeginRef.isInvalid())
2518 return StmtError();
2519
Richard Smith02e85f32011-04-14 22:09:26 +00002520 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2521 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002522 if (EndRef.isInvalid())
2523 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002524
2525 // Build and check __begin != __end expression.
2526 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2527 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002528 if (!NotEqExpr.isInvalid())
2529 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2530 if (!NotEqExpr.isInvalid())
2531 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002532 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002533 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2534 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002535 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2536 if (!Context.hasSameType(BeginType, EndType))
2537 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2538 return StmtError();
2539 }
2540
2541 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002542 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2543 VK_LValue, ColonLoc);
2544 if (BeginRef.isInvalid())
2545 return StmtError();
2546
Richard Smith02e85f32011-04-14 22:09:26 +00002547 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002548 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002549 // FIXME: getCurScope() should not be used during template instantiation.
2550 // We should pick up the set of unqualified lookup results for operator
2551 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002552 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002553 if (!IncrExpr.isInvalid())
2554 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002555 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002556 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2557 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002558 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2559 return StmtError();
2560 }
2561
2562 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002563 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2564 VK_LValue, ColonLoc);
2565 if (BeginRef.isInvalid())
2566 return StmtError();
2567
Richard Smith02e85f32011-04-14 22:09:26 +00002568 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2569 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002570 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2571 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002572 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2573 return StmtError();
2574 }
2575
Richard Smitha05b3b52012-09-20 21:52:32 +00002576 // Attach *__begin as initializer for VD. Don't touch it if we're just
2577 // trying to determine whether this would be a valid range.
2578 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002579 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002580 if (LoopVar->isInvalidDecl())
2581 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2582 }
2583 }
2584
Richard Smitha05b3b52012-09-20 21:52:32 +00002585 // Don't bother to actually allocate the result if we're just trying to
2586 // determine whether it would be valid.
2587 if (Kind == BFRK_Check)
2588 return StmtResult();
2589
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002590 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002591 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2592 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002593 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2594 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002595}
2596
Chad Rosier02a84392012-08-10 17:56:09 +00002597/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002598/// statement.
2599StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2600 if (!S || !B)
2601 return StmtError();
2602 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002603
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002604 ForStmt->setBody(B);
2605 return S;
2606}
2607
Richard Trieu3e1d4832015-04-13 22:08:55 +00002608// Warn when the loop variable is a const reference that creates a copy.
2609// Suggest using the non-reference type for copies. If a copy can be prevented
2610// suggest the const reference type that would do so.
2611// For instance, given "for (const &Foo : Range)", suggest
2612// "for (const Foo : Range)" to denote a copy is made for the loop. If
2613// possible, also suggest "for (const &Bar : Range)" if this type prevents
2614// the copy altogether.
2615static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2616 const VarDecl *VD,
2617 QualType RangeInitType) {
2618 const Expr *InitExpr = VD->getInit();
2619 if (!InitExpr)
2620 return;
2621
2622 QualType VariableType = VD->getType();
2623
Tim Shen4a05bb82016-06-21 20:29:17 +00002624 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2625 if (!Cleanups->cleanupsHaveSideEffects())
2626 InitExpr = Cleanups->getSubExpr();
2627
Richard Trieu3e1d4832015-04-13 22:08:55 +00002628 const MaterializeTemporaryExpr *MTE =
2629 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2630
2631 // No copy made.
2632 if (!MTE)
2633 return;
2634
2635 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2636
2637 // Searching for either UnaryOperator for dereference of a pointer or
2638 // CXXOperatorCallExpr for handling iterators.
2639 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2640 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2641 E = CCE->getArg(0);
2642 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2643 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2644 E = ME->getBase();
2645 } else {
2646 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2647 E = MTE->GetTemporaryExpr();
2648 }
2649 E = E->IgnoreImpCasts();
2650 }
2651
2652 bool ReturnsReference = false;
2653 if (isa<UnaryOperator>(E)) {
2654 ReturnsReference = true;
2655 } else {
2656 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2657 const FunctionDecl *FD = Call->getDirectCallee();
2658 QualType ReturnType = FD->getReturnType();
2659 ReturnsReference = ReturnType->isReferenceType();
2660 }
2661
2662 if (ReturnsReference) {
2663 // Loop variable creates a temporary. Suggest either to go with
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002664 // non-reference loop variable to indicate a copy is made, or
Richard Trieu3e1d4832015-04-13 22:08:55 +00002665 // the correct time to bind a const reference.
2666 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2667 << VD << VariableType << E->getType();
2668 QualType NonReferenceType = VariableType.getNonReferenceType();
2669 NonReferenceType.removeLocalConst();
2670 QualType NewReferenceType =
2671 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2672 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2673 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2674 } else {
2675 // The range always returns a copy, so a temporary is always created.
2676 // Suggest removing the reference from the loop variable.
2677 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2678 << VD << RangeInitType;
2679 QualType NonReferenceType = VariableType.getNonReferenceType();
2680 NonReferenceType.removeLocalConst();
2681 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2682 << NonReferenceType << VD->getSourceRange();
2683 }
2684}
2685
2686// Warns when the loop variable can be changed to a reference type to
2687// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2688// "for (const Foo &x : Range)" if this form does not make a copy.
2689static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2690 const VarDecl *VD) {
2691 const Expr *InitExpr = VD->getInit();
2692 if (!InitExpr)
2693 return;
2694
2695 QualType VariableType = VD->getType();
2696
2697 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2698 if (!CE->getConstructor()->isCopyConstructor())
2699 return;
2700 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2701 if (CE->getCastKind() != CK_LValueToRValue)
2702 return;
2703 } else {
2704 return;
2705 }
2706
2707 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2708 // should be emitted. Also, only ignore POD types with trivial copy
2709 // constructors.
2710 if (VariableType.isPODType(SemaRef.Context))
2711 return;
2712
2713 // Suggest changing from a const variable to a const reference variable
2714 // if doing so will prevent a copy.
2715 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2716 << VD << VariableType << InitExpr->getType();
2717 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2718 << SemaRef.Context.getLValueReferenceType(VariableType)
2719 << VD->getSourceRange();
2720}
2721
2722/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2723/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2724/// using "const foo x" to show that a copy is made
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002725/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
Richard Trieu3e1d4832015-04-13 22:08:55 +00002726/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2727/// prevent the copy.
2728/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2729/// Suggest "const foo &x" to prevent the copy.
2730static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2731 const CXXForRangeStmt *ForStmt) {
2732 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2733 ForStmt->getLocStart()) &&
2734 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2735 ForStmt->getLocStart()) &&
2736 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2737 ForStmt->getLocStart())) {
2738 return;
2739 }
2740
2741 const VarDecl *VD = ForStmt->getLoopVariable();
2742 if (!VD)
2743 return;
2744
2745 QualType VariableType = VD->getType();
2746
2747 if (VariableType->isIncompleteType())
2748 return;
2749
2750 const Expr *InitExpr = VD->getInit();
2751 if (!InitExpr)
2752 return;
2753
2754 if (VariableType->isReferenceType()) {
2755 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2756 ForStmt->getRangeInit()->getType());
2757 } else if (VariableType.isConstQualified()) {
2758 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2759 }
2760}
2761
Richard Smith02e85f32011-04-14 22:09:26 +00002762/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2763/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2764/// body cannot be performed until after the type of the range variable is
2765/// determined.
2766StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2767 if (!S || !B)
2768 return StmtError();
2769
Fariborz Jahanian00213472012-07-06 19:04:04 +00002770 if (isa<ObjCForCollectionStmt>(S))
2771 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002772
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002773 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2774 ForStmt->setBody(B);
2775
2776 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2777 diag::warn_empty_range_based_for_body);
2778
Richard Trieu3e1d4832015-04-13 22:08:55 +00002779 DiagnoseForRangeVariableCopies(*this, ForStmt);
2780
Richard Smith02e85f32011-04-14 22:09:26 +00002781 return S;
2782}
2783
Chris Lattnercab02a62011-02-17 20:34:02 +00002784StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2785 SourceLocation LabelLoc,
2786 LabelDecl *TheDecl) {
Reid Kleckner87a31802018-03-12 21:43:02 +00002787 setFunctionHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002788 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002789 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002790}
Chris Lattner1c310502007-05-31 06:00:00 +00002791
John McCalldadc5752010-08-24 06:29:42 +00002792StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002793Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002794 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002795 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002796 if (!E->isTypeDependent()) {
2797 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002798 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002799 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002800 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002801 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2802 if (ExprRes.isInvalid())
2803 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002804 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002805 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002806 return StmtError();
2807 }
John McCalla95172b2010-08-01 00:26:45 +00002808
Richard Smith945f8d32013-01-14 22:39:08 +00002809 ExprResult ExprRes = ActOnFinishFullExpr(E);
2810 if (ExprRes.isInvalid())
2811 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002812 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002813
Reid Kleckner87a31802018-03-12 21:43:02 +00002814 setFunctionHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002815
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002816 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002817}
2818
Nico Weberd64657f2015-03-09 02:47:59 +00002819static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2820 const Scope &DestScope) {
2821 if (!S.CurrentSEHFinally.empty() &&
2822 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2823 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2824 }
2825}
2826
John McCalldadc5752010-08-24 06:29:42 +00002827StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002828Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002829 Scope *S = CurScope->getContinueParent();
2830 if (!S) {
2831 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002832 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002833 }
Nico Weberd64657f2015-03-09 02:47:59 +00002834 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002835
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002836 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002837}
2838
John McCalldadc5752010-08-24 06:29:42 +00002839StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002840Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002841 Scope *S = CurScope->getBreakParent();
2842 if (!S) {
2843 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002844 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002845 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002846 if (S->isOpenMPLoopScope())
2847 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2848 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002849 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002850
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002851 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002852}
2853
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002854/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002855/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002856///
Douglas Gregor5d369002011-01-21 18:05:27 +00002857/// \param ReturnType If we're determining the copy elision candidate for
2858/// a return statement, this is the return type of the function. If we're
2859/// determining the copy elision candidate for a throw expression, this will
2860/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002861///
Douglas Gregor5d369002011-01-21 18:05:27 +00002862/// \param E The expression being returned from the function or block, or
2863/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002864///
Richard Trieu09c163b2018-03-15 03:00:55 +00002865/// \param CESK Whether we allow function parameters or
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002866/// id-expressions that could be moved out of the function to be considered NRVO
2867/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2868/// determine whether we should try to move as part of a return or throw (which
2869/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002870///
2871/// \returns The NRVO candidate variable, if the return statement may use the
2872/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002873VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
Richard Trieu09c163b2018-03-15 03:00:55 +00002874 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002875 // - in a return statement in a function [where] ...
2876 // ... the expression is the name of a non-volatile automatic object ...
2877 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002878 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002879 return nullptr;
2880 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2881 if (!VD)
2882 return nullptr;
2883
Richard Trieu09c163b2018-03-15 03:00:55 +00002884 if (isCopyElisionCandidate(ReturnType, VD, CESK))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002885 return VD;
2886 return nullptr;
2887}
2888
2889bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Richard Trieu09c163b2018-03-15 03:00:55 +00002890 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002891 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002892 // - in a return statement in a function with ...
2893 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002894 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002895 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002896 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002897 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002898 // When considering moving this expression out, allow dissimilar types.
Richard Trieu09c163b2018-03-15 03:00:55 +00002899 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002900 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2901 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903
John McCall03318c12011-11-11 03:57:31 +00002904 // ...object (other than a function or catch-clause parameter)...
2905 if (VD->getKind() != Decl::Var &&
Richard Trieu09c163b2018-03-15 03:00:55 +00002906 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002907 return false;
2908 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002909
John McCall03318c12011-11-11 03:57:31 +00002910 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002911 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002912
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002913 // Return false if VD is a __block variable. We don't want to implicitly move
2914 // out of a __block variable during a return because we cannot assume the
2915 // variable will no longer be used.
2916 if (VD->hasAttr<BlocksAttr>()) return false;
2917
Richard Trieu09c163b2018-03-15 03:00:55 +00002918 if (CESK & CES_AllowDifferentTypes)
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002919 return true;
2920
John McCall03318c12011-11-11 03:57:31 +00002921 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002922 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002923
John McCall03318c12011-11-11 03:57:31 +00002924 // Variables with higher required alignment than their type's ABI
2925 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002926 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002927 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002928 return false;
John McCall03318c12011-11-11 03:57:31 +00002929
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002930 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002931}
2932
Richard Trieu09c163b2018-03-15 03:00:55 +00002933/// \brief Try to perform the initialization of a potentially-movable value,
2934/// which is the operand to a return or throw statement.
2935///
2936/// This routine implements C++14 [class.copy]p32, which attempts to treat
2937/// returned lvalues as rvalues in certain cases (to prefer move construction),
2938/// then falls back to treating them as lvalues if that failed.
2939///
2940/// \param Res We will fill this in if move-initialization was possible.
2941/// If move-initialization is not possible, such that we must fall back to
2942/// treating the operand as an lvalue, we will leave Res in its original
2943/// invalid state.
2944static void TryMoveInitialization(Sema& S,
2945 const InitializedEntity &Entity,
2946 const VarDecl *NRVOCandidate,
2947 QualType ResultType,
2948 Expr *&Value,
2949 ExprResult &Res) {
2950 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2951 CK_NoOp, Value, VK_XValue);
2952
2953 Expr *InitExpr = &AsRvalue;
2954
2955 InitializationKind Kind = InitializationKind::CreateCopy(
2956 Value->getLocStart(), Value->getLocStart());
2957
2958 InitializationSequence Seq(S, Entity, Kind, InitExpr);
2959
2960 if (!Seq)
2961 return;
2962
2963 for (const InitializationSequence::Step &Step : Seq.steps()) {
2964 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
2965 Step.Kind != InitializationSequence::SK_UserConversion)
2966 continue;
2967
2968 FunctionDecl *FD = Step.Function.Function;
2969 if (isa<CXXConstructorDecl>(FD)) {
2970 // C++14 [class.copy]p32:
2971 // [...] If the first overload resolution fails or was not performed,
2972 // or if the type of the first parameter of the selected constructor
2973 // is not an rvalue reference to the object's type (possibly
2974 // cv-qualified), overload resolution is performed again, considering
2975 // the object as an lvalue.
2976 const RValueReferenceType *RRefType =
2977 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
2978 if (!RRefType)
2979 break;
2980 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2981 NRVOCandidate->getType()))
2982 break;
2983 } else {
2984 continue;
2985 }
2986
2987 // Promote "AsRvalue" to the heap, since we now need this
2988 // expression node to persist.
2989 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
2990 Value, nullptr, VK_XValue);
2991
2992 // Complete type-checking the initialization of the return type
2993 // using the constructor we found.
2994 Res = Seq.Perform(S, Entity, Kind, Value);
2995 }
2996}
2997
Douglas Gregor626fbed2011-01-21 21:08:57 +00002998/// \brief Perform the initialization of a potentially-movable value, which
2999/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00003000///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003001/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00003002/// returned lvalues as rvalues in certain cases (to prefer move construction),
3003/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003004ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00003005Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3006 const VarDecl *NRVOCandidate,
3007 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00003008 Expr *Value,
3009 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003010 // C++14 [class.copy]p32:
3011 // When the criteria for elision of a copy/move operation are met, but not for
3012 // an exception-declaration, and the object to be copied is designated by an
3013 // lvalue, or when the expression in a return statement is a (possibly
3014 // parenthesized) id-expression that names an object with automatic storage
3015 // duration declared in the body or parameter-declaration-clause of the
3016 // innermost enclosing function or lambda-expression, overload resolution to
3017 // select the constructor for the copy is first performed as if the object
3018 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00003019 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003020
Richard Trieu09c163b2018-03-15 03:00:55 +00003021 if (AllowNRVO) {
3022 if (!NRVOCandidate) {
3023 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3024 }
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003025
Richard Trieu09c163b2018-03-15 03:00:55 +00003026 if (NRVOCandidate) {
3027 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3028 Res);
Douglas Gregorf282a762011-01-21 19:38:21 +00003029 }
3030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031
Douglas Gregorf282a762011-01-21 19:38:21 +00003032 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003033 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00003034 // (again) now with the return value expression as written.
3035 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00003036 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003037
Douglas Gregorf282a762011-01-21 19:38:21 +00003038 return Res;
3039}
3040
Richard Smith4db51c22013-09-25 05:02:54 +00003041/// \brief Determine whether the declared return type of the specified function
3042/// contains 'auto'.
3043static bool hasDeducedReturnType(FunctionDecl *FD) {
3044 const FunctionProtoType *FPT =
3045 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003046 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003047}
3048
Eli Friedman34b49062012-01-26 03:00:14 +00003049/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3050/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003051///
John McCalldadc5752010-08-24 06:29:42 +00003052StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003053Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3054 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003055 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003056 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003057 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003058 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003059 bool HasDeducedReturnType =
3060 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003061
Faisal Valid143a0c2017-04-01 21:30:49 +00003062 if (ExprEvalContexts.back().Context ==
3063 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003064 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3065 if (RetValExp) {
3066 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3067 if (ER.isInvalid())
3068 return StmtError();
3069 RetValExp = ER.get();
3070 }
3071 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3072 }
3073
3074 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003075 // In C++1y, the return type may involve 'auto'.
3076 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3077 FunctionDecl *FD = CurLambda->CallOperator;
3078 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003079 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003080
3081 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3082 assert(AT && "lost auto type from lambda return type");
3083 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3084 FD->setInvalidDecl();
3085 return StmtError();
3086 }
Alp Toker314cc812014-01-25 16:55:45 +00003087 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003088 } else if (CurCap->HasImplicitReturnType) {
3089 // For blocks/lambdas with implicit return types, we check each return
3090 // statement individually, and deduce the common return type when the block
3091 // or lambda is completed.
3092 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003093 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003094 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3095 if (Result.isInvalid())
3096 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003097 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003098
Richard Smith5a0e50c2014-12-19 22:10:51 +00003099 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3100 // when deducing a return type for a lambda-expression (or by extension
3101 // for a block). These rules differ from the stated C++11 rules only in
3102 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003103 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003104 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003105 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003106 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003107 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003108 if (RetValExp) {
3109 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3110 // initializer list, because it is not an expression (even
3111 // though we represent it as one). We still deduce 'void'.
3112 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3113 << RetValExp->getSourceRange();
3114 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003115
Jordan Rosed39e5f12012-07-02 21:19:23 +00003116 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003117 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003118
3119 // Although we'll properly infer the type of the block once it's completed,
3120 // make sure we provide a return type now for better error recovery.
3121 if (CurCap->ReturnType.isNull())
3122 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003123 }
Eli Friedman34b49062012-01-26 03:00:14 +00003124 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003125
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003126 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00003127 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3128 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3129 return StmtError();
3130 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003131 } else if (CapturedRegionScopeInfo *CurRegion =
3132 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3133 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3134 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003135 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003136 assert(CurLambda && "unknown kind of captured scope");
3137 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3138 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003139 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3140 return StmtError();
3141 }
3142 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003143
Steve Naroffc540d662008-09-03 18:15:37 +00003144 // Otherwise, verify that this result type matches the previous one. We are
3145 // pickier with blocks than for normal functions because we don't have GCC
3146 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003147 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003148 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003149 // Delay processing for now. TODO: there are lots of dependent
3150 // types we can conclusively prove aren't void.
3151 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003152 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003153 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003154 (RetValExp->isTypeDependent() ||
3155 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003156 if (!getLangOpts().CPlusPlus &&
3157 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003158 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003159 else {
3160 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003161 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003162 }
Steve Naroffc540d662008-09-03 18:15:37 +00003163 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003164 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003165 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3166 } else if (!RetValExp->isTypeDependent()) {
3167 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003168
John McCall5500ef22011-08-17 22:09:46 +00003169 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3170 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3171 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003172
John McCall5500ef22011-08-17 22:09:46 +00003173 // In C++ the return statement is handled via a copy initialization.
3174 // the C version of which boils down to CheckSingleAssignmentConstraints.
Richard Trieu09c163b2018-03-15 03:00:55 +00003175 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
John McCall5500ef22011-08-17 22:09:46 +00003176 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3177 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003178 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003179 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3180 FnRetType, RetValExp);
3181 if (Res.isInvalid()) {
3182 // FIXME: Cleanup temporaries here, anyway?
3183 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003184 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003185 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003186 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003187 } else {
Richard Trieu09c163b2018-03-15 03:00:55 +00003188 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Steve Naroffc540d662008-09-03 18:15:37 +00003189 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003190
John McCall75f92b52011-08-17 21:34:14 +00003191 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003192 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3193 if (ER.isInvalid())
3194 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003195 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003196 }
John McCall5500ef22011-08-17 22:09:46 +00003197 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3198 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003199
Jordan Rosed39e5f12012-07-02 21:19:23 +00003200 // If we need to check for the named return value optimization,
3201 // or if we need to infer the return type,
3202 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003203 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003204 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003205
Richard Smith9f690bd2015-10-27 06:02:45 +00003206 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3207 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3208
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003209 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003210}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003211
Nico Weber72889432014-09-06 01:25:55 +00003212namespace {
3213/// \brief Marks all typedefs in all local classes in a type referenced.
3214///
3215/// In a function like
3216/// auto f() {
3217/// struct S { typedef int a; };
3218/// return S();
3219/// }
3220///
3221/// the local type escapes and could be referenced in some TUs but not in
3222/// others. Pretend that all local typedefs are always referenced, to not warn
3223/// on this. This isn't necessary if f has internal linkage, or the typedef
3224/// is private.
3225class LocalTypedefNameReferencer
3226 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3227public:
3228 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3229 bool VisitRecordType(const RecordType *RT);
3230private:
3231 Sema &S;
3232};
3233bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3234 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3235 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3236 R->isDependentType())
3237 return true;
3238 for (auto *TmpD : R->decls())
3239 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3240 if (T->getAccess() != AS_private || R->hasFriends())
3241 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3242 return true;
3243}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003244}
Nico Weber72889432014-09-06 01:25:55 +00003245
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003246TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003247 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003248 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3249 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003250 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003251}
3252
Richard Smith2a7d4812013-05-04 07:00:32 +00003253/// Deduce the return type for a function from a returned expression, per
3254/// C++1y [dcl.spec.auto]p6.
3255bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3256 SourceLocation ReturnLoc,
3257 Expr *&RetExpr,
3258 AutoType *AT) {
Richard Smith50e291e2018-01-02 23:52:42 +00003259 // If this is the conversion function for a lambda, we choose to deduce it
3260 // type from the corresponding call operator, not from the synthesized return
3261 // statement within it. See Sema::DeduceReturnType.
3262 if (isLambdaConversionOperator(FD))
3263 return false;
3264
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003265 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003266 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003267
Richard Smithc58f38f2013-08-14 20:16:31 +00003268 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3269 // If the deduction is for a return statement and the initializer is
3270 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003271 Diag(RetExpr->getExprLoc(),
3272 getCurLambda() ? diag::err_lambda_return_init_list
3273 : diag::err_auto_fn_return_init_list)
3274 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003275 return true;
3276 }
3277
3278 if (FD->isDependentContext()) {
3279 // C++1y [dcl.spec.auto]p12:
3280 // Return type deduction [...] occurs when the definition is
3281 // instantiated even if the function body contains a return
3282 // statement with a non-type-dependent operand.
3283 assert(AT->isDeduced() && "should have deduced to dependent type");
3284 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003285 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003286
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003287 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003288 // Otherwise, [...] deduce a value for U using the rules of template
3289 // argument deduction.
3290 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3291
3292 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3293 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3294 << OrigResultType.getType() << RetExpr->getType();
3295
3296 if (DAR != DAR_Succeeded)
3297 return true;
Nico Weber72889432014-09-06 01:25:55 +00003298
3299 // If a local type is part of the returned type, mark its fields as
3300 // referenced.
3301 LocalTypedefNameReferencer Referencer(*this);
3302 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003303 } else {
3304 // In the case of a return with no operand, the initializer is considered
3305 // to be void().
3306 //
3307 // Deduction here can only succeed if the return type is exactly 'cv auto'
3308 // or 'decltype(auto)', so just check for that case directly.
3309 if (!OrigResultType.getType()->getAs<AutoType>()) {
3310 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3311 << OrigResultType.getType();
3312 return true;
3313 }
3314 // We always deduce U = void in this case.
3315 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3316 if (Deduced.isNull())
3317 return true;
3318 }
3319
3320 // If a function with a declared return type that contains a placeholder type
3321 // has multiple return statements, the return type is deduced for each return
3322 // statement. [...] if the type deduced is not the same in each deduction,
3323 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003324 QualType DeducedT = AT->getDeducedType();
3325 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003326 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003327 // It is possible that NewAT->getDeducedType() is null. When that happens,
3328 // we should not crash, instead we ignore this deduction.
3329 if (NewAT->getDeducedType().isNull())
3330 return false;
3331
Douglas Gregora602a152015-10-01 20:20:47 +00003332 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003333 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003334 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3335 NewAT->getDeducedType());
3336 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003337 const LambdaScopeInfo *LambdaSI = getCurLambda();
3338 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3339 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003340 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003341 << true /*IsLambda*/;
3342 } else {
3343 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3344 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003345 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003346 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003347 return true;
3348 }
3349 } else if (!FD->isInvalidDecl()) {
3350 // Update all declarations of the function to have the deduced return type.
3351 Context.adjustDeducedFunctionResultType(FD, Deduced);
3352 }
3353
3354 return false;
3355}
3356
John McCalldadc5752010-08-24 06:29:42 +00003357StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003358Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3359 Scope *CurScope) {
3360 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Faisal Valid143a0c2017-04-01 21:30:49 +00003361 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3362 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003363 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003364
3365 if (VarDecl *VD =
3366 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3367 CurScope->addNRVOCandidate(VD);
3368 } else {
3369 CurScope->setNoNRVO();
3370 }
3371
Nico Weberd64657f2015-03-09 02:47:59 +00003372 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3373
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003374 return R;
3375}
3376
3377StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003378 // Check for unexpanded parameter packs.
3379 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3380 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003381
Eli Friedman34b49062012-01-26 03:00:14 +00003382 if (isa<CapturingScopeInfo>(getCurFunction()))
3383 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003384
Chris Lattner79413952008-12-04 23:50:19 +00003385 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003386 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003387 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003388 bool isObjCMethod = false;
3389
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003390 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003391 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003392 if (FD->hasAttrs())
3393 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003394 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003395 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003396 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003397 if (FD->isMain() && RetValExp)
3398 if (isa<CXXBoolLiteralExpr>(RetValExp))
3399 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3400 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003401 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003402 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003403 isObjCMethod = true;
3404 if (MD->hasAttrs())
3405 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003406 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3407 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003408 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003409 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003410 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3411 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003412 }
3413 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003414 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003415
Richard Smithb130fe72016-06-23 19:16:49 +00003416 // C++1z: discarded return statements are not considered when deducing a
3417 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003418 if (ExprEvalContexts.back().Context ==
3419 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003420 FnRetType->getContainedAutoType()) {
3421 if (RetValExp) {
3422 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3423 if (ER.isInvalid())
3424 return StmtError();
3425 RetValExp = ER.get();
3426 }
3427 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3428 }
3429
Richard Smith2a7d4812013-05-04 07:00:32 +00003430 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3431 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003432 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003433 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3434 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003435 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003436 FD->setInvalidDecl();
3437 return StmtError();
3438 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003439 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003440 }
3441 }
3442 }
3443
Richard Smithc58f38f2013-08-14 20:16:31 +00003444 bool HasDependentReturnType = FnRetType->isDependentType();
3445
Craig Topperc3ec1492014-05-26 06:22:03 +00003446 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003447 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003448 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003449 if (isa<InitListExpr>(RetValExp)) {
3450 // We simply never allow init lists as the return value of void
3451 // functions. This is compatible because this was never allowed before,
3452 // so there's no legacy code to deal with.
3453 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3454 int FunctionKind = 0;
3455 if (isa<ObjCMethodDecl>(CurDecl))
3456 FunctionKind = 1;
3457 else if (isa<CXXConstructorDecl>(CurDecl))
3458 FunctionKind = 2;
3459 else if (isa<CXXDestructorDecl>(CurDecl))
3460 FunctionKind = 3;
3461
3462 Diag(ReturnLoc, diag::err_return_init_list)
3463 << CurDecl->getDeclName() << FunctionKind
3464 << RetValExp->getSourceRange();
3465
3466 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003467 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003468 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003469 // C99 6.8.6.4p1 (ext_ since GCC warns)
3470 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003471 if (RetValExp->getType()->isVoidType()) {
3472 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3473 if (isa<CXXConstructorDecl>(CurDecl) ||
3474 isa<CXXDestructorDecl>(CurDecl))
3475 D = diag::err_ctor_dtor_returns_void;
3476 else
3477 D = diag::ext_return_has_void_expr;
3478 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003479 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003480 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003481 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003482 if (Result.isInvalid())
3483 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003484 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003485 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003486 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003487 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003488 // return of void in constructor/destructor is illegal in C++.
3489 if (D == diag::err_ctor_dtor_returns_void) {
3490 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3491 Diag(ReturnLoc, D)
3492 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3493 << RetValExp->getSourceRange();
3494 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003495 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003496 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003497 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003498 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003499
3500 int FunctionKind = 0;
3501 if (isa<ObjCMethodDecl>(CurDecl))
3502 FunctionKind = 1;
3503 else if (isa<CXXConstructorDecl>(CurDecl))
3504 FunctionKind = 2;
3505 else if (isa<CXXDestructorDecl>(CurDecl))
3506 FunctionKind = 3;
3507
Nick Lewycky1be750a2011-06-01 07:44:31 +00003508 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003509 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003510 << RetValExp->getSourceRange();
3511 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003512 }
Mike Stump11289f42009-09-09 15:08:12 +00003513
Sebastian Redleef474c2012-02-22 10:50:08 +00003514 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003515 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3516 if (ER.isInvalid())
3517 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003518 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003519 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Craig Topperc3ec1492014-05-26 06:22:03 +00003522 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003523 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003524 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003525
David Majnemer2887ad32014-12-13 08:12:56 +00003526 unsigned DiagID;
3527 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3528 // C++11 [stmt.return]p2
3529 DiagID = diag::err_constexpr_return_missing_expr;
3530 FD->setInvalidDecl();
3531 } else if (getLangOpts().C99) {
3532 // C99 6.8.6.4p1 (ext_ since GCC warns)
3533 DiagID = diag::ext_return_missing_expr;
3534 } else {
3535 // C90 6.6.6.4p4
3536 DiagID = diag::warn_return_missing_expr;
3537 }
3538
3539 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003540 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003541 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003542 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003543
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003544 Result = new (Context) ReturnStmt(ReturnLoc);
3545 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003546 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003547 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003548
3549 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3550
3551 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3552 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3553 // function return.
3554
3555 // In C++ the return statement is handled via a copy initialization,
3556 // the C version of which boils down to CheckSingleAssignmentConstraints.
3557 if (RetValExp)
Richard Trieu09c163b2018-03-15 03:00:55 +00003558 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Richard Smith2a7d4812013-05-04 07:00:32 +00003559 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003560 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003562 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003563 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003565 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003566 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003567 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003568 return StmtError();
3569 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003570 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003571
3572 // If we have a related result type, we need to implicitly
3573 // convert back to the formal result type. We can't pretend to
3574 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003575 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003576 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003577 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3578 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003579 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3580 if (Res.isInvalid()) {
3581 // FIXME: Clean up temporaries here anyway?
3582 return StmtError();
3583 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003584 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003585 }
3586
Artyom Skrobov9f213442014-01-24 11:10:39 +00003587 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3588 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590
John McCallacf0ee52010-10-08 02:01:28 +00003591 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003592 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3593 if (ER.isInvalid())
3594 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003595 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003596 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003597 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
3600 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003601 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003602 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003603 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003604
Richard Smith9f690bd2015-10-27 06:02:45 +00003605 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3606 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3607
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003608 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003609}
3610
John McCalldadc5752010-08-24 06:29:42 +00003611StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003612Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003613 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003614 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003615 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003616 if (Var && Var->isInvalidDecl())
3617 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003619 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003620}
3621
John McCalldadc5752010-08-24 06:29:42 +00003622StmtResult
John McCallb268a282010-08-23 23:25:46 +00003623Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003624 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003625}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003626
John McCalldadc5752010-08-24 06:29:42 +00003627StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003629 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003630 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003631 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3632
Reid Kleckner87a31802018-03-12 21:43:02 +00003633 setFunctionHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003634 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003635 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3636 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003637}
3638
John McCall0bd3e402012-05-08 21:41:25 +00003639StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003640 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003641 ExprResult Result = DefaultLvalueConversion(Throw);
3642 if (Result.isInvalid())
3643 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003644
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003645 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003646 if (Result.isInvalid())
3647 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003648 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003649
Douglas Gregor2900c162010-04-22 21:44:01 +00003650 QualType ThrowType = Throw->getType();
3651 // Make sure the expression type is an ObjC pointer or "void *".
3652 if (!ThrowType->isDependentType() &&
3653 !ThrowType->isObjCObjectPointerType()) {
3654 const PointerType *PT = ThrowType->getAs<PointerType>();
3655 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003656 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003657 << Throw->getType() << Throw->getSourceRange());
3658 }
3659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003661 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003662}
3663
John McCalldadc5752010-08-24 06:29:42 +00003664StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003666 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003667 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003668 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3669
John McCallb268a282010-08-23 23:25:46 +00003670 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003671 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003672 // in the context of an @catch clause).
3673 Scope *AtCatchParent = CurScope;
3674 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3675 AtCatchParent = AtCatchParent->getParent();
3676 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003677 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678 }
John McCallb268a282010-08-23 23:25:46 +00003679 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003680}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003681
John McCalld9bb7432011-07-27 21:50:02 +00003682ExprResult
3683Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3684 ExprResult result = DefaultLvalueConversion(operand);
3685 if (result.isInvalid())
3686 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003687 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003688
3689 // Make sure the expression type is an ObjC pointer or "void *".
3690 QualType type = operand->getType();
3691 if (!type->isDependentType() &&
3692 !type->isObjCObjectPointerType()) {
3693 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003694 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3695 if (getLangOpts().CPlusPlus) {
3696 if (RequireCompleteType(atLoc, type,
3697 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003698 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003699 << type << operand->getSourceRange();
3700
3701 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003702 if (result.isInvalid())
3703 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003704 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003705 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003706 << type << operand->getSourceRange();
3707
3708 operand = result.get();
3709 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003710 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003711 << type << operand->getSourceRange();
3712 }
3713 }
John McCalld9bb7432011-07-27 21:50:02 +00003714 }
3715
3716 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003717 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003718}
3719
John McCalldadc5752010-08-24 06:29:42 +00003720StmtResult
John McCallb268a282010-08-23 23:25:46 +00003721Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3722 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003723 // We can't jump into or indirect-jump out of a @synchronized block.
Reid Kleckner87a31802018-03-12 21:43:02 +00003724 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003725 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003726}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003727
3728/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3729/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003730StmtResult
John McCall48871652010-08-21 09:40:31 +00003731Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003732 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003733 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003734 return new (Context)
3735 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003736}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003737
John McCall31168b02011-06-15 23:02:42 +00003738StmtResult
3739Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
Reid Kleckner87a31802018-03-12 21:43:02 +00003740 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003741 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003742}
3743
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003744namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003745class CatchHandlerType {
3746 QualType QT;
3747 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003748
Aaron Ballman8aee642902015-04-08 00:05:29 +00003749 // This is a special constructor to be used only with DenseMapInfo's
3750 // getEmptyKey() and getTombstoneKey() functions.
3751 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3752 enum Unique { ForDenseMap };
3753 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3754
Sebastian Redl63c4da02009-07-29 17:15:45 +00003755public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003756 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003757 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003758 /// level pointer and cv-qualifiers.
3759 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3760 if (QT->isPointerType())
3761 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003762
Aaron Ballman8aee642902015-04-08 00:05:29 +00003763 if (IsPointer || QT->isReferenceType())
3764 QT = QT->getPointeeType();
3765 QT = QT.getUnqualifiedType();
3766 }
3767
3768 /// Used when creating a CatchHandlerType from a base class type; pretends the
3769 /// type passed in had the pointer qualifier, does not need to get an
3770 /// unqualified type.
3771 CatchHandlerType(QualType QT, bool IsPointer)
3772 : QT(QT), IsPointer(IsPointer) {}
3773
3774 QualType underlying() const { return QT; }
3775 bool isPointer() const { return IsPointer; }
3776
3777 friend bool operator==(const CatchHandlerType &LHS,
3778 const CatchHandlerType &RHS) {
3779 // If the pointer qualification does not match, we can return early.
3780 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003781 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003782 // Otherwise, check the underlying type without cv-qualifiers.
3783 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003784 }
3785};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003786} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003787
Aaron Ballman8aee642902015-04-08 00:05:29 +00003788namespace llvm {
3789template <> struct DenseMapInfo<CatchHandlerType> {
3790 static CatchHandlerType getEmptyKey() {
3791 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3792 CatchHandlerType::ForDenseMap);
3793 }
3794
3795 static CatchHandlerType getTombstoneKey() {
3796 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3797 CatchHandlerType::ForDenseMap);
3798 }
3799
3800 static unsigned getHashValue(const CatchHandlerType &Base) {
3801 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3802 }
3803
3804 static bool isEqual(const CatchHandlerType &LHS,
3805 const CatchHandlerType &RHS) {
3806 return LHS == RHS;
3807 }
3808};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003809}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003810
3811namespace {
3812class CatchTypePublicBases {
3813 ASTContext &Ctx;
3814 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3815 const bool CheckAgainstPointer;
3816
3817 CXXCatchStmt *FoundHandler;
3818 CanQualType FoundHandlerType;
3819
3820public:
3821 CatchTypePublicBases(
3822 ASTContext &Ctx,
3823 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3824 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3825 FoundHandler(nullptr) {}
3826
3827 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3828 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3829
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003830 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003831 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003832 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003833 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003834 auto I = M.find(Check);
3835 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003836 FoundHandler = I->second;
3837 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003838 return true;
3839 }
3840 }
3841 return false;
3842 }
3843};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003844}
Dan Gohman28ade552010-07-26 21:25:24 +00003845
Sebastian Redl9b244a82008-12-22 21:35:02 +00003846/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3847/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003848StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3849 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003850 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003851 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003852 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003853 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003854
Justin Lebar2a8db342016-09-28 22:45:54 +00003855 // Exceptions aren't allowed in CUDA device code.
3856 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00003857 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3858 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00003859
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003860 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3861 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3862
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003863 sema::FunctionScopeInfo *FSI = getCurFunction();
3864
Reid Klecknere7175912015-02-02 22:15:31 +00003865 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003866 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003867 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003868 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003869 }
3870
Robert Wilhelmcafda822013-08-22 09:20:03 +00003871 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003872 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003873 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003874
Aaron Ballman8aee642902015-04-08 00:05:29 +00003875 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003876 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003877 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003878
Aaron Ballman8aee642902015-04-08 00:05:29 +00003879 // Diagnose when the handler is a catch-all handler, but it isn't the last
3880 // handler for the try block. [except.handle]p5. Also, skip exception
3881 // declarations that are invalid, since we can't usefully report on them.
3882 if (!H->getExceptionDecl()) {
3883 if (i < NumHandlers - 1)
3884 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003885 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003886 } else if (H->getExceptionDecl()->isInvalidDecl())
3887 continue;
3888
3889 // Walk the type hierarchy to diagnose when this type has already been
3890 // handled (duplication), or cannot be handled (derivation inversion). We
3891 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003892 CatchHandlerType HandlerCHT =
3893 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003894
3895 // We can ignore whether the type is a reference or a pointer; we need the
3896 // underlying declaration type in order to get at the underlying record
3897 // decl, if there is one.
3898 QualType Underlying = HandlerCHT.underlying();
3899 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3900 if (!RD->hasDefinition())
3901 continue;
3902 // Check that none of the public, unambiguous base classes are in the
3903 // map ([except.handle]p1). Give the base classes the same pointer
3904 // qualification as the original type we are basing off of. This allows
3905 // comparison against the handler type using the same top-level pointer
3906 // as the original type.
3907 CXXBasePaths Paths;
3908 Paths.setOrigin(RD);
3909 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003910 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003911 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3912 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3913 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3914 diag::warn_exception_caught_by_earlier_handler)
3915 << H->getCaughtType();
3916 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3917 diag::note_previous_exception_handler)
3918 << Problem->getCaughtType();
3919 }
3920 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003921 }
Mike Stump11289f42009-09-09 15:08:12 +00003922
Aaron Ballman8aee642902015-04-08 00:05:29 +00003923 // Add the type the list of ones we have handled; diagnose if we've already
3924 // handled it.
3925 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3926 if (!R.second) {
3927 const CXXCatchStmt *Problem = R.first->second;
3928 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3929 diag::warn_exception_caught_by_earlier_handler)
3930 << H->getCaughtType();
3931 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3932 diag::note_previous_exception_handler)
3933 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003934 }
3935 }
Mike Stump11289f42009-09-09 15:08:12 +00003936
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003937 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003938
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003939 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003940}
John Wiegley1c0675e2011-04-28 01:08:34 +00003941
Reid Klecknere7175912015-02-02 22:15:31 +00003942StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3943 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003944 assert(TryBlock && Handler);
3945
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003946 sema::FunctionScopeInfo *FSI = getCurFunction();
3947
Reid Klecknere7175912015-02-02 22:15:31 +00003948 // SEH __try is incompatible with C++ try. Borland appears to support this,
3949 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003950 if (!getLangOpts().Borland) {
3951 if (FSI->FirstCXXTryLoc.isValid()) {
3952 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3953 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3954 }
Reid Klecknere7175912015-02-02 22:15:31 +00003955 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003956
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003957 FSI->setHasSEHTry(TryLoc);
3958
3959 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3960 // track if they use SEH.
3961 DeclContext *DC = CurContext;
3962 while (DC && !DC->isFunctionOrMethod())
3963 DC = DC->getParent();
3964 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3965 if (FD)
3966 FD->setUsesSEHTry(true);
3967 else
3968 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003969
Reid Kleckner8819a402015-07-10 00:16:25 +00003970 // Reject __try on unsupported targets.
3971 if (!Context.getTargetInfo().isSEHTrySupported())
3972 Diag(TryLoc, diag::err_seh_try_unsupported);
3973
Reid Klecknere7175912015-02-02 22:15:31 +00003974 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003975}
3976
3977StmtResult
3978Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3979 Expr *FilterExpr,
3980 Stmt *Block) {
3981 assert(FilterExpr && Block);
3982
3983 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003984 return StmtError(Diag(FilterExpr->getExprLoc(),
3985 diag::err_filter_expression_integral)
3986 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003987 }
3988
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003989 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003990}
3991
Nico Weberd64657f2015-03-09 02:47:59 +00003992void Sema::ActOnStartSEHFinallyBlock() {
3993 CurrentSEHFinally.push_back(CurScope);
3994}
3995
Nico Weberce903292015-03-09 03:17:15 +00003996void Sema::ActOnAbortSEHFinallyBlock() {
3997 CurrentSEHFinally.pop_back();
3998}
3999
Nico Weberd64657f2015-03-09 02:47:59 +00004000StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004001 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00004002 CurrentSEHFinally.pop_back();
4003 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004004}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004005
Nico Weberc7d05962014-07-06 22:32:59 +00004006StmtResult
4007Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00004008 Scope *SEHTryParent = CurScope;
4009 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4010 SEHTryParent = SEHTryParent->getParent();
4011 if (!SEHTryParent)
4012 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00004013 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00004014
Nico Weber9b982072014-07-07 00:12:30 +00004015 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00004016}
4017
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004018StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4019 bool IsIfExists,
4020 NestedNameSpecifierLoc QualifierLoc,
4021 DeclarationNameInfo NameInfo,
4022 Stmt *Nested)
4023{
4024 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004025 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004026 cast<CompoundStmt>(Nested));
4027}
4028
4029
Chad Rosier02a84392012-08-10 17:56:09 +00004030StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004031 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004032 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004033 UnqualifiedId &Name,
4034 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00004035 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004036 SS.getWithLocInContext(Context),
4037 GetNameFromUnqualifiedId(Name),
4038 Nested);
4039}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004040
4041RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00004042Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4043 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004044 DeclContext *DC = CurContext;
4045 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4046 DC = DC->getParent();
4047
Craig Topperc3ec1492014-05-26 06:22:03 +00004048 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004049 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004050 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4051 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004052 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004053 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004054
Alexey Bataev330de032014-10-29 12:21:55 +00004055 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004056 DC->addDecl(RD);
4057 RD->setImplicit();
4058 RD->startDefinition();
4059
Alexey Bataev9959db52014-05-06 10:08:46 +00004060 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004061 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004062 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004063 return RD;
4064}
4065
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004066static void
4067buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
4068 SmallVectorImpl<Expr *> &CaptureInits,
4069 ArrayRef<sema::Capture> Candidates) {
4070 for (const sema::Capture &Cap : Candidates) {
4071 if (Cap.isThisCapture()) {
4072 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004073 CapturedStmt::VCK_This));
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004074 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004075 continue;
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004076 } else if (Cap.isVLATypeCapture()) {
Alexey Bataev330de032014-10-29 12:21:55 +00004077 Captures.push_back(
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004078 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
Alexey Bataev330de032014-10-29 12:21:55 +00004079 CaptureInits.push_back(nullptr);
4080 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004081 }
4082
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004083 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4084 Cap.isReferenceCapture()
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004085 ? CapturedStmt::VCK_ByRef
4086 : CapturedStmt::VCK_ByCopy,
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004087 Cap.getVariable()));
4088 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004089 }
4090}
4091
4092void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004093 CapturedRegionKind Kind,
4094 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004095 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004096 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004097
Alexey Bataev9959db52014-05-06 10:08:46 +00004098 // Build the context parameter
4099 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4100 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4101 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004102 auto *Param =
4103 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4104 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004105 DC->addDecl(Param);
4106
4107 CD->setContextParam(0, Param);
4108
4109 // Enter the capturing scope for this captured region.
4110 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4111
4112 if (CurScope)
4113 PushDeclContext(CurScope, CD);
4114 else
4115 CurContext = CD;
4116
Faisal Valid143a0c2017-04-01 21:30:49 +00004117 PushExpressionEvaluationContext(
4118 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004119}
4120
4121void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4122 CapturedRegionKind Kind,
4123 ArrayRef<CapturedParamNameType> Params) {
4124 CapturedDecl *CD = nullptr;
4125 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4126
4127 // Build the context parameter
4128 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4129 bool ContextIsFound = false;
4130 unsigned ParamNum = 0;
4131 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4132 E = Params.end();
4133 I != E; ++I, ++ParamNum) {
4134 if (I->second.isNull()) {
4135 assert(!ContextIsFound &&
4136 "null type has been found already for '__context' parameter");
4137 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4138 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004139 auto *Param =
4140 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4141 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004142 DC->addDecl(Param);
4143 CD->setContextParam(ParamNum, Param);
4144 ContextIsFound = true;
4145 } else {
4146 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004147 auto *Param =
4148 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4149 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004150 DC->addDecl(Param);
4151 CD->setParam(ParamNum, Param);
4152 }
4153 }
4154 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004155 if (!ContextIsFound) {
4156 // Add __context implicitly if it is not specified.
4157 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4158 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004159 auto *Param =
4160 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4161 ImplicitParamDecl::CapturedContext);
Alexey Bataev301a2d92014-05-14 10:40:54 +00004162 DC->addDecl(Param);
4163 CD->setContextParam(ParamNum, Param);
4164 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004165 // Enter the capturing scope for this captured region.
4166 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4167
4168 if (CurScope)
4169 PushDeclContext(CurScope, CD);
4170 else
4171 CurContext = CD;
4172
Faisal Valid143a0c2017-04-01 21:30:49 +00004173 PushExpressionEvaluationContext(
4174 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004175}
4176
Wei Pan17fbf6e2013-05-04 03:59:06 +00004177void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004178 DiscardCleanupsInEvaluationContext();
4179 PopExpressionEvaluationContext();
4180
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004181 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4182 RecordDecl *Record = RSI->TheRecordDecl;
4183 Record->setInvalidDecl();
4184
Aaron Ballman62e47c42014-03-10 13:43:55 +00004185 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004186 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4187 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004188
Wei Pan17fbf6e2013-05-04 03:59:06 +00004189 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004190 PopFunctionScopeInfo();
4191}
4192
4193StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4194 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4195
4196 SmallVector<CapturedStmt::Capture, 4> Captures;
4197 SmallVector<Expr *, 4> CaptureInits;
4198 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4199
4200 CapturedDecl *CD = RSI->TheCapturedDecl;
4201 RecordDecl *RD = RSI->TheRecordDecl;
4202
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004203 CapturedStmt *Res = CapturedStmt::Create(
4204 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4205 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004206
4207 CD->setBody(Res->getCapturedStmt());
4208 RD->completeDefinition();
4209
Wei Pan17fbf6e2013-05-04 03:59:06 +00004210 DiscardCleanupsInEvaluationContext();
4211 PopExpressionEvaluationContext();
4212
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004213 PopDeclContext();
4214 PopFunctionScopeInfo();
4215
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004216 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004217}