blob: 9ffc23b5adbab5972078e3849a76e23c6febb5da [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"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000040
Chris Lattneraf8d5812006-11-10 05:07:45 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000043
Richard Smith945f8d32013-01-14 22:39:08 +000044StmtResult Sema::ActOnExprStmt(ExprResult FE) {
45 if (FE.isInvalid())
46 return StmtError();
47
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
50 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000051 return StmtError();
52
Chris Lattner903eb512008-07-25 23:18:17 +000053 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000056
Chris Lattner903eb512008-07-25 23:18:17 +000057 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000058 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000059}
60
61
John McCalleaef89b2013-03-22 02:10:40 +000062StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
64 return StmtError();
65}
66
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000067StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000068 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000069 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000070}
71
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000072StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000074 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnercbafe8d2009-04-12 20:13:14 +000076 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000079 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000080}
Chris Lattneraf8d5812006-11-10 05:07:45 +000081
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000082void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000083 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 // If we don't have a declaration, or we have an invalid declaration,
86 // just return.
87 if (DG.isNull() || !DG.isSingleDecl())
88 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089
Douglas Gregor2eb1c572013-04-08 20:52:24 +000090 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
92 return;
93
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
96 if (!var) {
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
99 return;
100 }
John McCall31168b02011-06-15 23:02:42 +0000101
John McCalld4631322011-06-17 06:42:21 +0000102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000104 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000105
John McCalld4631322011-06-17 06:42:21 +0000106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000110 QualType type = var->getType();
111
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000119 }
120 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000121}
122
Richard Trieu99e1c952014-03-11 03:11:08 +0000123/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125///
126/// Adding a cast to void (or other expression wrappers) will prevent the
127/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000128static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000130 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000133 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000134 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000141 switch (Op->getOperator()) {
142 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000143 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000144 case OO_EqualEqual:
145 case OO_ExclaimEqual:
146 IsRelational = false;
147 break;
148 case OO_Less:
149 case OO_Greater:
150 case OO_GreaterEqual:
151 case OO_LessEqual:
152 IsRelational = true;
153 break;
154 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000159 } else {
160 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000161 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000162 }
163
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000168
Chandler Carruthe2669392011-08-17 09:34:37 +0000169 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000174 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000175 if (IsNotEqual)
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
178 else
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
181 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000182
183 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000184}
185
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
189
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000190 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000191 if (!E)
192 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000193
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
197 return;
198
Nico Weber0e631632015-10-27 19:47:40 +0000199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208
Eli Friedmanc11535c2012-05-24 00:47:05 +0000209 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000210 SourceLocation Loc;
211 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000213 return;
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattner6dc7e572012-08-31 22:39:21 +0000215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
218 // false positive.
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
220 return;
221
Nico Weber0e631632015-10-27 19:47:40 +0000222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
228 return;
229 }
230
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
233 // cases now.
234 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000236 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000239
Chandler Carruthe2669392011-08-17 09:34:37 +0000240 if (DiagnoseUnusedComparison(*this, E))
241 return;
242
Eli Friedmanc11535c2012-05-24 00:47:05 +0000243 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000245 if (E->getType()->isVoidType())
246 return;
247
Chris Lattner1a6babf2009-10-13 04:53:48 +0000248 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
251 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000252 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000257 return;
258 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000259 if (ShouldSuppress)
260 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000261 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
263 return;
264 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000265 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000270 } else if (ShouldSuppress)
271 return;
272
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
276 return;
277 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000279 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000282 return;
283 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
289 else
290 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000293 const Expr *E = FC->getSubExpr();
294 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
295 E = TE->getSubExpr();
296 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000297 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000298 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
299 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
300 if (!RD->getAttr<WarnUnusedAttr>())
301 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000302 }
John McCall2351cb92010-04-06 22:24:14 +0000303 // Diagnose "(void*) blah" as a typo for "(void) blah".
304 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
305 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
306 QualType T = TI->getType();
307
308 // We really do want to use the non-canonical type here.
309 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000310 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000311
312 Diag(Loc, diag::warn_unused_voidptr)
313 << FixItHint::CreateRemoval(TL.getStarLoc());
314 return;
315 }
316 }
317
Eli Friedmanc11535c2012-05-24 00:47:05 +0000318 if (E->isGLValue() && E->getType().isVolatileQualified()) {
319 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
320 return;
321 }
322
Craig Topperc3ec1492014-05-26 06:22:03 +0000323 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000324}
325
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000326void Sema::ActOnStartOfCompoundStmt() {
327 PushCompoundScope();
328}
329
330void Sema::ActOnFinishOfCompoundStmt() {
331 PopCompoundScope();
332}
333
334sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
335 return getCurFunction()->CompoundScopes.back();
336}
337
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000338StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
339 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
340 const unsigned NumElts = Elts.size();
341
Chris Lattnerd864daf2007-08-27 04:29:41 +0000342 // If we're in C89 mode, check that we don't have any decls after stmts. If
343 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000344 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000345 // Note that __extension__ can be around a decl.
346 unsigned i = 0;
347 // Skip over all declarations.
348 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
349 /*empty*/;
350
351 // We found the end of the list or a statement. Scan for another declstmt.
352 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
353 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chris Lattnerd864daf2007-08-27 04:29:41 +0000355 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000356 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000357 Diag(D->getLocation(), diag::ext_mixed_decls_code);
358 }
359 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000360 // Warn about unused expressions in statements.
361 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000362 // Ignore statements that are last in a statement expression.
363 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000364 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000365
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000366 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000367 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000368
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000369 // Check for suspicious empty body (null statement) in `for' and `while'
370 // statements. Don't do anything for template instantiations, this just adds
371 // noise.
372 if (NumElts != 0 && !CurrentInstantiationScope &&
373 getCurCompoundScope().HasEmptyLoopBodies) {
374 for (unsigned i = 0; i != NumElts - 1; ++i)
375 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
376 }
377
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000378 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000379}
380
John McCalldadc5752010-08-24 06:29:42 +0000381StmtResult
John McCallb268a282010-08-23 23:25:46 +0000382Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
383 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000384 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000385 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000386
John McCallaab3e412010-08-25 08:40:02 +0000387 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000388 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000389 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000390 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000391
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000392 ExprResult LHS =
393 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
394 if (!getLangOpts().CPlusPlus11)
395 return VerifyIntegerConstantExpression(E);
396 if (Expr *CondExpr =
397 getCurFunction()->SwitchStack.back()->getCond()) {
398 QualType CondType = CondExpr->getType();
399 llvm::APSInt TempVal;
400 return CheckConvertedConstantExpression(E, CondType, TempVal,
401 CCEK_CaseValue);
402 }
403 return ExprError();
404 });
405 if (LHS.isInvalid())
406 return StmtError();
407 LHSVal = LHS.get();
408
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000409 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000410 // C99 6.8.4.2p3: The expression shall be an integer constant.
411 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000412 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000413 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000414 if (!LHSVal)
415 return StmtError();
416 }
Richard Smithf8379a02012-01-18 23:55:52 +0000417
418 // GCC extension: The expression shall be an integer constant.
419
Richard Smithf4c51d92012-02-04 09:53:13 +0000420 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000421 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000422 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000423 }
424 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000425
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000426 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000427 getLangOpts().CPlusPlus11);
428 if (LHS.isInvalid())
429 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000430
Richard Smith5b555da2014-11-20 01:24:12 +0000431 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
432 getLangOpts().CPlusPlus11)
433 : ExprResult();
434 if (RHS.isInvalid())
435 return StmtError();
436
437 CaseStmt *CS = new (Context)
438 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000439 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000441}
442
Chris Lattner34a22092009-03-04 04:23:07 +0000443/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000444void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000445 DiagnoseUnusedExprResult(SubStmt);
446
Chris Lattner34a22092009-03-04 04:23:07 +0000447 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000448 CS->setSubStmt(SubStmt);
449}
450
John McCalldadc5752010-08-24 06:29:42 +0000451StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000452Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000453 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000454 DiagnoseUnusedExprResult(SubStmt);
455
John McCallaab3e412010-08-25 08:40:02 +0000456 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000457 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000458 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000459 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000460
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000461 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000462 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000463 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000464}
465
John McCalldadc5752010-08-24 06:29:42 +0000466StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000467Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
468 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000469 // If the label was multiply defined, reject it now.
470 if (TheDecl->getStmt()) {
471 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
472 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000473 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000474 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000475
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000476 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000477 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
478 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000479 if (!TheDecl->isGnuLocal()) {
480 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000481 if (!TheDecl->isMSAsmLabel()) {
482 // Don't update the location of MS ASM labels. These will result in
483 // a diagnostic, and changing the location here will mess that up.
484 TheDecl->setLocation(IdentLoc);
485 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000486 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000487 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000488}
489
Richard Smithc202b282012-04-14 00:33:13 +0000490StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000491 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000492 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000493 // Fill in the declaration and return it.
494 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000495 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000496}
497
Richard Trieufaca2d82016-02-18 23:58:40 +0000498namespace {
499class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
500 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
501 Sema &SemaRef;
502public:
503 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
504 void VisitBinaryOperator(BinaryOperator *E) {
505 if (E->getOpcode() == BO_Comma)
506 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
507 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
508 }
509};
510}
511
John McCalldadc5752010-08-24 06:29:42 +0000512StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000513Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
514 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000515 Stmt *thenStmt, SourceLocation ElseLoc,
516 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000517 if (Cond.isInvalid())
518 Cond = ConditionResult(
519 *this, nullptr,
520 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
521 Context.BoolTy, VK_RValue),
522 IfLoc),
523 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000524
Richard Smithb130fe72016-06-23 19:16:49 +0000525 Expr *CondExpr = Cond.get().second;
Richard Smith03a4aa32016-06-23 19:02:52 +0000526 if (!Diags.isIgnored(diag::warn_comma_operator,
Richard Smithb130fe72016-06-23 19:16:49 +0000527 CondExpr->getExprLoc()))
528 CommaVisitor(*this).Visit(CondExpr);
529
530 if (!elseStmt)
531 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
532 diag::warn_empty_if_body);
533
Richard Smitha547eb22016-07-14 00:11:03 +0000534 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
535 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000536}
537
538StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000539 Stmt *InitStmt, ConditionResult Cond,
540 Stmt *thenStmt, SourceLocation ElseLoc,
541 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000542 if (Cond.isInvalid())
543 return StmtError();
544
Erik Pilkington5cd57172016-08-16 17:44:11 +0000545 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Richard Smithb130fe72016-06-23 19:16:49 +0000546 getCurFunction()->setHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000547
548 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000549 DiagnoseUnusedExprResult(elseStmt);
550
Richard Smitha547eb22016-07-14 00:11:03 +0000551 return new (Context)
552 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
553 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000554}
Steve Naroff86272ea2007-05-29 02:14:17 +0000555
Chris Lattner67998452007-08-23 18:29:20 +0000556namespace {
557 struct CaseCompareFunctor {
558 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
559 const llvm::APSInt &RHS) {
560 return LHS.first < RHS;
561 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000562 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
563 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
564 return LHS.first < RHS.first;
565 }
Chris Lattner67998452007-08-23 18:29:20 +0000566 bool operator()(const llvm::APSInt &LHS,
567 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
568 return LHS < RHS.first;
569 }
570 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000571}
Chris Lattner67998452007-08-23 18:29:20 +0000572
Chris Lattner4b2ff022007-09-21 18:15:22 +0000573/// CmpCaseVals - Comparison predicate for sorting case values.
574///
575static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
576 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
577 if (lhs.first < rhs.first)
578 return true;
579
580 if (lhs.first == rhs.first &&
581 lhs.second->getCaseLoc().getRawEncoding()
582 < rhs.second->getCaseLoc().getRawEncoding())
583 return true;
584 return false;
585}
586
Douglas Gregorbd6839732010-02-08 22:24:16 +0000587/// CmpEnumVals - Comparison predicate for sorting enumeration values.
588///
589static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
590 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
591{
592 return lhs.first < rhs.first;
593}
594
595/// EqEnumVals - Comparison preficate for uniqing enumeration values.
596///
597static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
598 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
599{
600 return lhs.first == rhs.first;
601}
602
Chris Lattnera96d4272009-10-16 16:45:22 +0000603/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
604/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000605static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
606 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
607 expr = cleanups->getSubExpr();
608 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
609 if (impcast->getCastKind() != CK_IntegralCast) break;
610 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000611 }
612 return expr->getType();
613}
614
Richard Smith03a4aa32016-06-23 19:02:52 +0000615ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000616 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
617 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000618
Douglas Gregore2b37442012-05-04 22:38:52 +0000619 public:
620 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000621 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
622 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000623
Craig Toppere14c0f82014-03-12 04:55:44 +0000624 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
625 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000626 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
627 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000628
Craig Toppere14c0f82014-03-12 04:55:44 +0000629 SemaDiagnosticBuilder diagnoseIncomplete(
630 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000631 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
632 << T << Cond->getSourceRange();
633 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000634
Craig Toppere14c0f82014-03-12 04:55:44 +0000635 SemaDiagnosticBuilder diagnoseExplicitConv(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000637 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
638 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000639
Craig Toppere14c0f82014-03-12 04:55:44 +0000640 SemaDiagnosticBuilder noteExplicitConv(
641 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000642 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
643 << ConvTy->isEnumeralType() << ConvTy;
644 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000645
Craig Toppere14c0f82014-03-12 04:55:44 +0000646 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
647 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000648 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
649 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000650
Craig Toppere14c0f82014-03-12 04:55:44 +0000651 SemaDiagnosticBuilder noteAmbiguous(
652 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000653 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
654 << ConvTy->isEnumeralType() << ConvTy;
655 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000656
Craig Toppere14c0f82014-03-12 04:55:44 +0000657 SemaDiagnosticBuilder diagnoseConversion(
658 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000659 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000660 }
661 } SwitchDiagnoser(Cond);
662
Richard Smith03a4aa32016-06-23 19:02:52 +0000663 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000664 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000665 if (CondResult.isInvalid())
666 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667
John McCall5939b162011-08-06 07:30:58 +0000668 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smith03a4aa32016-06-23 19:02:52 +0000669 return UsualUnaryConversions(CondResult.get());
670}
John McCall5939b162011-08-06 07:30:58 +0000671
Richard Smithc7a05a92016-06-29 21:17:59 +0000672StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
673 Stmt *InitStmt, ConditionResult Cond) {
Richard Smith03a4aa32016-06-23 19:02:52 +0000674 if (Cond.isInvalid())
Meador Ingef0af05c2015-06-25 22:06:40 +0000675 return StmtError();
John McCalla95172b2010-08-01 00:26:45 +0000676
John McCallaab3e412010-08-25 08:40:02 +0000677 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Richard Smitha547eb22016-07-14 00:11:03 +0000679 SwitchStmt *SS = new (Context)
680 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
John McCallaab3e412010-08-25 08:40:02 +0000681 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000682 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000683}
684
Gabor Greif16e02862010-10-01 22:05:14 +0000685static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000686 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000687 Val.setIsSigned(IsSigned);
688}
689
Richard Smith077d0832014-08-04 00:40:48 +0000690/// Check the specified case value is in range for the given unpromoted switch
691/// type.
692static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
693 unsigned UnpromotedWidth, bool UnpromotedSign) {
694 // If the case value was signed and negative and the switch expression is
695 // unsigned, don't bother to warn: this is implementation-defined behavior.
696 // FIXME: Introduce a second, default-ignored warning for this case?
697 if (UnpromotedWidth < Val.getBitWidth()) {
698 llvm::APSInt ConvVal(Val);
699 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
700 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
701 // FIXME: Use different diagnostics for overflow in conversion to promoted
702 // type versus "switch expression cannot have this value". Use proper
703 // IntRange checking rather than just looking at the unpromoted type here.
704 if (ConvVal != Val)
705 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
706 << ConvVal.toString(10);
707 }
708}
709
Alexis Hunt724f14e2014-11-28 00:53:20 +0000710typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
711
Dmitri Gribenko58683752013-12-05 22:52:07 +0000712/// Returns true if we should emit a diagnostic about this case expression not
713/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000714static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000715 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000716 const Expr *CaseExpr,
717 EnumValsTy::iterator &EI,
718 EnumValsTy::iterator &EIEnd,
719 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000720 if (!ED->isClosed())
721 return false;
722
Alexis Hunt724f14e2014-11-28 00:53:20 +0000723 if (const DeclRefExpr *DRE =
724 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000725 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000726 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000727 QualType EnumType = S.Context.getTypeDeclType(ED);
728 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
729 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000730 return false;
731 }
732 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000733
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000734 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000735 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000736
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000737 while (EI != EIEnd && EI->first < Val)
738 EI++;
739
740 if (EI != EIEnd && EI->first == Val)
741 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000742
Dmitri Gribenko58683752013-12-05 22:52:07 +0000743 return true;
744}
745
John McCalldadc5752010-08-24 06:29:42 +0000746StmtResult
John McCallb268a282010-08-23 23:25:46 +0000747Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
748 Stmt *BodyStmt) {
749 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000750 assert(SS == getCurFunction()->SwitchStack.back() &&
751 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000752
David Majnemer418ad3f2014-12-15 07:46:12 +0000753 getCurFunction()->SwitchStack.pop_back();
754
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000755 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000756 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000757
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000758 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000759 if (!CondExpr) return StmtError();
760
761 QualType CondType = CondExpr->getType();
762
John McCalld3dfbd62010-05-18 03:19:21 +0000763 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000764 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000765 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000766
Chris Lattnera96d4272009-10-16 16:45:22 +0000767 // C++ 6.4.2.p2:
768 // Integral promotions are performed (on the switch condition).
769 //
770 // A case value unrepresentable by the original switch condition
771 // type (before the promotion) doesn't make sense, even when it can
772 // be represented by the promoted type. Therefore we need to find
773 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000774 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000775 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000777 // appropriate type now, just return an error.
778 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000779 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000780
Chris Lattner4ebae652010-04-16 23:34:13 +0000781 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000782 // switch(bool_expr) {...} is often a programmer error, e.g.
783 // switch(n && mask) { ... } // Doh - should be "n & mask".
784 // One can always use an if statement instead of switch(bool_expr).
785 Diag(SwitchLoc, diag::warn_bool_switch_condition)
786 << CondExpr->getSourceRange();
787 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000788 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000789
Richard Smith077d0832014-08-04 00:40:48 +0000790 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000791 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000792 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000793 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000794 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
795 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
796
797 // Get the width and signedness that the condition might actually have, for
798 // warning purposes.
799 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
800 // type.
801 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000802 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000803 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000804 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000806 // Accumulate all of the case values in a vector so that we can sort them
807 // and detect duplicates. This vector contains the APInt for the case after
808 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000809 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000810 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000811
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000812 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000813 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
814 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000815
Craig Topperc3ec1492014-05-26 06:22:03 +0000816 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattner10cb5e52007-08-23 06:23:56 +0000818 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000819
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000820 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000821 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000822
Anders Carlsson51873c22007-07-22 07:07:56 +0000823 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000824 if (TheDefaultStmt) {
825 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000826 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000827
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000828 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000829 // we'll return a valid AST. This requires recursing down the AST and
830 // finding it, not something we are set up to do right now. For now,
831 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000832 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000833 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000834 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000836 } else {
837 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattnera65e1f32008-01-16 19:17:22 +0000839 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000840
841 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
842 HasDependentValue = true;
843 break;
844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Richard Smithf8379a02012-01-18 23:55:52 +0000846 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000847
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000848 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000849 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
850 // constant expression of the promoted type of the switch condition.
851 ExprResult ConvLo =
852 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
853 if (ConvLo.isInvalid()) {
854 CaseListIsErroneous = true;
855 continue;
856 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000857 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000858 } else {
859 // We already verified that the expression has a i-c-e value (C99
860 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000861 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000862
863 // If the LHS is not the same type as the condition, insert an implicit
864 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000865 Lo = DefaultLvalueConversion(Lo).get();
866 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000867 }
868
Richard Smith077d0832014-08-04 00:40:48 +0000869 // Check the unconverted value is within the range of possible values of
870 // the switch expression.
871 checkCaseValue(*this, Lo->getLocStart(), LoVal,
872 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
873
874 // Convert the value to the same width/sign as the condition.
875 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000876
Chris Lattnera65e1f32008-01-16 19:17:22 +0000877 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000878
Chris Lattner10cb5e52007-08-23 06:23:56 +0000879 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000880 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000881 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000882 CS->getRHS()->isValueDependent()) {
883 HasDependentValue = true;
884 break;
885 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000886 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000887 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000888 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000889 }
890 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000891
892 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000893 // If we don't have a default statement, check whether the
894 // condition is constant.
895 llvm::APSInt ConstantCondValue;
896 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000897 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000898 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
899 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000900 assert(!HasConstantCond ||
901 (ConstantCondValue.getBitWidth() == CondWidth &&
902 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000903 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000904 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000905
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000906 // Sort all the scalar case values so we can easily detect duplicates.
907 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
908
909 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000910 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
911 if (ShouldCheckConstantCond &&
912 CaseVals[i].first == ConstantCondValue)
913 ShouldCheckConstantCond = false;
914
915 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000916 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000917 // First, determine if either case value has a name
918 StringRef PrevString, CurrString;
919 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
920 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
921 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
922 PrevString = DeclRef->getDecl()->getName();
923 }
924 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
925 CurrString = DeclRef->getDecl()->getName();
926 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000927 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000928 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000929
930 if (PrevString == CurrString)
931 Diag(CaseVals[i].second->getLHS()->getLocStart(),
932 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000933 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000934 else
935 Diag(CaseVals[i].second->getLHS()->getLocStart(),
936 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000937 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
938 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000939 CaseValStr;
940
John McCalld3dfbd62010-05-18 03:19:21 +0000941 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000942 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000943 // FIXME: We really want to remove the bogus case stmt from the
944 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000945 CaseListIsErroneous = true;
946 }
947 }
948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000950 // Detect duplicate case ranges, which usually don't exist at all in
951 // the first place.
952 if (!CaseRanges.empty()) {
953 // Sort all the case ranges by their low value so we can easily detect
954 // overlaps between ranges.
955 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000956
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000957 // Scan the ranges, computing the high values and removing empty ranges.
958 std::vector<llvm::APSInt> HiVals;
959 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000960 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000961 CaseStmt *CR = CaseRanges[i].second;
962 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000963 llvm::APSInt HiVal;
964
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000965 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000966 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
967 // constant expression of the promoted type of the switch condition.
968 ExprResult ConvHi =
969 CheckConvertedConstantExpression(Hi, CondType, HiVal,
970 CCEK_CaseValue);
971 if (ConvHi.isInvalid()) {
972 CaseListIsErroneous = true;
973 continue;
974 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000975 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000976 } else {
977 HiVal = Hi->EvaluateKnownConstInt(Context);
978
979 // If the RHS is not the same type as the condition, insert an
980 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000981 Hi = DefaultLvalueConversion(Hi).get();
982 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000983 }
Mike Stump11289f42009-09-09 15:08:12 +0000984
Richard Smith077d0832014-08-04 00:40:48 +0000985 // Check the unconverted value is within the range of possible values of
986 // the switch expression.
987 checkCaseValue(*this, Hi->getLocStart(), HiVal,
988 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
989
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000990 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000991 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000992
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000993 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000994
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000996 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000997 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
998 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000999 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001000 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001001 --i;
1002 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 continue;
1004 }
John McCalld3dfbd62010-05-18 03:19:21 +00001005
1006 if (ShouldCheckConstantCond &&
1007 LoVal <= ConstantCondValue &&
1008 ConstantCondValue <= HiVal)
1009 ShouldCheckConstantCond = false;
1010
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001011 HiVals.push_back(HiVal);
1012 }
Mike Stump11289f42009-09-09 15:08:12 +00001013
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001014 // Rescan the ranges, looking for overlap with singleton values and other
1015 // ranges. Since the range list is sorted, we only need to compare case
1016 // ranges with their neighbors.
1017 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1018 llvm::APSInt &CRLo = CaseRanges[i].first;
1019 llvm::APSInt &CRHi = HiVals[i];
1020 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001021
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001022 // Check to see whether the case range overlaps with any
1023 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001024 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001025 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001027 // Find the smallest value >= the lower bound. If I is in the
1028 // case range, then we have overlap.
1029 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1030 CaseVals.end(), CRLo,
1031 CaseCompareFunctor());
1032 if (I != CaseVals.end() && I->first < CRHi) {
1033 OverlapVal = I->first; // Found overlap with scalar.
1034 OverlapStmt = I->second;
1035 }
Mike Stump11289f42009-09-09 15:08:12 +00001036
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001037 // Find the smallest value bigger than the upper bound.
1038 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1039 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1040 OverlapVal = (I-1)->first; // Found overlap with scalar.
1041 OverlapStmt = (I-1)->second;
1042 }
Mike Stump11289f42009-09-09 15:08:12 +00001043
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001044 // Check to see if this case stmt overlaps with the subsequent
1045 // case range.
1046 if (i && CRLo <= HiVals[i-1]) {
1047 OverlapVal = HiVals[i-1]; // Found overlap with range.
1048 OverlapStmt = CaseRanges[i-1].second;
1049 }
Mike Stump11289f42009-09-09 15:08:12 +00001050
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001051 if (OverlapStmt) {
1052 // If we have a duplicate, report it.
1053 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1054 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001055 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001056 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001057 // FIXME: We really want to remove the bogus case stmt from the
1058 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001059 CaseListIsErroneous = true;
1060 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001061 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001062 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001063
John McCalld3dfbd62010-05-18 03:19:21 +00001064 // Complain if we have a constant condition and we didn't find a match.
1065 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1066 // TODO: it would be nice if we printed enums as enums, chars as
1067 // chars, etc.
1068 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1069 << ConstantCondValue.toString(10)
1070 << CondExpr->getSourceRange();
1071 }
1072
1073 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001074 // values. We only issue a warning if there is not 'default:', but
1075 // we still do the analysis to preserve this information in the AST
1076 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001077 //
Chris Lattner51679082010-09-16 17:09:42 +00001078 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001079
Douglas Gregorbd6839732010-02-08 22:24:16 +00001080 // If switch has default case, then ignore it.
Alex Lorenz660195f2016-12-08 14:46:05 +00001081 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1082 ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001083 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001084 EnumValsTy EnumVals;
1085
John McCalld3dfbd62010-05-18 03:19:21 +00001086 // Gather all enum values, set their type and sort them,
1087 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001088 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001089 llvm::APSInt Val = EDI->getInitVal();
1090 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001091 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001092 }
1093 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001094 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001095 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001096
1097 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001098 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001099 CI != CaseVals.end(); CI++) {
1100 Expr *CaseExpr = CI->second->getLHS();
1101 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1102 CI->first))
1103 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1104 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001105 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001106
David Blaikiee476f972012-01-22 02:31:55 +00001107 // See which of case ranges aren't in enum
1108 EI = EnumVals.begin();
1109 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001110 RI != CaseRanges.end(); RI++) {
1111 Expr *CaseExpr = RI->second->getLHS();
1112 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1113 RI->first))
1114 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1115 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001116
Chad Rosier02a84392012-08-10 17:56:09 +00001117 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001118 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1119 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001120
1121 CaseExpr = RI->second->getRHS();
1122 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1123 Hi))
1124 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1125 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001127
Ted Kremenekc42f3452010-09-09 00:05:53 +00001128 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001129 auto CI = CaseVals.begin();
1130 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001131 bool hasCasesNotInSwitch = false;
1132
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001133 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134
Alexis Hunt724f14e2014-11-28 00:53:20 +00001135 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001136 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001137 while (CI != CaseVals.end() && CI->first < EI->first)
1138 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Douglas Gregorbd6839732010-02-08 22:24:16 +00001140 if (CI != CaseVals.end() && CI->first == EI->first)
1141 continue;
1142
Ted Kremenekc42f3452010-09-09 00:05:53 +00001143 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001144 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001145 llvm::APSInt Hi =
1146 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001147 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001148 if (EI->first <= Hi)
1149 break;
1150 }
1151
Ted Kremenekc42f3452010-09-09 00:05:53 +00001152 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001153 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001154 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001155 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001158 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001159 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001160
Chris Lattner51679082010-09-16 17:09:42 +00001161 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001162 if (!UnhandledNames.empty()) {
1163 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1164 TheDefaultStmt ? diag::warn_def_missing_case
1165 : diag::warn_missing_case)
1166 << (int)UnhandledNames.size();
1167
1168 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1169 I != E; ++I)
1170 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001171 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001172
1173 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001174 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001175 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001176 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001177
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001178 if (BodyStmt)
1179 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1180 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001181
Mike Stump87c57ac2009-05-16 07:39:55 +00001182 // FIXME: If the case list was broken is some way, we don't have a good system
1183 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001184 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001185 return StmtError();
1186
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001187 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001188}
1189
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001190void
1191Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1192 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001193 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001194 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001195
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001196 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001197 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001198 SrcType->isIntegerType()) {
1199 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1200 SrcExpr->isIntegerConstantExpr(Context)) {
1201 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001202 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001203 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1204
1205 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001206 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001207 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001208
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001209 if (!ED->isClosed())
1210 return;
1211
Alexis Hunt724f14e2014-11-28 00:53:20 +00001212 if (ED->hasAttr<FlagEnumAttr>()) {
1213 if (!IsValueInFlagEnum(ED, RhsVal, true))
1214 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001215 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001216 } else {
1217 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1218 EnumValsTy;
1219 EnumValsTy EnumVals;
1220
1221 // Gather all enum values, set their type and sort them,
1222 // allowing easier comparison with rhs constant.
1223 for (auto *EDI : ED->enumerators()) {
1224 llvm::APSInt Val = EDI->getInitVal();
1225 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1226 EnumVals.push_back(std::make_pair(Val, EDI));
1227 }
1228 if (EnumVals.empty())
1229 return;
1230 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1231 EnumValsTy::iterator EIend =
1232 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1233
1234 // See which values aren't in the enum.
1235 EnumValsTy::const_iterator EI = EnumVals.begin();
1236 while (EI != EIend && EI->first < RhsVal)
1237 EI++;
1238 if (EI == EIend || EI->first != RhsVal) {
1239 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1240 << DstType.getUnqualifiedType();
1241 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001242 }
1243 }
1244 }
1245}
1246
Richard Smith03a4aa32016-06-23 19:02:52 +00001247StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1248 Stmt *Body) {
1249 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001250 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251
Richard Smith03a4aa32016-06-23 19:02:52 +00001252 auto CondVal = Cond.get();
1253 CheckBreakContinueBinding(CondVal.second);
1254
1255 if (CondVal.second &&
1256 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1257 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001258
John McCallb268a282010-08-23 23:25:46 +00001259 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001260
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001261 if (isa<NullStmt>(Body))
1262 getCurCompoundScope().setHasEmptyLoopBodies();
1263
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001264 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001265 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001266}
1267
John McCalldadc5752010-08-24 06:29:42 +00001268StmtResult
John McCallb268a282010-08-23 23:25:46 +00001269Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001270 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001271 Expr *Cond, SourceLocation CondRParen) {
1272 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001273
Serge Pavlov09f99242014-01-23 15:05:00 +00001274 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001275 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001276 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001277 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001278 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001279
Richard Smith945f8d32013-01-14 22:39:08 +00001280 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001281 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001282 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001283 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284
John McCallb268a282010-08-23 23:25:46 +00001285 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001286
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001287 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001288}
1289
Richard Trieu451a5db2012-04-30 18:01:30 +00001290namespace {
1291 // This visitor will traverse a conditional statement and store all
1292 // the evaluated decls into a vector. Simple is set to true if none
1293 // of the excluded constructs are used.
1294 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001295 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001296 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001297 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001298 public:
1299 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001300
Craig Topper4dd9b432014-08-17 23:49:53 +00001301 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001302 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001303 Inherited(S.Context),
1304 Decls(Decls),
1305 Ranges(Ranges),
1306 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001307
Richard Trieu9d228802013-05-31 22:46:45 +00001308 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001309
Richard Trieu9d228802013-05-31 22:46:45 +00001310 // Replaces the method in EvaluatedExprVisitor.
1311 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001312 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001313 }
1314
1315 // Any Stmt not whitelisted will cause the condition to be marked complex.
1316 void VisitStmt(Stmt *S) {
1317 Simple = false;
1318 }
1319
1320 void VisitBinaryOperator(BinaryOperator *E) {
1321 Visit(E->getLHS());
1322 Visit(E->getRHS());
1323 }
1324
1325 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001326 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001327 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001328
Richard Trieu9d228802013-05-31 22:46:45 +00001329 void VisitUnaryOperator(UnaryOperator *E) {
1330 // Skip checking conditionals with derefernces.
1331 if (E->getOpcode() == UO_Deref)
1332 Simple = false;
1333 else
1334 Visit(E->getSubExpr());
1335 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001336
Richard Trieu9d228802013-05-31 22:46:45 +00001337 void VisitConditionalOperator(ConditionalOperator *E) {
1338 Visit(E->getCond());
1339 Visit(E->getTrueExpr());
1340 Visit(E->getFalseExpr());
1341 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 void VisitParenExpr(ParenExpr *E) {
1344 Visit(E->getSubExpr());
1345 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1348 Visit(E->getOpaqueValue()->getSourceExpr());
1349 Visit(E->getFalseExpr());
1350 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001351
Richard Trieu9d228802013-05-31 22:46:45 +00001352 void VisitIntegerLiteral(IntegerLiteral *E) { }
1353 void VisitFloatingLiteral(FloatingLiteral *E) { }
1354 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1355 void VisitCharacterLiteral(CharacterLiteral *E) { }
1356 void VisitGNUNullExpr(GNUNullExpr *E) { }
1357 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001358
Richard Trieu9d228802013-05-31 22:46:45 +00001359 void VisitDeclRefExpr(DeclRefExpr *E) {
1360 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1361 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001362
Richard Trieu9d228802013-05-31 22:46:45 +00001363 Ranges.push_back(E->getSourceRange());
1364
1365 Decls.insert(VD);
1366 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001367
1368 }; // end class DeclExtractor
1369
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001370 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001371 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001372 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001373 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001374 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001375
Richard Trieu9d228802013-05-31 22:46:45 +00001376 public:
1377 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001378
Craig Topper4dd9b432014-08-17 23:49:53 +00001379 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001380 Stmt *Statement) :
1381 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1382 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001383
Richard Trieu9d228802013-05-31 22:46:45 +00001384 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001385 }
1386
Richard Trieu9d228802013-05-31 22:46:45 +00001387 void VisitReturnStmt(ReturnStmt *S) {
1388 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001389 }
1390
Richard Trieu9d228802013-05-31 22:46:45 +00001391 void VisitBreakStmt(BreakStmt *S) {
1392 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001393 }
1394
Richard Trieu9d228802013-05-31 22:46:45 +00001395 void VisitGotoStmt(GotoStmt *S) {
1396 FoundDecl = true;
1397 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001398
Richard Trieu9d228802013-05-31 22:46:45 +00001399 void VisitCastExpr(CastExpr *E) {
1400 if (E->getCastKind() == CK_LValueToRValue)
1401 CheckLValueToRValueCast(E->getSubExpr());
1402 else
1403 Visit(E->getSubExpr());
1404 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001405
Richard Trieu9d228802013-05-31 22:46:45 +00001406 void CheckLValueToRValueCast(Expr *E) {
1407 E = E->IgnoreParenImpCasts();
1408
1409 if (isa<DeclRefExpr>(E)) {
1410 return;
1411 }
1412
1413 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1414 Visit(CO->getCond());
1415 CheckLValueToRValueCast(CO->getTrueExpr());
1416 CheckLValueToRValueCast(CO->getFalseExpr());
1417 return;
1418 }
1419
1420 if (BinaryConditionalOperator *BCO =
1421 dyn_cast<BinaryConditionalOperator>(E)) {
1422 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1423 CheckLValueToRValueCast(BCO->getFalseExpr());
1424 return;
1425 }
1426
1427 Visit(E);
1428 }
1429
1430 void VisitDeclRefExpr(DeclRefExpr *E) {
1431 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1432 if (Decls.count(VD))
1433 FoundDecl = true;
1434 }
1435
Steven Wu92910f62016-03-10 02:02:48 +00001436 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1437 // Only need to visit the semantics for POE.
1438 // SyntaticForm doesn't really use the Decal.
1439 for (auto *S : POE->semantics()) {
1440 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1441 // Look past the OVE into the expression it binds.
1442 Visit(OVE->getSourceExpr());
1443 else
1444 Visit(S);
1445 }
1446 }
1447
Richard Trieu9d228802013-05-31 22:46:45 +00001448 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001449
1450 }; // end class DeclMatcher
1451
1452 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1453 Expr *Third, Stmt *Body) {
1454 // Condition is empty
1455 if (!Second) return;
1456
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001457 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1458 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001459 return;
1460
1461 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1462 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001463 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001464 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001465 DE.Visit(Second);
1466
1467 // Don't analyze complex conditionals.
1468 if (!DE.isSimple()) return;
1469
1470 // No decls found.
1471 if (Decls.size() == 0) return;
1472
Richard Trieu0030f1d2012-05-04 03:01:54 +00001473 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001474 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1475 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001476 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001477 if ((*I)->getType().isVolatileQualified() ||
1478 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001479
1480 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1481 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1482 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1483 return;
1484
1485 // Load decl names into diagnostic.
1486 if (Decls.size() > 4)
1487 PDiag << 0;
1488 else {
1489 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001490 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1491 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001492 I != E; ++I)
1493 PDiag << (*I)->getDeclName();
1494 }
1495
1496 // Load SourceRanges into diagnostic if there is room.
1497 // Otherwise, load the SourceRange of the conditional expression.
1498 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001499 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001500 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001501 I != E; ++I)
1502 PDiag << *I;
1503 else
1504 PDiag << Second->getSourceRange();
1505
1506 S.Diag(Ranges.begin()->getBegin(), PDiag);
1507 }
1508
Richard Trieu4e7c9622013-08-06 21:31:54 +00001509 // If Statement is an incemement or decrement, return true and sets the
1510 // variables Increment and DRE.
1511 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1512 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001513 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1514 if (!Cleanups->cleanupsHaveSideEffects())
1515 Statement = Cleanups->getSubExpr();
1516
Richard Trieu4e7c9622013-08-06 21:31:54 +00001517 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1518 switch (UO->getOpcode()) {
1519 default: return false;
1520 case UO_PostInc:
1521 case UO_PreInc:
1522 Increment = true;
1523 break;
1524 case UO_PostDec:
1525 case UO_PreDec:
1526 Increment = false;
1527 break;
1528 }
1529 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1530 return DRE;
1531 }
1532
1533 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1534 FunctionDecl *FD = Call->getDirectCallee();
1535 if (!FD || !FD->isOverloadedOperator()) return false;
1536 switch (FD->getOverloadedOperator()) {
1537 default: return false;
1538 case OO_PlusPlus:
1539 Increment = true;
1540 break;
1541 case OO_MinusMinus:
1542 Increment = false;
1543 break;
1544 }
1545 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1546 return DRE;
1547 }
1548
1549 return false;
1550 }
1551
Serge Pavlov09f99242014-01-23 15:05:00 +00001552 // A visitor to determine if a continue or break statement is a
1553 // subexpression.
1554 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1555 SourceLocation BreakLoc;
1556 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001557 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001558 BreakContinueFinder(Sema &S, Stmt* Body) :
1559 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001560 Visit(Body);
1561 }
1562
Serge Pavlov09f99242014-01-23 15:05:00 +00001563 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001564
1565 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001566 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001567 }
1568
Serge Pavlov09f99242014-01-23 15:05:00 +00001569 void VisitBreakStmt(BreakStmt* E) {
1570 BreakLoc = E->getBreakLoc();
1571 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001572
Serge Pavlov09f99242014-01-23 15:05:00 +00001573 bool ContinueFound() { return ContinueLoc.isValid(); }
1574 bool BreakFound() { return BreakLoc.isValid(); }
1575 SourceLocation GetContinueLoc() { return ContinueLoc; }
1576 SourceLocation GetBreakLoc() { return BreakLoc; }
1577
1578 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001579
1580 // Emit a warning when a loop increment/decrement appears twice per loop
1581 // iteration. The conditions which trigger this warning are:
1582 // 1) The last statement in the loop body and the third expression in the
1583 // for loop are both increment or both decrement of the same variable
1584 // 2) No continue statements in the loop body.
1585 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1586 // Return when there is nothing to check.
1587 if (!Body || !Third) return;
1588
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001589 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1590 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001591 return;
1592
1593 // Get the last statement from the loop body.
1594 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1595 if (!CS || CS->body_empty()) return;
1596 Stmt *LastStmt = CS->body_back();
1597 if (!LastStmt) return;
1598
1599 bool LoopIncrement, LastIncrement;
1600 DeclRefExpr *LoopDRE, *LastDRE;
1601
1602 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1603 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1604
1605 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001606 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001607 if (LoopIncrement != LastIncrement ||
1608 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1609
Serge Pavlov09f99242014-01-23 15:05:00 +00001610 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001611
1612 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1613 << LastDRE->getDecl() << LastIncrement;
1614 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1615 << LoopIncrement;
1616 }
1617
Richard Trieu451a5db2012-04-30 18:01:30 +00001618} // end namespace
1619
Serge Pavlov09f99242014-01-23 15:05:00 +00001620
1621void Sema::CheckBreakContinueBinding(Expr *E) {
1622 if (!E || getLangOpts().CPlusPlus)
1623 return;
1624 BreakContinueFinder BCFinder(*this, E);
1625 Scope *BreakParent = CurScope->getBreakParent();
1626 if (BCFinder.BreakFound() && BreakParent) {
1627 if (BreakParent->getFlags() & Scope::SwitchScope) {
1628 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1629 } else {
1630 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1631 << "break";
1632 }
1633 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1634 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1635 << "continue";
1636 }
1637}
1638
Richard Smith03a4aa32016-06-23 19:02:52 +00001639StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1640 Stmt *First, ConditionResult Second,
1641 FullExprArg third, SourceLocation RParenLoc,
1642 Stmt *Body) {
1643 if (Second.isInvalid())
1644 return StmtError();
1645
David Blaikiebbafb8a2012-03-11 07:00:24 +00001646 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001647 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001648 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1649 // declare identifiers for objects having storage class 'auto' or
1650 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001651 for (auto *DI : DS->decls()) {
1652 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001653 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001654 VD = nullptr;
1655 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001656 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1657 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001658 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001659 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001660 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001661 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001662
Richard Smith03a4aa32016-06-23 19:02:52 +00001663 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001664 CheckBreakContinueBinding(third.get());
1665
Richard Smith03a4aa32016-06-23 19:02:52 +00001666 if (!Second.get().first)
1667 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1668 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001669 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001670
Richard Smith03a4aa32016-06-23 19:02:52 +00001671 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001672 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001673 Second.get().second->getExprLoc()))
1674 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001675
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001676 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677
Anders Carlsson1682af52009-08-01 01:39:59 +00001678 DiagnoseUnusedExprResult(First);
1679 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001680 DiagnoseUnusedExprResult(Body);
1681
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001682 if (isa<NullStmt>(Body))
1683 getCurCompoundScope().setHasEmptyLoopBodies();
1684
Richard Smith03a4aa32016-06-23 19:02:52 +00001685 return new (Context)
1686 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1687 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001688}
1689
John McCall34376a62010-12-04 03:47:34 +00001690/// In an Objective C collection iteration statement:
1691/// for (x in y)
1692/// x can be an arbitrary l-value expression. Bind it up as a
1693/// full-expression.
1694StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001695 // Reduce placeholder expressions here. Note that this rejects the
1696 // use of pseudo-object l-values in this position.
1697 ExprResult result = CheckPlaceholderExpr(E);
1698 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001699 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001700
Richard Smith945f8d32013-01-14 22:39:08 +00001701 ExprResult FullExpr = ActOnFinishFullExpr(E);
1702 if (FullExpr.isInvalid())
1703 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001704 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001705}
1706
John McCall53848232011-07-27 01:07:15 +00001707ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001708Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1709 if (!collection)
1710 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001711
Kaelyn Takata15867822014-11-21 18:48:04 +00001712 ExprResult result = CorrectDelayedTyposInExpr(collection);
1713 if (!result.isUsable())
1714 return ExprError();
1715 collection = result.get();
1716
John McCall53848232011-07-27 01:07:15 +00001717 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001718 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001719
1720 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001721 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001722 if (result.isInvalid())
1723 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001724 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001725
1726 // The operand needs to have object-pointer type.
1727 // TODO: should we do a contextual conversion?
1728 const ObjCObjectPointerType *pointerType =
1729 collection->getType()->getAs<ObjCObjectPointerType>();
1730 if (!pointerType)
1731 return Diag(forLoc, diag::err_collection_expr_type)
1732 << collection->getType() << collection->getSourceRange();
1733
1734 // Check that the operand provides
1735 // - countByEnumeratingWithState:objects:count:
1736 const ObjCObjectType *objectType = pointerType->getObjectType();
1737 ObjCInterfaceDecl *iface = objectType->getInterface();
1738
1739 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001740 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001741 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001742 (getLangOpts().ObjCAutoRefCount
1743 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1744 diag::err_arc_collection_forward, collection)
1745 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001746 // Otherwise, if we have any useful type information, check that
1747 // the type declares the appropriate method.
1748 } else if (iface || !objectType->qual_empty()) {
1749 IdentifierInfo *selectorIdents[] = {
1750 &Context.Idents.get("countByEnumeratingWithState"),
1751 &Context.Idents.get("objects"),
1752 &Context.Idents.get("count")
1753 };
1754 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1755
Craig Topperc3ec1492014-05-26 06:22:03 +00001756 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001757
1758 // If there's an interface, look in both the public and private APIs.
1759 if (iface) {
1760 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001761 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001762 }
1763
1764 // Also check protocol qualifiers.
1765 if (!method)
1766 method = LookupMethodInQualifiedType(selector, pointerType,
1767 /*instance*/ true);
1768
1769 // If we didn't find it anywhere, give up.
1770 if (!method) {
1771 Diag(forLoc, diag::warn_collection_expr_type)
1772 << collection->getType() << selector << collection->getSourceRange();
1773 }
1774
1775 // TODO: check for an incompatible signature?
1776 }
1777
1778 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001779 return collection;
John McCall53848232011-07-27 01:07:15 +00001780}
1781
John McCalldadc5752010-08-24 06:29:42 +00001782StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001783Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001784 Stmt *First, Expr *collection,
1785 SourceLocation RParenLoc) {
Akira Hatanaka39013772017-04-19 17:54:08 +00001786 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001787
1788 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001789 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001790
Fariborz Jahanian93977672008-01-10 20:33:58 +00001791 if (First) {
1792 QualType FirstType;
1793 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001794 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001795 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1796 diag::err_toomany_element_decls));
1797
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001798 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1799 if (!D || D->isInvalidDecl())
1800 return StmtError();
1801
John McCall31168b02011-06-15 23:02:42 +00001802 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001803 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1804 // declare identifiers for objects having storage class 'auto' or
1805 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001806 if (!D->hasLocalStorage())
1807 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001808 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001809
1810 // If the type contained 'auto', deduce the 'auto' to 'id'.
1811 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001812 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1813 VK_RValue);
1814 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001815 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1816 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001817 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001818 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001819 D->setInvalidDecl();
1820 return StmtError();
1821 }
1822
Richard Smith061f1e22013-04-30 21:23:01 +00001823 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001824
Richard Smith51ec0cf2017-02-21 01:17:38 +00001825 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001826 SourceLocation Loc =
1827 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001828 Diag(Loc, diag::warn_auto_var_is_id)
1829 << D->getDeclName();
1830 }
1831 }
1832
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001833 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001834 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001835 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001836 return StmtError(Diag(First->getLocStart(),
1837 diag::err_selector_element_not_lvalue)
1838 << First->getSourceRange());
1839
Mike Stump11289f42009-09-09 15:08:12 +00001840 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001841 if (FirstType.isConstQualified())
1842 Diag(ForLoc, diag::err_selector_element_const_type)
1843 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001844 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001845 if (!FirstType->isDependentType() &&
1846 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001847 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001848 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1849 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001850 }
Chad Rosier02a84392012-08-10 17:56:09 +00001851
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001852 if (CollectionExprResult.isInvalid())
1853 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001854
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001855 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001856 if (CollectionExprResult.isInvalid())
1857 return StmtError();
1858
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001859 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1860 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001861}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001862
Richard Smith02e85f32011-04-14 22:09:26 +00001863/// Finish building a variable declaration for a for-range statement.
1864/// \return true if an error occurs.
1865static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001866 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001867 if (Decl->getType()->isUndeducedType()) {
1868 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1869 if (!Res.isUsable()) {
1870 Decl->setInvalidDecl();
1871 return true;
1872 }
1873 Init = Res.get();
1874 }
1875
Richard Smith02e85f32011-04-14 22:09:26 +00001876 // Deduce the type for the iterator variable now rather than leaving it to
1877 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001878 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001879 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001880 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001881 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001882 SemaRef.Diag(Loc, DiagID) << Init->getType();
1883 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001884 Decl->setInvalidDecl();
1885 return true;
1886 }
Richard Smith061f1e22013-04-30 21:23:01 +00001887 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001888
John McCall31168b02011-06-15 23:02:42 +00001889 // In ARC, infer lifetime.
1890 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1891 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001892 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001893 SemaRef.inferObjCARCLifetime(Decl))
1894 Decl->setInvalidDecl();
1895
Richard Smith3beb7c62017-01-12 02:27:38 +00001896 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001897 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001898 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001899 return false;
1900}
1901
Sam Panzer0f384432012-08-21 00:52:01 +00001902namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001903// An enum to represent whether something is dealing with a call to begin()
1904// or a call to end() in a range-based for loop.
1905enum BeginEndFunction {
1906 BEF_begin,
1907 BEF_end
1908};
Sam Panzer0f384432012-08-21 00:52:01 +00001909
Richard Smith02e85f32011-04-14 22:09:26 +00001910/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001911/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001912/// nor from the diagnostics produced when analysing the implicit expressions
1913/// required in a for-range statement.
1914void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001915 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001916 CallExpr *CE = dyn_cast<CallExpr>(E);
1917 if (!CE)
1918 return;
1919 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1920 if (!D)
1921 return;
1922 SourceLocation Loc = D->getLocation();
1923
1924 std::string Description;
1925 bool IsTemplate = false;
1926 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1927 Description = SemaRef.getTemplateArgumentBindingsText(
1928 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1929 IsTemplate = true;
1930 }
1931
1932 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1933 << BEF << IsTemplate << Description << E->getType();
1934}
1935
Sam Panzer0f384432012-08-21 00:52:01 +00001936/// Build a variable declaration for a for-range statement.
1937VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1938 QualType Type, const char *Name) {
1939 DeclContext *DC = SemaRef.CurContext;
1940 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1941 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1942 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001943 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001944 Decl->setImplicit();
1945 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001946}
1947
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001948}
Richard Smith02e85f32011-04-14 22:09:26 +00001949
Fariborz Jahanian00213472012-07-06 19:04:04 +00001950static bool ObjCEnumerationCollection(Expr *Collection) {
1951 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001953}
1954
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001955/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001956///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001957/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001958/// A range-based for statement is equivalent to
1959///
1960/// {
1961/// auto && __range = range-init;
1962/// for ( auto __begin = begin-expr,
1963/// __end = end-expr;
1964/// __begin != __end;
1965/// ++__begin ) {
1966/// for-range-declaration = *__begin;
1967/// statement
1968/// }
1969/// }
1970///
1971/// The body of the loop is not available yet, since it cannot be analysed until
1972/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00001973StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1974 SourceLocation CoawaitLoc, Stmt *First,
1975 SourceLocation ColonLoc, Expr *Range,
1976 SourceLocation RParenLoc,
1977 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001978 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001979 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001980
Richard Smith3249fed2013-08-21 01:40:36 +00001981 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001982 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001983
1984 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1985 assert(DS && "first part of for range not a decl stmt");
1986
1987 if (!DS->isSingleDecl()) {
1988 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1989 return StmtError();
1990 }
Richard Smith02e85f32011-04-14 22:09:26 +00001991
Richard Smith3249fed2013-08-21 01:40:36 +00001992 Decl *LoopVar = DS->getSingleDecl();
1993 if (LoopVar->isInvalidDecl() || !Range ||
1994 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1995 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001996 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001997 }
Richard Smith02e85f32011-04-14 22:09:26 +00001998
Richard Smithcfd53b42015-10-22 06:13:50 +00001999 // Coroutines: 'for co_await' implicitly co_awaits its range.
2000 if (CoawaitLoc.isValid()) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002001 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
Richard Smithcfd53b42015-10-22 06:13:50 +00002002 if (Coawait.isInvalid()) return StmtError();
2003 Range = Coawait.get();
2004 }
2005
Richard Smith02e85f32011-04-14 22:09:26 +00002006 // Build auto && __range = range-init
2007 SourceLocation RangeLoc = Range->getLocStart();
2008 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2009 Context.getAutoRRefDeductType(),
2010 "__range");
2011 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002012 diag::err_for_range_deduction_failure)) {
2013 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002014 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002015 }
Richard Smith02e85f32011-04-14 22:09:26 +00002016
2017 // Claim the type doesn't contain auto: we've already done the checking.
2018 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002019 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002020 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002021 if (RangeDecl.isInvalid()) {
2022 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002023 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002024 }
Richard Smith02e85f32011-04-14 22:09:26 +00002025
Richard Smithcfd53b42015-10-22 06:13:50 +00002026 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002027 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2028 /*Cond=*/nullptr, /*Inc=*/nullptr,
2029 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002030}
2031
2032/// \brief Create the initialization, compare, and increment steps for
2033/// the range-based for loop expression.
2034/// This function does not handle array-based for loops,
2035/// which are created in Sema::BuildCXXForRangeStmt.
2036///
2037/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2038/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2039/// CandidateSet and BEF are set and some non-success value is returned on
2040/// failure.
Richard Smith9f690bd2015-10-27 06:02:45 +00002041static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
Sam Panzer0f384432012-08-21 00:52:01 +00002042 Expr *BeginRange, Expr *EndRange,
2043 QualType RangeType,
2044 VarDecl *BeginVar,
2045 VarDecl *EndVar,
2046 SourceLocation ColonLoc,
2047 OverloadCandidateSet *CandidateSet,
2048 ExprResult *BeginExpr,
2049 ExprResult *EndExpr,
Richard Smith9f690bd2015-10-27 06:02:45 +00002050 BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002051 DeclarationNameInfo BeginNameInfo(
2052 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2053 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2054 ColonLoc);
2055
2056 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2057 Sema::LookupMemberName);
2058 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2059
2060 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2061 // - if _RangeT is a class type, the unqualified-ids begin and end are
2062 // looked up in the scope of class _RangeT as if by class member access
2063 // lookup (3.4.5), and if either (or both) finds at least one
2064 // declaration, begin-expr and end-expr are __range.begin() and
2065 // __range.end(), respectively;
2066 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2067 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2068
2069 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2070 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002071 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002072
2073 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2074 << RangeLoc << BeginRange->getType() << *BEF;
2075 return Sema::FRS_DiagnosticIssued;
2076 }
2077 } else {
2078 // - otherwise, begin-expr and end-expr are begin(__range) and
2079 // end(__range), respectively, where begin and end are looked up with
2080 // argument-dependent lookup (3.4.2). For the purposes of this name
2081 // lookup, namespace std is an associated namespace.
2082
2083 }
2084
Richard Smith9f690bd2015-10-27 06:02:45 +00002085 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002086 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002087 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002088 BeginMemberLookup, CandidateSet,
2089 BeginRange, BeginExpr);
2090
Richard Smith9f690bd2015-10-27 06:02:45 +00002091 if (RangeStatus != Sema::FRS_Success) {
2092 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2093 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2094 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002095 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002096 }
Sam Panzer0f384432012-08-21 00:52:01 +00002097 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2098 diag::err_for_range_iter_deduction_failure)) {
2099 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2100 return Sema::FRS_DiagnosticIssued;
2101 }
2102
Richard Smith9f690bd2015-10-27 06:02:45 +00002103 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002104 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002105 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002106 EndMemberLookup, CandidateSet,
2107 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002108 if (RangeStatus != Sema::FRS_Success) {
2109 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2110 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2111 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002112 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002113 }
Sam Panzer0f384432012-08-21 00:52:01 +00002114 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2115 diag::err_for_range_iter_deduction_failure)) {
2116 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2117 return Sema::FRS_DiagnosticIssued;
2118 }
2119 return Sema::FRS_Success;
2120}
2121
2122/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002123/// If the attempt fails, this function will return a valid, null StmtResult
2124/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002125static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2126 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002127 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002128 Stmt *LoopVarDecl,
2129 SourceLocation ColonLoc,
2130 Expr *Range,
2131 SourceLocation RangeLoc,
2132 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002133 // Determine whether we can rebuild the for-range statement with a
2134 // dereferenced range expression.
2135 ExprResult AdjustedRange;
2136 {
2137 Sema::SFINAETrap Trap(SemaRef);
2138
2139 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2140 if (AdjustedRange.isInvalid())
2141 return StmtResult();
2142
Richard Smith9f690bd2015-10-27 06:02:45 +00002143 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2144 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2145 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002146 if (SR.isInvalid())
2147 return StmtResult();
2148 }
2149
2150 // The attempt to dereference worked well enough that it could produce a valid
2151 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2152 // case there are any other (non-fatal) problems with it.
2153 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2154 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002155 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2156 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002157 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002158}
2159
Richard Smith3249fed2013-08-21 01:40:36 +00002160namespace {
2161/// RAII object to automatically invalidate a declaration if an error occurs.
2162struct InvalidateOnErrorScope {
2163 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2164 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2165 ~InvalidateOnErrorScope() {
2166 if (Enabled && Trap.hasErrorOccurred())
2167 D->setInvalidDecl();
2168 }
2169
2170 DiagnosticErrorTrap Trap;
2171 Decl *D;
2172 bool Enabled;
2173};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002174}
Richard Smith3249fed2013-08-21 01:40:36 +00002175
Richard Smitha05b3b52012-09-20 21:52:32 +00002176/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002177StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002178Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002179 SourceLocation ColonLoc, Stmt *RangeDecl,
2180 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002181 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002182 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002183 // FIXME: This should not be used during template instantiation. We should
2184 // pick up the set of unqualified lookup results for the != and + operators
2185 // in the initial parse.
2186 //
2187 // Testcase (accepts-invalid):
2188 // template<typename T> void f() { for (auto x : T()) {} }
2189 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2190 // bool operator!=(N::X, N::X); void operator++(N::X);
2191 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002192 Scope *S = getCurScope();
2193
2194 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2195 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2196 QualType RangeVarType = RangeVar->getType();
2197
2198 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2199 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2200
Richard Smith3249fed2013-08-21 01:40:36 +00002201 // If we hit any errors, mark the loop variable as invalid if its type
2202 // contains 'auto'.
2203 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2204 LoopVar->getType()->isUndeducedType());
2205
Richard Smith01694c32016-03-20 10:33:40 +00002206 StmtResult BeginDeclStmt = Begin;
2207 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002208 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2209
Richard Smith27d807c2013-04-30 13:56:41 +00002210 if (RangeVarType->isDependentType()) {
2211 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002212 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002213
2214 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2215 // them in properly when we instantiate the loop.
2216 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2217 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Richard Smith01694c32016-03-20 10:33:40 +00002218 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002219 SourceLocation RangeLoc = RangeVar->getLocation();
2220
Ted Kremenekbed648e2011-10-10 22:36:28 +00002221 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2222
2223 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2224 VK_LValue, ColonLoc);
2225 if (BeginRangeRef.isInvalid())
2226 return StmtError();
2227
2228 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2229 VK_LValue, ColonLoc);
2230 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002231 return StmtError();
2232
2233 QualType AutoType = Context.getAutoDeductType();
2234 Expr *Range = RangeVar->getInit();
2235 if (!Range)
2236 return StmtError();
2237 QualType RangeType = Range->getType();
2238
2239 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002240 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002241 return StmtError();
2242
2243 // Build auto __begin = begin-expr, __end = end-expr.
2244 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2245 "__begin");
2246 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2247 "__end");
2248
2249 // Build begin-expr and end-expr and attach to __begin and __end variables.
2250 ExprResult BeginExpr, EndExpr;
2251 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2252 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2253 // __range + __bound, respectively, where __bound is the array bound. If
2254 // _RangeT is an array of unknown size or an array of incomplete type,
2255 // the program is ill-formed;
2256
2257 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002258 BeginExpr = BeginRangeRef;
2259 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002260 diag::err_for_range_iter_deduction_failure)) {
2261 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2262 return StmtError();
2263 }
2264
2265 // Find the array bound.
2266 ExprResult BoundExpr;
2267 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002268 BoundExpr = IntegerLiteral::Create(
2269 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002270 else if (const VariableArrayType *VAT =
2271 dyn_cast<VariableArrayType>(UnqAT))
2272 BoundExpr = VAT->getSizeExpr();
2273 else {
2274 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2275 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002276 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002277 }
2278
2279 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002280 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002281 BoundExpr.get());
2282 if (EndExpr.isInvalid())
2283 return StmtError();
2284 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2285 diag::err_for_range_iter_deduction_failure)) {
2286 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2287 return StmtError();
2288 }
2289 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002290 OverloadCandidateSet CandidateSet(RangeLoc,
2291 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002292 BeginEndFunction BEFFailure;
Sam Panzer0f384432012-08-21 00:52:01 +00002293 ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002294 BuildNonArrayForRange(*this, BeginRangeRef.get(),
Sam Panzer0f384432012-08-21 00:52:01 +00002295 EndRangeRef.get(), RangeType,
2296 BeginVar, EndVar, ColonLoc, &CandidateSet,
2297 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002298
Richard Smitha05b3b52012-09-20 21:52:32 +00002299 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002300 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002301 // If the range is being built from an array parameter, emit a
2302 // a diagnostic that it is being treated as a pointer.
2303 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2304 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2305 QualType ArrayTy = PVD->getOriginalType();
2306 QualType PointerTy = PVD->getType();
2307 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2308 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2309 << RangeLoc << PVD << ArrayTy << PointerTy;
2310 Diag(PVD->getLocation(), diag::note_declared_at);
2311 return StmtError();
2312 }
2313 }
2314 }
2315
2316 // If building the range failed, try dereferencing the range expression
2317 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002318 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002319 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002320 LoopVarDecl, ColonLoc,
2321 Range, RangeLoc,
2322 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002323 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002324 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002325 }
2326
Sam Panzer0f384432012-08-21 00:52:01 +00002327 // Otherwise, emit diagnostics if we haven't already.
2328 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002329 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002330 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2331 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002332 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002333 }
2334 // Return an error if no fix was discovered.
2335 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002336 return StmtError();
2337 }
2338
Sam Panzer0f384432012-08-21 00:52:01 +00002339 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2340 "invalid range expression in for loop");
2341
2342 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002343 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002344 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2345 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002346 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2347 ? diag::warn_for_range_begin_end_types_differ
2348 : diag::ext_for_range_begin_end_types_differ)
2349 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002350 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2351 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2352 }
2353
Richard Smith01694c32016-03-20 10:33:40 +00002354 BeginDeclStmt =
2355 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2356 EndDeclStmt =
2357 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002358
Ted Kremenekbed648e2011-10-10 22:36:28 +00002359 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2360 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002361 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002362 if (BeginRef.isInvalid())
2363 return StmtError();
2364
Richard Smith02e85f32011-04-14 22:09:26 +00002365 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2366 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002367 if (EndRef.isInvalid())
2368 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002369
2370 // Build and check __begin != __end expression.
2371 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2372 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002373 if (!NotEqExpr.isInvalid())
2374 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2375 if (!NotEqExpr.isInvalid())
2376 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002377 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002378 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2379 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002380 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2381 if (!Context.hasSameType(BeginType, EndType))
2382 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2383 return StmtError();
2384 }
2385
2386 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002387 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2388 VK_LValue, ColonLoc);
2389 if (BeginRef.isInvalid())
2390 return StmtError();
2391
Richard Smith02e85f32011-04-14 22:09:26 +00002392 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002393 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Richard Smith9f690bd2015-10-27 06:02:45 +00002394 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002395 if (!IncrExpr.isInvalid())
2396 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002397 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002398 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2399 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002400 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2401 return StmtError();
2402 }
2403
2404 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002405 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2406 VK_LValue, ColonLoc);
2407 if (BeginRef.isInvalid())
2408 return StmtError();
2409
Richard Smith02e85f32011-04-14 22:09:26 +00002410 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2411 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002412 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2413 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002414 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2415 return StmtError();
2416 }
2417
Richard Smitha05b3b52012-09-20 21:52:32 +00002418 // Attach *__begin as initializer for VD. Don't touch it if we're just
2419 // trying to determine whether this would be a valid range.
2420 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002421 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002422 if (LoopVar->isInvalidDecl())
2423 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2424 }
2425 }
2426
Richard Smitha05b3b52012-09-20 21:52:32 +00002427 // Don't bother to actually allocate the result if we're just trying to
2428 // determine whether it would be valid.
2429 if (Kind == BFRK_Check)
2430 return StmtResult();
2431
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002432 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002433 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2434 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002435 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2436 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002437}
2438
Chad Rosier02a84392012-08-10 17:56:09 +00002439/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002440/// statement.
2441StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2442 if (!S || !B)
2443 return StmtError();
2444 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002445
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002446 ForStmt->setBody(B);
2447 return S;
2448}
2449
Richard Trieu3e1d4832015-04-13 22:08:55 +00002450// Warn when the loop variable is a const reference that creates a copy.
2451// Suggest using the non-reference type for copies. If a copy can be prevented
2452// suggest the const reference type that would do so.
2453// For instance, given "for (const &Foo : Range)", suggest
2454// "for (const Foo : Range)" to denote a copy is made for the loop. If
2455// possible, also suggest "for (const &Bar : Range)" if this type prevents
2456// the copy altogether.
2457static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2458 const VarDecl *VD,
2459 QualType RangeInitType) {
2460 const Expr *InitExpr = VD->getInit();
2461 if (!InitExpr)
2462 return;
2463
2464 QualType VariableType = VD->getType();
2465
Tim Shen4a05bb82016-06-21 20:29:17 +00002466 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2467 if (!Cleanups->cleanupsHaveSideEffects())
2468 InitExpr = Cleanups->getSubExpr();
2469
Richard Trieu3e1d4832015-04-13 22:08:55 +00002470 const MaterializeTemporaryExpr *MTE =
2471 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2472
2473 // No copy made.
2474 if (!MTE)
2475 return;
2476
2477 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2478
2479 // Searching for either UnaryOperator for dereference of a pointer or
2480 // CXXOperatorCallExpr for handling iterators.
2481 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2482 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2483 E = CCE->getArg(0);
2484 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2485 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2486 E = ME->getBase();
2487 } else {
2488 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2489 E = MTE->GetTemporaryExpr();
2490 }
2491 E = E->IgnoreImpCasts();
2492 }
2493
2494 bool ReturnsReference = false;
2495 if (isa<UnaryOperator>(E)) {
2496 ReturnsReference = true;
2497 } else {
2498 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2499 const FunctionDecl *FD = Call->getDirectCallee();
2500 QualType ReturnType = FD->getReturnType();
2501 ReturnsReference = ReturnType->isReferenceType();
2502 }
2503
2504 if (ReturnsReference) {
2505 // Loop variable creates a temporary. Suggest either to go with
2506 // non-reference loop variable to indiciate a copy is made, or
2507 // the correct time to bind a const reference.
2508 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2509 << VD << VariableType << E->getType();
2510 QualType NonReferenceType = VariableType.getNonReferenceType();
2511 NonReferenceType.removeLocalConst();
2512 QualType NewReferenceType =
2513 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2514 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2515 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2516 } else {
2517 // The range always returns a copy, so a temporary is always created.
2518 // Suggest removing the reference from the loop variable.
2519 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2520 << VD << RangeInitType;
2521 QualType NonReferenceType = VariableType.getNonReferenceType();
2522 NonReferenceType.removeLocalConst();
2523 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2524 << NonReferenceType << VD->getSourceRange();
2525 }
2526}
2527
2528// Warns when the loop variable can be changed to a reference type to
2529// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2530// "for (const Foo &x : Range)" if this form does not make a copy.
2531static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2532 const VarDecl *VD) {
2533 const Expr *InitExpr = VD->getInit();
2534 if (!InitExpr)
2535 return;
2536
2537 QualType VariableType = VD->getType();
2538
2539 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2540 if (!CE->getConstructor()->isCopyConstructor())
2541 return;
2542 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2543 if (CE->getCastKind() != CK_LValueToRValue)
2544 return;
2545 } else {
2546 return;
2547 }
2548
2549 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2550 // should be emitted. Also, only ignore POD types with trivial copy
2551 // constructors.
2552 if (VariableType.isPODType(SemaRef.Context))
2553 return;
2554
2555 // Suggest changing from a const variable to a const reference variable
2556 // if doing so will prevent a copy.
2557 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2558 << VD << VariableType << InitExpr->getType();
2559 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2560 << SemaRef.Context.getLValueReferenceType(VariableType)
2561 << VD->getSourceRange();
2562}
2563
2564/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2565/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2566/// using "const foo x" to show that a copy is made
2567/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2568/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2569/// prevent the copy.
2570/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2571/// Suggest "const foo &x" to prevent the copy.
2572static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2573 const CXXForRangeStmt *ForStmt) {
2574 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2575 ForStmt->getLocStart()) &&
2576 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2577 ForStmt->getLocStart()) &&
2578 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2579 ForStmt->getLocStart())) {
2580 return;
2581 }
2582
2583 const VarDecl *VD = ForStmt->getLoopVariable();
2584 if (!VD)
2585 return;
2586
2587 QualType VariableType = VD->getType();
2588
2589 if (VariableType->isIncompleteType())
2590 return;
2591
2592 const Expr *InitExpr = VD->getInit();
2593 if (!InitExpr)
2594 return;
2595
2596 if (VariableType->isReferenceType()) {
2597 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2598 ForStmt->getRangeInit()->getType());
2599 } else if (VariableType.isConstQualified()) {
2600 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2601 }
2602}
2603
Richard Smith02e85f32011-04-14 22:09:26 +00002604/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2605/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2606/// body cannot be performed until after the type of the range variable is
2607/// determined.
2608StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2609 if (!S || !B)
2610 return StmtError();
2611
Fariborz Jahanian00213472012-07-06 19:04:04 +00002612 if (isa<ObjCForCollectionStmt>(S))
2613 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002614
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002615 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2616 ForStmt->setBody(B);
2617
2618 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2619 diag::warn_empty_range_based_for_body);
2620
Richard Trieu3e1d4832015-04-13 22:08:55 +00002621 DiagnoseForRangeVariableCopies(*this, ForStmt);
2622
Richard Smith02e85f32011-04-14 22:09:26 +00002623 return S;
2624}
2625
Chris Lattnercab02a62011-02-17 20:34:02 +00002626StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2627 SourceLocation LabelLoc,
2628 LabelDecl *TheDecl) {
2629 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002630 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002631 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002632}
Chris Lattner1c310502007-05-31 06:00:00 +00002633
John McCalldadc5752010-08-24 06:29:42 +00002634StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002635Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002636 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002637 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002638 if (!E->isTypeDependent()) {
2639 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002640 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002641 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002642 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002643 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2644 if (ExprRes.isInvalid())
2645 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002646 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002647 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002648 return StmtError();
2649 }
John McCalla95172b2010-08-01 00:26:45 +00002650
Richard Smith945f8d32013-01-14 22:39:08 +00002651 ExprResult ExprRes = ActOnFinishFullExpr(E);
2652 if (ExprRes.isInvalid())
2653 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002654 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002655
John McCallaab3e412010-08-25 08:40:02 +00002656 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002657
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002658 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002659}
2660
Nico Weberd64657f2015-03-09 02:47:59 +00002661static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2662 const Scope &DestScope) {
2663 if (!S.CurrentSEHFinally.empty() &&
2664 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2665 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2666 }
2667}
2668
John McCalldadc5752010-08-24 06:29:42 +00002669StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002670Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002671 Scope *S = CurScope->getContinueParent();
2672 if (!S) {
2673 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002674 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002675 }
Nico Weberd64657f2015-03-09 02:47:59 +00002676 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002677
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002678 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002679}
2680
John McCalldadc5752010-08-24 06:29:42 +00002681StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002682Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002683 Scope *S = CurScope->getBreakParent();
2684 if (!S) {
2685 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002686 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002687 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002688 if (S->isOpenMPLoopScope())
2689 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2690 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002691 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002692
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002693 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002694}
2695
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002696/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002697/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002698///
Douglas Gregor5d369002011-01-21 18:05:27 +00002699/// \param ReturnType If we're determining the copy elision candidate for
2700/// a return statement, this is the return type of the function. If we're
2701/// determining the copy elision candidate for a throw expression, this will
2702/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002703///
Douglas Gregor5d369002011-01-21 18:05:27 +00002704/// \param E The expression being returned from the function or block, or
2705/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002706///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002707/// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2708/// id-expressions that could be moved out of the function to be considered NRVO
2709/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2710/// determine whether we should try to move as part of a return or throw (which
2711/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002712///
2713/// \returns The NRVO candidate variable, if the return statement may use the
2714/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002715VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2716 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002717 if (!getLangOpts().CPlusPlus)
2718 return nullptr;
2719
2720 // - in a return statement in a function [where] ...
2721 // ... the expression is the name of a non-volatile automatic object ...
2722 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002723 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002724 return nullptr;
2725 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2726 if (!VD)
2727 return nullptr;
2728
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002729 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002730 return VD;
2731 return nullptr;
2732}
2733
2734bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002735 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002736 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002737 // - in a return statement in a function with ...
2738 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002739 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002740 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002741 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002742 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002743 // When considering moving this expression out, allow dissimilar types.
2744 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002745 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2746 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002748
John McCall03318c12011-11-11 03:57:31 +00002749 // ...object (other than a function or catch-clause parameter)...
2750 if (VD->getKind() != Decl::Var &&
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002751 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002752 return false;
2753 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002754
John McCall03318c12011-11-11 03:57:31 +00002755 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002756 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002757
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002758 // Return false if VD is a __block variable. We don't want to implicitly move
2759 // out of a __block variable during a return because we cannot assume the
2760 // variable will no longer be used.
2761 if (VD->hasAttr<BlocksAttr>()) return false;
2762
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002763 if (AllowParamOrMoveConstructible)
2764 return true;
2765
John McCall03318c12011-11-11 03:57:31 +00002766 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002767 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002768
John McCall03318c12011-11-11 03:57:31 +00002769 // Variables with higher required alignment than their type's ABI
2770 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002771 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002772 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002773 return false;
John McCall03318c12011-11-11 03:57:31 +00002774
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002775 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002776}
2777
Douglas Gregor626fbed2011-01-21 21:08:57 +00002778/// \brief Perform the initialization of a potentially-movable value, which
2779/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002780///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002781/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00002782/// returned lvalues as rvalues in certain cases (to prefer move construction),
2783/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002785Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2786 const VarDecl *NRVOCandidate,
2787 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002788 Expr *Value,
2789 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002790 // C++14 [class.copy]p32:
2791 // When the criteria for elision of a copy/move operation are met, but not for
2792 // an exception-declaration, and the object to be copied is designated by an
2793 // lvalue, or when the expression in a return statement is a (possibly
2794 // parenthesized) id-expression that names an object with automatic storage
2795 // duration declared in the body or parameter-declaration-clause of the
2796 // innermost enclosing function or lambda-expression, overload resolution to
2797 // select the constructor for the copy is first performed as if the object
2798 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002799 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002800
2801 if (AllowNRVO && !NRVOCandidate)
2802 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2803
2804 if (AllowNRVO && NRVOCandidate) {
2805 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2806 CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002807
Douglas Gregorf282a762011-01-21 19:38:21 +00002808 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002810 InitializationKind Kind = InitializationKind::CreateCopy(
2811 Value->getLocStart(), Value->getLocStart());
2812
2813 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002814 if (Seq) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002815 for (const InitializationSequence::Step &Step : Seq.steps()) {
2816 if (!(Step.Kind ==
2817 InitializationSequence::SK_ConstructorInitialization ||
2818 (Step.Kind == InitializationSequence::SK_UserConversion &&
2819 isa<CXXConstructorDecl>(Step.Function.Function))))
Douglas Gregorf282a762011-01-21 19:38:21 +00002820 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002822 CXXConstructorDecl *Constructor =
2823 cast<CXXConstructorDecl>(Step.Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824
Douglas Gregorf282a762011-01-21 19:38:21 +00002825 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002826 = Constructor->getParamDecl(0)->getType()
2827 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002829 // [...] If the first overload resolution fails or was not performed, or
2830 // if the type of the first parameter of the selected constructor is not
2831 // an rvalue reference to the object’s type (possibly cv-qualified),
2832 // overload resolution is performed again, considering the object as an
2833 // lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002835 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002836 NRVOCandidate->getType()))
Douglas Gregorf282a762011-01-21 19:38:21 +00002837 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838
Douglas Gregorf282a762011-01-21 19:38:21 +00002839 // Promote "AsRvalue" to the heap, since we now need this
2840 // expression node to persist.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002841 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2842 Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002843
Douglas Gregorf282a762011-01-21 19:38:21 +00002844 // Complete type-checking the initialization of the return type
2845 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002846 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002847 }
2848 }
2849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002850
Douglas Gregorf282a762011-01-21 19:38:21 +00002851 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002852 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002853 // (again) now with the return value expression as written.
2854 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002855 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002856
Douglas Gregorf282a762011-01-21 19:38:21 +00002857 return Res;
2858}
2859
Richard Smith4db51c22013-09-25 05:02:54 +00002860/// \brief Determine whether the declared return type of the specified function
2861/// contains 'auto'.
2862static bool hasDeducedReturnType(FunctionDecl *FD) {
2863 const FunctionProtoType *FPT =
2864 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002865 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002866}
2867
Eli Friedman34b49062012-01-26 03:00:14 +00002868/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2869/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002870///
John McCalldadc5752010-08-24 06:29:42 +00002871StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002872Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2873 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002874 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002875 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002876 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002877 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00002878 bool HasDeducedReturnType =
2879 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002880
Faisal Valid143a0c2017-04-01 21:30:49 +00002881 if (ExprEvalContexts.back().Context ==
2882 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00002883 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
2884 if (RetValExp) {
2885 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2886 if (ER.isInvalid())
2887 return StmtError();
2888 RetValExp = ER.get();
2889 }
2890 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2891 }
2892
2893 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00002894 // In C++1y, the return type may involve 'auto'.
2895 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2896 FunctionDecl *FD = CurLambda->CallOperator;
2897 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002898 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002899
2900 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2901 assert(AT && "lost auto type from lambda return type");
2902 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2903 FD->setInvalidDecl();
2904 return StmtError();
2905 }
Alp Toker314cc812014-01-25 16:55:45 +00002906 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002907 } else if (CurCap->HasImplicitReturnType) {
2908 // For blocks/lambdas with implicit return types, we check each return
2909 // statement individually, and deduce the common return type when the block
2910 // or lambda is completed.
2911 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002912 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002913 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2914 if (Result.isInvalid())
2915 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002916 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002917
Richard Smith5a0e50c2014-12-19 22:10:51 +00002918 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2919 // when deducing a return type for a lambda-expression (or by extension
2920 // for a block). These rules differ from the stated C++11 rules only in
2921 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002922 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002923 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002924 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002925 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002926 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002927 if (RetValExp) {
2928 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2929 // initializer list, because it is not an expression (even
2930 // though we represent it as one). We still deduce 'void'.
2931 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2932 << RetValExp->getSourceRange();
2933 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002934
Jordan Rosed39e5f12012-07-02 21:19:23 +00002935 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002936 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002937
2938 // Although we'll properly infer the type of the block once it's completed,
2939 // make sure we provide a return type now for better error recovery.
2940 if (CurCap->ReturnType.isNull())
2941 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002942 }
Eli Friedman34b49062012-01-26 03:00:14 +00002943 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002944
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002945 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002946 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2947 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2948 return StmtError();
2949 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002950 } else if (CapturedRegionScopeInfo *CurRegion =
2951 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2952 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2953 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002954 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002955 assert(CurLambda && "unknown kind of captured scope");
2956 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2957 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002958 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2959 return StmtError();
2960 }
2961 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002962
Steve Naroffc540d662008-09-03 18:15:37 +00002963 // Otherwise, verify that this result type matches the previous one. We are
2964 // pickier with blocks than for normal functions because we don't have GCC
2965 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002966 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002967 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002968 // Delay processing for now. TODO: there are lots of dependent
2969 // types we can conclusively prove aren't void.
2970 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002971 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002972 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002973 (RetValExp->isTypeDependent() ||
2974 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002975 if (!getLangOpts().CPlusPlus &&
2976 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002977 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002978 else {
2979 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002980 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002981 }
Steve Naroffc540d662008-09-03 18:15:37 +00002982 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002983 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002984 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2985 } else if (!RetValExp->isTypeDependent()) {
2986 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002987
John McCall5500ef22011-08-17 22:09:46 +00002988 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2989 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2990 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002991
John McCall5500ef22011-08-17 22:09:46 +00002992 // In C++ the return statement is handled via a copy initialization.
2993 // the C version of which boils down to CheckSingleAssignmentConstraints.
2994 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2995 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2996 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002997 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002998 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2999 FnRetType, RetValExp);
3000 if (Res.isInvalid()) {
3001 // FIXME: Cleanup temporaries here, anyway?
3002 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003003 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003004 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003005 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003006 } else {
3007 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00003008 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003009
John McCall75f92b52011-08-17 21:34:14 +00003010 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003011 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3012 if (ER.isInvalid())
3013 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003014 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003015 }
John McCall5500ef22011-08-17 22:09:46 +00003016 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3017 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003018
Jordan Rosed39e5f12012-07-02 21:19:23 +00003019 // If we need to check for the named return value optimization,
3020 // or if we need to infer the return type,
3021 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003022 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003023 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024
Richard Smith9f690bd2015-10-27 06:02:45 +00003025 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3026 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3027
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003028 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003029}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003030
Nico Weber72889432014-09-06 01:25:55 +00003031namespace {
3032/// \brief Marks all typedefs in all local classes in a type referenced.
3033///
3034/// In a function like
3035/// auto f() {
3036/// struct S { typedef int a; };
3037/// return S();
3038/// }
3039///
3040/// the local type escapes and could be referenced in some TUs but not in
3041/// others. Pretend that all local typedefs are always referenced, to not warn
3042/// on this. This isn't necessary if f has internal linkage, or the typedef
3043/// is private.
3044class LocalTypedefNameReferencer
3045 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3046public:
3047 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3048 bool VisitRecordType(const RecordType *RT);
3049private:
3050 Sema &S;
3051};
3052bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3053 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3054 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3055 R->isDependentType())
3056 return true;
3057 for (auto *TmpD : R->decls())
3058 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3059 if (T->getAccess() != AS_private || R->hasFriends())
3060 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3061 return true;
3062}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003063}
Nico Weber72889432014-09-06 01:25:55 +00003064
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003065TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003066 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003067 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3068 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003069 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003070}
3071
Richard Smith2a7d4812013-05-04 07:00:32 +00003072/// Deduce the return type for a function from a returned expression, per
3073/// C++1y [dcl.spec.auto]p6.
3074bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3075 SourceLocation ReturnLoc,
3076 Expr *&RetExpr,
3077 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003078 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003079 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003080
Richard Smithc58f38f2013-08-14 20:16:31 +00003081 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3082 // If the deduction is for a return statement and the initializer is
3083 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003084 Diag(RetExpr->getExprLoc(),
3085 getCurLambda() ? diag::err_lambda_return_init_list
3086 : diag::err_auto_fn_return_init_list)
3087 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003088 return true;
3089 }
3090
3091 if (FD->isDependentContext()) {
3092 // C++1y [dcl.spec.auto]p12:
3093 // Return type deduction [...] occurs when the definition is
3094 // instantiated even if the function body contains a return
3095 // statement with a non-type-dependent operand.
3096 assert(AT->isDeduced() && "should have deduced to dependent type");
3097 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003098 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003099
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003100 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003101 // Otherwise, [...] deduce a value for U using the rules of template
3102 // argument deduction.
3103 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3104
3105 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3106 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3107 << OrigResultType.getType() << RetExpr->getType();
3108
3109 if (DAR != DAR_Succeeded)
3110 return true;
Nico Weber72889432014-09-06 01:25:55 +00003111
3112 // If a local type is part of the returned type, mark its fields as
3113 // referenced.
3114 LocalTypedefNameReferencer Referencer(*this);
3115 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003116 } else {
3117 // In the case of a return with no operand, the initializer is considered
3118 // to be void().
3119 //
3120 // Deduction here can only succeed if the return type is exactly 'cv auto'
3121 // or 'decltype(auto)', so just check for that case directly.
3122 if (!OrigResultType.getType()->getAs<AutoType>()) {
3123 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3124 << OrigResultType.getType();
3125 return true;
3126 }
3127 // We always deduce U = void in this case.
3128 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3129 if (Deduced.isNull())
3130 return true;
3131 }
3132
3133 // If a function with a declared return type that contains a placeholder type
3134 // has multiple return statements, the return type is deduced for each return
3135 // statement. [...] if the type deduced is not the same in each deduction,
3136 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003137 QualType DeducedT = AT->getDeducedType();
3138 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003139 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003140 // It is possible that NewAT->getDeducedType() is null. When that happens,
3141 // we should not crash, instead we ignore this deduction.
3142 if (NewAT->getDeducedType().isNull())
3143 return false;
3144
Douglas Gregora602a152015-10-01 20:20:47 +00003145 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003146 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003147 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3148 NewAT->getDeducedType());
3149 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003150 const LambdaScopeInfo *LambdaSI = getCurLambda();
3151 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3152 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003153 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003154 << true /*IsLambda*/;
3155 } else {
3156 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3157 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003158 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003159 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003160 return true;
3161 }
3162 } else if (!FD->isInvalidDecl()) {
3163 // Update all declarations of the function to have the deduced return type.
3164 Context.adjustDeducedFunctionResultType(FD, Deduced);
3165 }
3166
3167 return false;
3168}
3169
John McCalldadc5752010-08-24 06:29:42 +00003170StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003171Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3172 Scope *CurScope) {
3173 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Faisal Valid143a0c2017-04-01 21:30:49 +00003174 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3175 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003176 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003177
3178 if (VarDecl *VD =
3179 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3180 CurScope->addNRVOCandidate(VD);
3181 } else {
3182 CurScope->setNoNRVO();
3183 }
3184
Nico Weberd64657f2015-03-09 02:47:59 +00003185 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3186
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003187 return R;
3188}
3189
3190StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003191 // Check for unexpanded parameter packs.
3192 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3193 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003194
Eli Friedman34b49062012-01-26 03:00:14 +00003195 if (isa<CapturingScopeInfo>(getCurFunction()))
3196 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003197
Chris Lattner79413952008-12-04 23:50:19 +00003198 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003199 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003201 bool isObjCMethod = false;
3202
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003203 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003204 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003205 if (FD->hasAttrs())
3206 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003207 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003208 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003209 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003210 if (FD->isMain() && RetValExp)
3211 if (isa<CXXBoolLiteralExpr>(RetValExp))
3212 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3213 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003214 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003215 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003216 isObjCMethod = true;
3217 if (MD->hasAttrs())
3218 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003219 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3220 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003221 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003222 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003223 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3224 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003225 }
3226 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003227 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003228
Richard Smithb130fe72016-06-23 19:16:49 +00003229 // C++1z: discarded return statements are not considered when deducing a
3230 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003231 if (ExprEvalContexts.back().Context ==
3232 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003233 FnRetType->getContainedAutoType()) {
3234 if (RetValExp) {
3235 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3236 if (ER.isInvalid())
3237 return StmtError();
3238 RetValExp = ER.get();
3239 }
3240 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3241 }
3242
Richard Smith2a7d4812013-05-04 07:00:32 +00003243 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3244 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003245 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003246 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3247 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003248 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003249 FD->setInvalidDecl();
3250 return StmtError();
3251 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003252 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003253 }
3254 }
3255 }
3256
Richard Smithc58f38f2013-08-14 20:16:31 +00003257 bool HasDependentReturnType = FnRetType->isDependentType();
3258
Craig Topperc3ec1492014-05-26 06:22:03 +00003259 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003260 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003261 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003262 if (isa<InitListExpr>(RetValExp)) {
3263 // We simply never allow init lists as the return value of void
3264 // functions. This is compatible because this was never allowed before,
3265 // so there's no legacy code to deal with.
3266 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3267 int FunctionKind = 0;
3268 if (isa<ObjCMethodDecl>(CurDecl))
3269 FunctionKind = 1;
3270 else if (isa<CXXConstructorDecl>(CurDecl))
3271 FunctionKind = 2;
3272 else if (isa<CXXDestructorDecl>(CurDecl))
3273 FunctionKind = 3;
3274
3275 Diag(ReturnLoc, diag::err_return_init_list)
3276 << CurDecl->getDeclName() << FunctionKind
3277 << RetValExp->getSourceRange();
3278
3279 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003280 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003281 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003282 // C99 6.8.6.4p1 (ext_ since GCC warns)
3283 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003284 if (RetValExp->getType()->isVoidType()) {
3285 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3286 if (isa<CXXConstructorDecl>(CurDecl) ||
3287 isa<CXXDestructorDecl>(CurDecl))
3288 D = diag::err_ctor_dtor_returns_void;
3289 else
3290 D = diag::ext_return_has_void_expr;
3291 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003292 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003293 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003294 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003295 if (Result.isInvalid())
3296 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003297 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003298 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003299 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003300 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003301 // return of void in constructor/destructor is illegal in C++.
3302 if (D == diag::err_ctor_dtor_returns_void) {
3303 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3304 Diag(ReturnLoc, D)
3305 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3306 << RetValExp->getSourceRange();
3307 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003308 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003309 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003310 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003311 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003312
3313 int FunctionKind = 0;
3314 if (isa<ObjCMethodDecl>(CurDecl))
3315 FunctionKind = 1;
3316 else if (isa<CXXConstructorDecl>(CurDecl))
3317 FunctionKind = 2;
3318 else if (isa<CXXDestructorDecl>(CurDecl))
3319 FunctionKind = 3;
3320
Nick Lewycky1be750a2011-06-01 07:44:31 +00003321 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003322 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003323 << RetValExp->getSourceRange();
3324 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003325 }
Mike Stump11289f42009-09-09 15:08:12 +00003326
Sebastian Redleef474c2012-02-22 10:50:08 +00003327 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003328 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3329 if (ER.isInvalid())
3330 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003331 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003332 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334
Craig Topperc3ec1492014-05-26 06:22:03 +00003335 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003336 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003337 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003338
David Majnemer2887ad32014-12-13 08:12:56 +00003339 unsigned DiagID;
3340 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3341 // C++11 [stmt.return]p2
3342 DiagID = diag::err_constexpr_return_missing_expr;
3343 FD->setInvalidDecl();
3344 } else if (getLangOpts().C99) {
3345 // C99 6.8.6.4p1 (ext_ since GCC warns)
3346 DiagID = diag::ext_return_missing_expr;
3347 } else {
3348 // C90 6.6.6.4p4
3349 DiagID = diag::warn_return_missing_expr;
3350 }
3351
3352 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003353 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003354 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003355 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003356
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003357 Result = new (Context) ReturnStmt(ReturnLoc);
3358 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003359 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003360 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003361
3362 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3363
3364 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3365 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3366 // function return.
3367
3368 // In C++ the return statement is handled via a copy initialization,
3369 // the C version of which boils down to CheckSingleAssignmentConstraints.
3370 if (RetValExp)
3371 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003372 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003373 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003375 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003376 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003378 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003379 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003380 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003381 return StmtError();
3382 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003383 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003384
3385 // If we have a related result type, we need to implicitly
3386 // convert back to the formal result type. We can't pretend to
3387 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003388 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003389 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003390 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3391 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003392 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3393 if (Res.isInvalid()) {
3394 // FIXME: Clean up temporaries here anyway?
3395 return StmtError();
3396 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003397 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003398 }
3399
Artyom Skrobov9f213442014-01-24 11:10:39 +00003400 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3401 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
John McCallacf0ee52010-10-08 02:01:28 +00003404 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003405 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3406 if (ER.isInvalid())
3407 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003408 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003409 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003410 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412
3413 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003414 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003415 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003416 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003417
Richard Smith9f690bd2015-10-27 06:02:45 +00003418 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3419 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3420
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003421 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003422}
3423
John McCalldadc5752010-08-24 06:29:42 +00003424StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003425Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003426 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003427 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003428 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003429 if (Var && Var->isInvalidDecl())
3430 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003432 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003433}
3434
John McCalldadc5752010-08-24 06:29:42 +00003435StmtResult
John McCallb268a282010-08-23 23:25:46 +00003436Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003437 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003438}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003439
John McCalldadc5752010-08-24 06:29:42 +00003440StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003442 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003443 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003444 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3445
John McCallaab3e412010-08-25 08:40:02 +00003446 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003447 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003448 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3449 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003450}
3451
John McCall0bd3e402012-05-08 21:41:25 +00003452StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003453 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003454 ExprResult Result = DefaultLvalueConversion(Throw);
3455 if (Result.isInvalid())
3456 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003457
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003458 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003459 if (Result.isInvalid())
3460 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003461 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003462
Douglas Gregor2900c162010-04-22 21:44:01 +00003463 QualType ThrowType = Throw->getType();
3464 // Make sure the expression type is an ObjC pointer or "void *".
3465 if (!ThrowType->isDependentType() &&
3466 !ThrowType->isObjCObjectPointerType()) {
3467 const PointerType *PT = ThrowType->getAs<PointerType>();
3468 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003469 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003470 << Throw->getType() << Throw->getSourceRange());
3471 }
3472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003474 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003475}
3476
John McCalldadc5752010-08-24 06:29:42 +00003477StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003479 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003480 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003481 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3482
John McCallb268a282010-08-23 23:25:46 +00003483 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003484 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003485 // in the context of an @catch clause).
3486 Scope *AtCatchParent = CurScope;
3487 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3488 AtCatchParent = AtCatchParent->getParent();
3489 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003490 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491 }
John McCallb268a282010-08-23 23:25:46 +00003492 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003493}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003494
John McCalld9bb7432011-07-27 21:50:02 +00003495ExprResult
3496Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3497 ExprResult result = DefaultLvalueConversion(operand);
3498 if (result.isInvalid())
3499 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003500 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003501
3502 // Make sure the expression type is an ObjC pointer or "void *".
3503 QualType type = operand->getType();
3504 if (!type->isDependentType() &&
3505 !type->isObjCObjectPointerType()) {
3506 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003507 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3508 if (getLangOpts().CPlusPlus) {
3509 if (RequireCompleteType(atLoc, type,
3510 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003511 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003512 << type << operand->getSourceRange();
3513
3514 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003515 if (result.isInvalid())
3516 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003517 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003518 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003519 << type << operand->getSourceRange();
3520
3521 operand = result.get();
3522 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003523 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003524 << type << operand->getSourceRange();
3525 }
3526 }
John McCalld9bb7432011-07-27 21:50:02 +00003527 }
3528
3529 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003530 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003531}
3532
John McCalldadc5752010-08-24 06:29:42 +00003533StmtResult
John McCallb268a282010-08-23 23:25:46 +00003534Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3535 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003536 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003537 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003538 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003539}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003540
3541/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3542/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003543StmtResult
John McCall48871652010-08-21 09:40:31 +00003544Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003545 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003546 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003547 return new (Context)
3548 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003549}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003550
John McCall31168b02011-06-15 23:02:42 +00003551StmtResult
3552Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3553 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003554 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003555}
3556
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003557namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003558class CatchHandlerType {
3559 QualType QT;
3560 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003561
Aaron Ballman8aee642902015-04-08 00:05:29 +00003562 // This is a special constructor to be used only with DenseMapInfo's
3563 // getEmptyKey() and getTombstoneKey() functions.
3564 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3565 enum Unique { ForDenseMap };
3566 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3567
Sebastian Redl63c4da02009-07-29 17:15:45 +00003568public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003569 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003570 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003571 /// level pointer and cv-qualifiers.
3572 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3573 if (QT->isPointerType())
3574 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003575
Aaron Ballman8aee642902015-04-08 00:05:29 +00003576 if (IsPointer || QT->isReferenceType())
3577 QT = QT->getPointeeType();
3578 QT = QT.getUnqualifiedType();
3579 }
3580
3581 /// Used when creating a CatchHandlerType from a base class type; pretends the
3582 /// type passed in had the pointer qualifier, does not need to get an
3583 /// unqualified type.
3584 CatchHandlerType(QualType QT, bool IsPointer)
3585 : QT(QT), IsPointer(IsPointer) {}
3586
3587 QualType underlying() const { return QT; }
3588 bool isPointer() const { return IsPointer; }
3589
3590 friend bool operator==(const CatchHandlerType &LHS,
3591 const CatchHandlerType &RHS) {
3592 // If the pointer qualification does not match, we can return early.
3593 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003594 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003595 // Otherwise, check the underlying type without cv-qualifiers.
3596 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003597 }
3598};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003599} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003600
Aaron Ballman8aee642902015-04-08 00:05:29 +00003601namespace llvm {
3602template <> struct DenseMapInfo<CatchHandlerType> {
3603 static CatchHandlerType getEmptyKey() {
3604 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3605 CatchHandlerType::ForDenseMap);
3606 }
3607
3608 static CatchHandlerType getTombstoneKey() {
3609 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3610 CatchHandlerType::ForDenseMap);
3611 }
3612
3613 static unsigned getHashValue(const CatchHandlerType &Base) {
3614 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3615 }
3616
3617 static bool isEqual(const CatchHandlerType &LHS,
3618 const CatchHandlerType &RHS) {
3619 return LHS == RHS;
3620 }
3621};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003622}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003623
3624namespace {
3625class CatchTypePublicBases {
3626 ASTContext &Ctx;
3627 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3628 const bool CheckAgainstPointer;
3629
3630 CXXCatchStmt *FoundHandler;
3631 CanQualType FoundHandlerType;
3632
3633public:
3634 CatchTypePublicBases(
3635 ASTContext &Ctx,
3636 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3637 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3638 FoundHandler(nullptr) {}
3639
3640 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3641 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3642
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003643 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003644 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003645 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003646 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003647 auto I = M.find(Check);
3648 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003649 FoundHandler = I->second;
3650 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003651 return true;
3652 }
3653 }
3654 return false;
3655 }
3656};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003657}
Dan Gohman28ade552010-07-26 21:25:24 +00003658
Sebastian Redl9b244a82008-12-22 21:35:02 +00003659/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3660/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003661StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3662 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003663 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003664 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003665 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003666 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003667
Justin Lebar2a8db342016-09-28 22:45:54 +00003668 // Exceptions aren't allowed in CUDA device code.
3669 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00003670 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3671 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00003672
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003673 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3674 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3675
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003676 sema::FunctionScopeInfo *FSI = getCurFunction();
3677
Reid Klecknere7175912015-02-02 22:15:31 +00003678 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003679 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003680 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003681 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003682 }
3683
Robert Wilhelmcafda822013-08-22 09:20:03 +00003684 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003685 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003686 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003687
Aaron Ballman8aee642902015-04-08 00:05:29 +00003688 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003689 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003690 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003691
Aaron Ballman8aee642902015-04-08 00:05:29 +00003692 // Diagnose when the handler is a catch-all handler, but it isn't the last
3693 // handler for the try block. [except.handle]p5. Also, skip exception
3694 // declarations that are invalid, since we can't usefully report on them.
3695 if (!H->getExceptionDecl()) {
3696 if (i < NumHandlers - 1)
3697 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003698 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003699 } else if (H->getExceptionDecl()->isInvalidDecl())
3700 continue;
3701
3702 // Walk the type hierarchy to diagnose when this type has already been
3703 // handled (duplication), or cannot be handled (derivation inversion). We
3704 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003705 CatchHandlerType HandlerCHT =
3706 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003707
3708 // We can ignore whether the type is a reference or a pointer; we need the
3709 // underlying declaration type in order to get at the underlying record
3710 // decl, if there is one.
3711 QualType Underlying = HandlerCHT.underlying();
3712 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3713 if (!RD->hasDefinition())
3714 continue;
3715 // Check that none of the public, unambiguous base classes are in the
3716 // map ([except.handle]p1). Give the base classes the same pointer
3717 // qualification as the original type we are basing off of. This allows
3718 // comparison against the handler type using the same top-level pointer
3719 // as the original type.
3720 CXXBasePaths Paths;
3721 Paths.setOrigin(RD);
3722 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003723 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003724 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3725 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3726 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3727 diag::warn_exception_caught_by_earlier_handler)
3728 << H->getCaughtType();
3729 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3730 diag::note_previous_exception_handler)
3731 << Problem->getCaughtType();
3732 }
3733 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003734 }
Mike Stump11289f42009-09-09 15:08:12 +00003735
Aaron Ballman8aee642902015-04-08 00:05:29 +00003736 // Add the type the list of ones we have handled; diagnose if we've already
3737 // handled it.
3738 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3739 if (!R.second) {
3740 const CXXCatchStmt *Problem = R.first->second;
3741 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3742 diag::warn_exception_caught_by_earlier_handler)
3743 << H->getCaughtType();
3744 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3745 diag::note_previous_exception_handler)
3746 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003747 }
3748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003750 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003751
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003752 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003753}
John Wiegley1c0675e2011-04-28 01:08:34 +00003754
Reid Klecknere7175912015-02-02 22:15:31 +00003755StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3756 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003757 assert(TryBlock && Handler);
3758
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003759 sema::FunctionScopeInfo *FSI = getCurFunction();
3760
Reid Klecknere7175912015-02-02 22:15:31 +00003761 // SEH __try is incompatible with C++ try. Borland appears to support this,
3762 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003763 if (!getLangOpts().Borland) {
3764 if (FSI->FirstCXXTryLoc.isValid()) {
3765 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3766 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3767 }
Reid Klecknere7175912015-02-02 22:15:31 +00003768 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003769
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003770 FSI->setHasSEHTry(TryLoc);
3771
3772 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3773 // track if they use SEH.
3774 DeclContext *DC = CurContext;
3775 while (DC && !DC->isFunctionOrMethod())
3776 DC = DC->getParent();
3777 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3778 if (FD)
3779 FD->setUsesSEHTry(true);
3780 else
3781 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003782
Reid Kleckner8819a402015-07-10 00:16:25 +00003783 // Reject __try on unsupported targets.
3784 if (!Context.getTargetInfo().isSEHTrySupported())
3785 Diag(TryLoc, diag::err_seh_try_unsupported);
3786
Reid Klecknere7175912015-02-02 22:15:31 +00003787 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003788}
3789
3790StmtResult
3791Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3792 Expr *FilterExpr,
3793 Stmt *Block) {
3794 assert(FilterExpr && Block);
3795
3796 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003797 return StmtError(Diag(FilterExpr->getExprLoc(),
3798 diag::err_filter_expression_integral)
3799 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003800 }
3801
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003802 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003803}
3804
Nico Weberd64657f2015-03-09 02:47:59 +00003805void Sema::ActOnStartSEHFinallyBlock() {
3806 CurrentSEHFinally.push_back(CurScope);
3807}
3808
Nico Weberce903292015-03-09 03:17:15 +00003809void Sema::ActOnAbortSEHFinallyBlock() {
3810 CurrentSEHFinally.pop_back();
3811}
3812
Nico Weberd64657f2015-03-09 02:47:59 +00003813StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003814 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003815 CurrentSEHFinally.pop_back();
3816 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003817}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003818
Nico Weberc7d05962014-07-06 22:32:59 +00003819StmtResult
3820Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003821 Scope *SEHTryParent = CurScope;
3822 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3823 SEHTryParent = SEHTryParent->getParent();
3824 if (!SEHTryParent)
3825 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003826 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003827
Nico Weber9b982072014-07-07 00:12:30 +00003828 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003829}
3830
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003831StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3832 bool IsIfExists,
3833 NestedNameSpecifierLoc QualifierLoc,
3834 DeclarationNameInfo NameInfo,
3835 Stmt *Nested)
3836{
3837 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003838 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003839 cast<CompoundStmt>(Nested));
3840}
3841
3842
Chad Rosier02a84392012-08-10 17:56:09 +00003843StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003844 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003845 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003846 UnqualifiedId &Name,
3847 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003848 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003849 SS.getWithLocInContext(Context),
3850 GetNameFromUnqualifiedId(Name),
3851 Nested);
3852}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003853
3854RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003855Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3856 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003857 DeclContext *DC = CurContext;
3858 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3859 DC = DC->getParent();
3860
Craig Topperc3ec1492014-05-26 06:22:03 +00003861 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003862 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003863 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3864 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003865 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003866 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003867
Alexey Bataev330de032014-10-29 12:21:55 +00003868 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003869 DC->addDecl(RD);
3870 RD->setImplicit();
3871 RD->startDefinition();
3872
Alexey Bataev9959db52014-05-06 10:08:46 +00003873 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003874 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003875 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003876 return RD;
3877}
3878
3879static void buildCapturedStmtCaptureList(
3880 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3881 SmallVectorImpl<Expr *> &CaptureInits,
3882 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3883
3884 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3885 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3886
3887 if (Cap->isThisCapture()) {
3888 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3889 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003890 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003891 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003892 } else if (Cap->isVLATypeCapture()) {
3893 Captures.push_back(
3894 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3895 CaptureInits.push_back(nullptr);
3896 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003897 }
3898
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003899 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003900 Cap->isReferenceCapture()
3901 ? CapturedStmt::VCK_ByRef
3902 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003903 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003904 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003905 }
3906}
3907
3908void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003909 CapturedRegionKind Kind,
3910 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003911 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003912 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003913
Alexey Bataev9959db52014-05-06 10:08:46 +00003914 // Build the context parameter
3915 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3916 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3917 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3918 ImplicitParamDecl *Param
3919 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3920 DC->addDecl(Param);
3921
3922 CD->setContextParam(0, Param);
3923
3924 // Enter the capturing scope for this captured region.
3925 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3926
3927 if (CurScope)
3928 PushDeclContext(CurScope, CD);
3929 else
3930 CurContext = CD;
3931
Faisal Valid143a0c2017-04-01 21:30:49 +00003932 PushExpressionEvaluationContext(
3933 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00003934}
3935
3936void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3937 CapturedRegionKind Kind,
3938 ArrayRef<CapturedParamNameType> Params) {
3939 CapturedDecl *CD = nullptr;
3940 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3941
3942 // Build the context parameter
3943 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3944 bool ContextIsFound = false;
3945 unsigned ParamNum = 0;
3946 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3947 E = Params.end();
3948 I != E; ++I, ++ParamNum) {
3949 if (I->second.isNull()) {
3950 assert(!ContextIsFound &&
3951 "null type has been found already for '__context' parameter");
3952 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3953 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3954 ImplicitParamDecl *Param
3955 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3956 DC->addDecl(Param);
3957 CD->setContextParam(ParamNum, Param);
3958 ContextIsFound = true;
3959 } else {
3960 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3961 ImplicitParamDecl *Param
3962 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3963 DC->addDecl(Param);
3964 CD->setParam(ParamNum, Param);
3965 }
3966 }
3967 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003968 if (!ContextIsFound) {
3969 // Add __context implicitly if it is not specified.
3970 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3971 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3972 ImplicitParamDecl *Param =
3973 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3974 DC->addDecl(Param);
3975 CD->setContextParam(ParamNum, Param);
3976 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003977 // Enter the capturing scope for this captured region.
3978 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3979
3980 if (CurScope)
3981 PushDeclContext(CurScope, CD);
3982 else
3983 CurContext = CD;
3984
Faisal Valid143a0c2017-04-01 21:30:49 +00003985 PushExpressionEvaluationContext(
3986 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003987}
3988
Wei Pan17fbf6e2013-05-04 03:59:06 +00003989void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003990 DiscardCleanupsInEvaluationContext();
3991 PopExpressionEvaluationContext();
3992
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003993 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3994 RecordDecl *Record = RSI->TheRecordDecl;
3995 Record->setInvalidDecl();
3996
Aaron Ballman62e47c42014-03-10 13:43:55 +00003997 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003998 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3999 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004000
Wei Pan17fbf6e2013-05-04 03:59:06 +00004001 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004002 PopFunctionScopeInfo();
4003}
4004
4005StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4006 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4007
4008 SmallVector<CapturedStmt::Capture, 4> Captures;
4009 SmallVector<Expr *, 4> CaptureInits;
4010 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4011
4012 CapturedDecl *CD = RSI->TheCapturedDecl;
4013 RecordDecl *RD = RSI->TheRecordDecl;
4014
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004015 CapturedStmt *Res = CapturedStmt::Create(
4016 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4017 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004018
4019 CD->setBody(Res->getCapturedStmt());
4020 RD->completeDefinition();
4021
Wei Pan17fbf6e2013-05-04 03:59:06 +00004022 DiscardCleanupsInEvaluationContext();
4023 PopExpressionEvaluationContext();
4024
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004025 PopDeclContext();
4026 PopFunctionScopeInfo();
4027
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004028 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004029}