blob: 14f7092e1554f868def21581fec7cdf322831af1 [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"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000022#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000023#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000025#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000031#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000036using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000037using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000038
Richard Smith945f8d32013-01-14 22:39:08 +000039StmtResult Sema::ActOnExprStmt(ExprResult FE) {
40 if (FE.isInvalid())
41 return StmtError();
42
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
45 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000046 return StmtError();
47
Chris Lattner903eb512008-07-25 23:18:17 +000048 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000051
Chris Lattner903eb512008-07-25 23:18:17 +000052 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000053 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000054}
55
56
John McCalleaef89b2013-03-22 02:10:40 +000057StmtResult Sema::ActOnExprStmtError() {
58 DiscardCleanupsInEvaluationContext();
59 return StmtError();
60}
61
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000062StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000063 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000065}
66
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000067StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
68 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000069 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000070
Chris Lattnercbafe8d2009-04-12 20:13:14 +000071 // If we have an invalid decl, just return an error.
72 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000073
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000074 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000075}
Chris Lattneraf8d5812006-11-10 05:07:45 +000076
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000077void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000078 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000079
Douglas Gregor2eb1c572013-04-08 20:52:24 +000080 // If we don't have a declaration, or we have an invalid declaration,
81 // just return.
82 if (DG.isNull() || !DG.isSingleDecl())
83 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 Decl *decl = DG.getSingleDecl();
86 if (!decl || decl->isInvalidDecl())
87 return;
88
89 // Only variable declarations are permitted.
90 VarDecl *var = dyn_cast<VarDecl>(decl);
91 if (!var) {
92 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
93 decl->setInvalidDecl();
94 return;
95 }
John McCall31168b02011-06-15 23:02:42 +000096
John McCalld4631322011-06-17 06:42:21 +000097 // foreach variables are never actually initialized in the way that
98 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +000099 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // In ARC, we don't need to retain the iteration variable of a fast
102 // enumeration loop. Rather than actually trying to catch that
103 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000104 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000105 QualType type = var->getType();
106
107 // Only do this if we inferred the lifetime. Inferred lifetime
108 // will show up as a local qualifier because explicit lifetime
109 // should have shown up as an AttributedType instead.
110 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
111 // Add 'const' and mark the variable as pseudo-strong.
112 var->setType(type.withConst());
113 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000114 }
115 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000116}
117
Richard Trieu99e1c952014-03-11 03:11:08 +0000118/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
119/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000120///
121/// Adding a cast to void (or other expression wrappers) will prevent the
122/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000123static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000125 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000126
127 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000128 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000129 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
Richard Trieu99e1c952014-03-11 03:11:08 +0000131 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 switch (Op->getOperator()) {
137 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000138 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000139 case OO_EqualEqual:
140 case OO_ExclaimEqual:
141 IsRelational = false;
142 break;
143 case OO_Less:
144 case OO_Greater:
145 case OO_GreaterEqual:
146 case OO_LessEqual:
147 IsRelational = true;
148 break;
149 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000150
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000151 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000152 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
153 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154 } else {
155 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000156 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000157 }
158
159 // Suppress warnings when the operator, suspicious as it may be, comes from
160 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000161 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000162 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000163
Chandler Carruthe2669392011-08-17 09:34:37 +0000164 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000165 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000166
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000167 // If the LHS is a plausible entity to assign to, provide a fixit hint to
168 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000170 if (IsNotEqual)
171 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
172 << FixItHint::CreateReplacement(Loc, "|=");
173 else
174 S.Diag(Loc, diag::note_equality_comparison_to_assign)
175 << FixItHint::CreateReplacement(Loc, "=");
176 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000177
178 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000179}
180
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000181void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000182 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
183 return DiagnoseUnusedExprResult(Label->getSubStmt());
184
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000185 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186 if (!E)
187 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000188
189 // If we are in an unevaluated expression context, then there can be no unused
190 // results because the results aren't expected to be used in the first place.
191 if (isUnevaluatedContext())
192 return;
193
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000194 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000195 // In most cases, we don't want to warn if the expression is written in a
196 // macro body, or if the macro comes from a system header. If the offending
197 // expression is a call to a function with the warn_unused_result attribute,
198 // we warn no matter the location. Because of the order in which the various
199 // checks need to happen, we factor out the macro-related test here.
200 bool ShouldSuppress =
201 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
202 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000203
Eli Friedmanc11535c2012-05-24 00:47:05 +0000204 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000205 SourceLocation Loc;
206 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000207 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208 return;
Mike Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattner6dc7e572012-08-31 22:39:21 +0000210 // If this is a GNU statement expression expanded from a macro, it is probably
211 // unused because it is a function-like macro that can be used as either an
212 // expression or statement. Don't warn, because it is almost certainly a
213 // false positive.
214 if (isa<StmtExpr>(E) && Loc.isMacroID())
215 return;
216
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000217 // Okay, we have an unused result. Depending on what the base expression is,
218 // we might want to make a more specific diagnostic. Check for one of these
219 // cases now.
220 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000221 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000222 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000223 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
224 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000225
Chandler Carruthe2669392011-08-17 09:34:37 +0000226 if (DiagnoseUnusedComparison(*this, E))
227 return;
228
Eli Friedmanc11535c2012-05-24 00:47:05 +0000229 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000230 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000231 if (E->getType()->isVoidType())
232 return;
233
Chris Lattner1a6babf2009-10-13 04:53:48 +0000234 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000235 // a more specific message to make it clear what is happening. If the call
236 // is written in a macro body, only warn if it has the warn_unused_result
237 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000238 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000239 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000240 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000241 return;
242 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000243 if (ShouldSuppress)
244 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000245 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000246 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
247 return;
248 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000249 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000250 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
251 return;
252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000253 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000254 } else if (ShouldSuppress)
255 return;
256
257 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000258 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000259 Diag(Loc, diag::err_arc_unused_init_message) << R1;
260 return;
261 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000262 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000263 if (MD) {
264 if (MD->hasAttr<WarnUnusedResultAttr>()) {
265 Diag(Loc, diag::warn_unused_result) << R1 << R2;
266 return;
267 }
268 if (MD->isPropertyAccessor()) {
269 Diag(Loc, diag::warn_unused_property_expr);
270 return;
271 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000272 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
274 const Expr *Source = POE->getSyntacticForm();
275 if (isa<ObjCSubscriptRefExpr>(Source))
276 DiagID = diag::warn_unused_container_subscript_expr;
277 else
278 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000279 } else if (const CXXFunctionalCastExpr *FC
280 = dyn_cast<CXXFunctionalCastExpr>(E)) {
281 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
282 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
283 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
John McCall2351cb92010-04-06 22:24:14 +0000285 // Diagnose "(void*) blah" as a typo for "(void) blah".
286 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
287 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
288 QualType T = TI->getType();
289
290 // We really do want to use the non-canonical type here.
291 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000292 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000293
294 Diag(Loc, diag::warn_unused_voidptr)
295 << FixItHint::CreateRemoval(TL.getStarLoc());
296 return;
297 }
298 }
299
Eli Friedmanc11535c2012-05-24 00:47:05 +0000300 if (E->isGLValue() && E->getType().isVolatileQualified()) {
301 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
302 return;
303 }
304
Craig Topperc3ec1492014-05-26 06:22:03 +0000305 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000306}
307
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000308void Sema::ActOnStartOfCompoundStmt() {
309 PushCompoundScope();
310}
311
312void Sema::ActOnFinishOfCompoundStmt() {
313 PopCompoundScope();
314}
315
316sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
317 return getCurFunction()->CompoundScopes.back();
318}
319
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000320StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
321 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
322 const unsigned NumElts = Elts.size();
323
Chris Lattnerd864daf2007-08-27 04:29:41 +0000324 // If we're in C89 mode, check that we don't have any decls after stmts. If
325 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000326 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000327 // Note that __extension__ can be around a decl.
328 unsigned i = 0;
329 // Skip over all declarations.
330 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
331 /*empty*/;
332
333 // We found the end of the list or a statement. Scan for another declstmt.
334 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
335 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000336
Chris Lattnerd864daf2007-08-27 04:29:41 +0000337 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000338 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000339 Diag(D->getLocation(), diag::ext_mixed_decls_code);
340 }
341 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000342 // Warn about unused expressions in statements.
343 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000344 // Ignore statements that are last in a statement expression.
345 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000346 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000347
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000348 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000349 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000350
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000351 // Check for suspicious empty body (null statement) in `for' and `while'
352 // statements. Don't do anything for template instantiations, this just adds
353 // noise.
354 if (NumElts != 0 && !CurrentInstantiationScope &&
355 getCurCompoundScope().HasEmptyLoopBodies) {
356 for (unsigned i = 0; i != NumElts - 1; ++i)
357 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
358 }
359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000360 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000361}
362
John McCalldadc5752010-08-24 06:29:42 +0000363StmtResult
John McCallb268a282010-08-23 23:25:46 +0000364Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
365 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000366 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000367 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000368
John McCallaab3e412010-08-25 08:40:02 +0000369 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000370 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000371 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000372 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000373
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000374 ExprResult LHS =
375 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
376 if (!getLangOpts().CPlusPlus11)
377 return VerifyIntegerConstantExpression(E);
378 if (Expr *CondExpr =
379 getCurFunction()->SwitchStack.back()->getCond()) {
380 QualType CondType = CondExpr->getType();
381 llvm::APSInt TempVal;
382 return CheckConvertedConstantExpression(E, CondType, TempVal,
383 CCEK_CaseValue);
384 }
385 return ExprError();
386 });
387 if (LHS.isInvalid())
388 return StmtError();
389 LHSVal = LHS.get();
390
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000391 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000392 // C99 6.8.4.2p3: The expression shall be an integer constant.
393 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000394 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000395 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000396 if (!LHSVal)
397 return StmtError();
398 }
Richard Smithf8379a02012-01-18 23:55:52 +0000399
400 // GCC extension: The expression shall be an integer constant.
401
Richard Smithf4c51d92012-02-04 09:53:13 +0000402 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000403 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000404 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000405 }
406 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000407
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000408 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000409 getLangOpts().CPlusPlus11);
410 if (LHS.isInvalid())
411 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000412
Richard Smith5b555da2014-11-20 01:24:12 +0000413 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
414 getLangOpts().CPlusPlus11)
415 : ExprResult();
416 if (RHS.isInvalid())
417 return StmtError();
418
419 CaseStmt *CS = new (Context)
420 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000421 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000422 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000423}
424
Chris Lattner34a22092009-03-04 04:23:07 +0000425/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000426void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000427 DiagnoseUnusedExprResult(SubStmt);
428
Chris Lattner34a22092009-03-04 04:23:07 +0000429 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000430 CS->setSubStmt(SubStmt);
431}
432
John McCalldadc5752010-08-24 06:29:42 +0000433StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000434Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000435 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000436 DiagnoseUnusedExprResult(SubStmt);
437
John McCallaab3e412010-08-25 08:40:02 +0000438 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000439 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000441 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000442
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000443 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000444 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000445 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000446}
447
John McCalldadc5752010-08-24 06:29:42 +0000448StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000449Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
450 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000451 // If the label was multiply defined, reject it now.
452 if (TheDecl->getStmt()) {
453 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
454 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000455 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000456 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000457
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000458 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000459 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
460 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000461 if (!TheDecl->isGnuLocal()) {
462 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000463 if (!TheDecl->isMSAsmLabel()) {
464 // Don't update the location of MS ASM labels. These will result in
465 // a diagnostic, and changing the location here will mess that up.
466 TheDecl->setLocation(IdentLoc);
467 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000468 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000469 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000470}
471
Richard Smithc202b282012-04-14 00:33:13 +0000472StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000473 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000474 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000475 // Fill in the declaration and return it.
476 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000477 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000478}
479
John McCalldadc5752010-08-24 06:29:42 +0000480StmtResult
John McCall48871652010-08-21 09:40:31 +0000481Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000482 Stmt *thenStmt, SourceLocation ElseLoc,
483 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000484 // If the condition was invalid, discard the if statement. We could recover
485 // better by replacing it with a valid expr, but don't do that yet.
486 if (!CondVal.get() && !CondVar) {
487 getCurFunction()->setHasDroppedStmt();
488 return StmtError();
489 }
490
John McCalldadc5752010-08-24 06:29:42 +0000491 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000492
Craig Topperc3ec1492014-05-26 06:22:03 +0000493 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000494 if (CondVar) {
495 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000496 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000497 if (CondResult.isInvalid())
498 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000499 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000500 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000501 if (!ConditionExpr)
502 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000504 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000505
John McCallb268a282010-08-23 23:25:46 +0000506 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000507 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
508 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000509 }
510
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000511 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000512
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000513 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
514 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000515}
Steve Naroff86272ea2007-05-29 02:14:17 +0000516
Chris Lattner67998452007-08-23 18:29:20 +0000517namespace {
518 struct CaseCompareFunctor {
519 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
520 const llvm::APSInt &RHS) {
521 return LHS.first < RHS;
522 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000523 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
524 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
525 return LHS.first < RHS.first;
526 }
Chris Lattner67998452007-08-23 18:29:20 +0000527 bool operator()(const llvm::APSInt &LHS,
528 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
529 return LHS < RHS.first;
530 }
531 };
532}
533
Chris Lattner4b2ff022007-09-21 18:15:22 +0000534/// CmpCaseVals - Comparison predicate for sorting case values.
535///
536static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
537 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
538 if (lhs.first < rhs.first)
539 return true;
540
541 if (lhs.first == rhs.first &&
542 lhs.second->getCaseLoc().getRawEncoding()
543 < rhs.second->getCaseLoc().getRawEncoding())
544 return true;
545 return false;
546}
547
Douglas Gregorbd6839732010-02-08 22:24:16 +0000548/// CmpEnumVals - Comparison predicate for sorting enumeration values.
549///
550static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
551 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
552{
553 return lhs.first < rhs.first;
554}
555
556/// EqEnumVals - Comparison preficate for uniqing enumeration values.
557///
558static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
559 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
560{
561 return lhs.first == rhs.first;
562}
563
Chris Lattnera96d4272009-10-16 16:45:22 +0000564/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
565/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000566static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
567 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
568 expr = cleanups->getSubExpr();
569 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
570 if (impcast->getCastKind() != CK_IntegralCast) break;
571 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000572 }
573 return expr->getType();
574}
575
John McCalldadc5752010-08-24 06:29:42 +0000576StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000578 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000579 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000580
Craig Topperc3ec1492014-05-26 06:22:03 +0000581 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000582 if (CondVar) {
583 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000584 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
585 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000586 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000588 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
John McCallb268a282010-08-23 23:25:46 +0000591 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000592 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregore2b37442012-05-04 22:38:52 +0000594 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
595 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000596
Douglas Gregore2b37442012-05-04 22:38:52 +0000597 public:
598 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000599 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
600 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000601
Craig Toppere14c0f82014-03-12 04:55:44 +0000602 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
603 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000604 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
605 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000606
Craig Toppere14c0f82014-03-12 04:55:44 +0000607 SemaDiagnosticBuilder diagnoseIncomplete(
608 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000609 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
610 << T << Cond->getSourceRange();
611 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000612
Craig Toppere14c0f82014-03-12 04:55:44 +0000613 SemaDiagnosticBuilder diagnoseExplicitConv(
614 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000615 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
616 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000617
Craig Toppere14c0f82014-03-12 04:55:44 +0000618 SemaDiagnosticBuilder noteExplicitConv(
619 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000620 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
621 << ConvTy->isEnumeralType() << ConvTy;
622 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000623
Craig Toppere14c0f82014-03-12 04:55:44 +0000624 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
625 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000626 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
627 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000628
Craig Toppere14c0f82014-03-12 04:55:44 +0000629 SemaDiagnosticBuilder noteAmbiguous(
630 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000631 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
632 << ConvTy->isEnumeralType() << ConvTy;
633 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000634
Craig Toppere14c0f82014-03-12 04:55:44 +0000635 SemaDiagnosticBuilder diagnoseConversion(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000637 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000638 }
639 } SwitchDiagnoser(Cond);
640
Richard Smithccc11812013-05-21 19:05:48 +0000641 CondResult =
642 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000643 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000644 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
John McCall5939b162011-08-06 07:30:58 +0000646 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
647 CondResult = UsualUnaryConversions(Cond);
648 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000649 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000650
John McCall48871652010-08-21 09:40:31 +0000651 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000652 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000653 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000654 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000655 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000656 }
John McCalla95172b2010-08-01 00:26:45 +0000657
John McCallaab3e412010-08-25 08:40:02 +0000658 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
John McCallb268a282010-08-23 23:25:46 +0000660 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000661 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000662 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000663}
664
Gabor Greif16e02862010-10-01 22:05:14 +0000665static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000666 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000667 Val.setIsSigned(IsSigned);
668}
669
Richard Smith077d0832014-08-04 00:40:48 +0000670/// Check the specified case value is in range for the given unpromoted switch
671/// type.
672static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
673 unsigned UnpromotedWidth, bool UnpromotedSign) {
674 // If the case value was signed and negative and the switch expression is
675 // unsigned, don't bother to warn: this is implementation-defined behavior.
676 // FIXME: Introduce a second, default-ignored warning for this case?
677 if (UnpromotedWidth < Val.getBitWidth()) {
678 llvm::APSInt ConvVal(Val);
679 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
680 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
681 // FIXME: Use different diagnostics for overflow in conversion to promoted
682 // type versus "switch expression cannot have this value". Use proper
683 // IntRange checking rather than just looking at the unpromoted type here.
684 if (ConvVal != Val)
685 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
686 << ConvVal.toString(10);
687 }
688}
689
Dmitri Gribenko58683752013-12-05 22:52:07 +0000690/// Returns true if we should emit a diagnostic about this case expression not
691/// being a part of the enum used in the switch controlling expression.
692static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
693 const EnumDecl *ED,
694 const Expr *CaseExpr) {
695 // Don't warn if the 'case' expression refers to a static const variable of
696 // the enum type.
697 CaseExpr = CaseExpr->IgnoreParenImpCasts();
698 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
699 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
700 if (!VD->hasGlobalStorage())
701 return true;
702 QualType VarType = VD->getType();
703 if (!VarType.isConstQualified())
704 return true;
705 QualType EnumType = Ctx.getTypeDeclType(ED);
706 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
707 return false;
708 }
709 }
710 return true;
711}
712
John McCalldadc5752010-08-24 06:29:42 +0000713StmtResult
John McCallb268a282010-08-23 23:25:46 +0000714Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
715 Stmt *BodyStmt) {
716 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000717 assert(SS == getCurFunction()->SwitchStack.back() &&
718 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000719
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000720 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000721 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000722 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000723
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000724 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000725 if (!CondExpr) return StmtError();
726
727 QualType CondType = CondExpr->getType();
728
John McCalld3dfbd62010-05-18 03:19:21 +0000729 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000730 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000731 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000732
Chris Lattnera96d4272009-10-16 16:45:22 +0000733 // C++ 6.4.2.p2:
734 // Integral promotions are performed (on the switch condition).
735 //
736 // A case value unrepresentable by the original switch condition
737 // type (before the promotion) doesn't make sense, even when it can
738 // be represented by the promoted type. Therefore we need to find
739 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000740 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000741 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000743 // appropriate type now, just return an error.
744 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000745 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000746
Chris Lattner4ebae652010-04-16 23:34:13 +0000747 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000748 // switch(bool_expr) {...} is often a programmer error, e.g.
749 // switch(n && mask) { ... } // Doh - should be "n & mask".
750 // One can always use an if statement instead of switch(bool_expr).
751 Diag(SwitchLoc, diag::warn_bool_switch_condition)
752 << CondExpr->getSourceRange();
753 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000754 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000755
Richard Smith077d0832014-08-04 00:40:48 +0000756 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000757 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000758 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000759 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000760 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
761 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
762
763 // Get the width and signedness that the condition might actually have, for
764 // warning purposes.
765 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
766 // type.
767 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000768 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000769 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000770 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000771
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000772 // Accumulate all of the case values in a vector so that we can sort them
773 // and detect duplicates. This vector contains the APInt for the case after
774 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000775 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000776 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000777
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000778 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000779 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
780 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000781
Craig Topperc3ec1492014-05-26 06:22:03 +0000782 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattner10cb5e52007-08-23 06:23:56 +0000784 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000786 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000787 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000788
Anders Carlsson51873c22007-07-22 07:07:56 +0000789 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000790 if (TheDefaultStmt) {
791 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000792 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000793
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000794 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000795 // we'll return a valid AST. This requires recursing down the AST and
796 // finding it, not something we are set up to do right now. For now,
797 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000798 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000799 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000800 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000802 } else {
803 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000804
Chris Lattnera65e1f32008-01-16 19:17:22 +0000805 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000806
807 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
808 HasDependentValue = true;
809 break;
810 }
Mike Stump11289f42009-09-09 15:08:12 +0000811
Richard Smithf8379a02012-01-18 23:55:52 +0000812 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000813
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000814 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000815 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
816 // constant expression of the promoted type of the switch condition.
817 ExprResult ConvLo =
818 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
819 if (ConvLo.isInvalid()) {
820 CaseListIsErroneous = true;
821 continue;
822 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000823 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000824 } else {
825 // We already verified that the expression has a i-c-e value (C99
826 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000827 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000828
829 // If the LHS is not the same type as the condition, insert an implicit
830 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000831 Lo = DefaultLvalueConversion(Lo).get();
832 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000833 }
834
Richard Smith077d0832014-08-04 00:40:48 +0000835 // Check the unconverted value is within the range of possible values of
836 // the switch expression.
837 checkCaseValue(*this, Lo->getLocStart(), LoVal,
838 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
839
840 // Convert the value to the same width/sign as the condition.
841 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000842
Chris Lattnera65e1f32008-01-16 19:17:22 +0000843 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000844
Chris Lattner10cb5e52007-08-23 06:23:56 +0000845 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000846 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000847 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000848 CS->getRHS()->isValueDependent()) {
849 HasDependentValue = true;
850 break;
851 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000852 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000853 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000854 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000855 }
856 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000857
858 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000859 // If we don't have a default statement, check whether the
860 // condition is constant.
861 llvm::APSInt ConstantCondValue;
862 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000863 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000864 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
865 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000866 assert(!HasConstantCond ||
867 (ConstantCondValue.getBitWidth() == CondWidth &&
868 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000869 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000870 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000871
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000872 // Sort all the scalar case values so we can easily detect duplicates.
873 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
874
875 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000876 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
877 if (ShouldCheckConstantCond &&
878 CaseVals[i].first == ConstantCondValue)
879 ShouldCheckConstantCond = false;
880
881 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000882 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000883 // First, determine if either case value has a name
884 StringRef PrevString, CurrString;
885 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
886 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
887 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
888 PrevString = DeclRef->getDecl()->getName();
889 }
890 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
891 CurrString = DeclRef->getDecl()->getName();
892 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000893 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000894 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000895
896 if (PrevString == CurrString)
897 Diag(CaseVals[i].second->getLHS()->getLocStart(),
898 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000899 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000900 else
901 Diag(CaseVals[i].second->getLHS()->getLocStart(),
902 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000903 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
904 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000905 CaseValStr;
906
John McCalld3dfbd62010-05-18 03:19:21 +0000907 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000908 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000909 // FIXME: We really want to remove the bogus case stmt from the
910 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000911 CaseListIsErroneous = true;
912 }
913 }
914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000916 // Detect duplicate case ranges, which usually don't exist at all in
917 // the first place.
918 if (!CaseRanges.empty()) {
919 // Sort all the case ranges by their low value so we can easily detect
920 // overlaps between ranges.
921 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000923 // Scan the ranges, computing the high values and removing empty ranges.
924 std::vector<llvm::APSInt> HiVals;
925 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000926 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000927 CaseStmt *CR = CaseRanges[i].second;
928 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000929 llvm::APSInt HiVal;
930
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000931 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000932 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
933 // constant expression of the promoted type of the switch condition.
934 ExprResult ConvHi =
935 CheckConvertedConstantExpression(Hi, CondType, HiVal,
936 CCEK_CaseValue);
937 if (ConvHi.isInvalid()) {
938 CaseListIsErroneous = true;
939 continue;
940 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000941 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000942 } else {
943 HiVal = Hi->EvaluateKnownConstInt(Context);
944
945 // If the RHS is not the same type as the condition, insert an
946 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000947 Hi = DefaultLvalueConversion(Hi).get();
948 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
Richard Smith077d0832014-08-04 00:40:48 +0000951 // Check the unconverted value is within the range of possible values of
952 // the switch expression.
953 checkCaseValue(*this, Hi->getLocStart(), HiVal,
954 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
955
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000956 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000957 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000958
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000959 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000960
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000961 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000962 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000963 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
964 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000965 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000966 CaseRanges.erase(CaseRanges.begin()+i);
967 --i, --e;
968 continue;
969 }
John McCalld3dfbd62010-05-18 03:19:21 +0000970
971 if (ShouldCheckConstantCond &&
972 LoVal <= ConstantCondValue &&
973 ConstantCondValue <= HiVal)
974 ShouldCheckConstantCond = false;
975
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000976 HiVals.push_back(HiVal);
977 }
Mike Stump11289f42009-09-09 15:08:12 +0000978
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000979 // Rescan the ranges, looking for overlap with singleton values and other
980 // ranges. Since the range list is sorted, we only need to compare case
981 // ranges with their neighbors.
982 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
983 llvm::APSInt &CRLo = CaseRanges[i].first;
984 llvm::APSInt &CRHi = HiVals[i];
985 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000986
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000987 // Check to see whether the case range overlaps with any
988 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +0000989 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000990 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 // Find the smallest value >= the lower bound. If I is in the
993 // case range, then we have overlap.
994 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
995 CaseVals.end(), CRLo,
996 CaseCompareFunctor());
997 if (I != CaseVals.end() && I->first < CRHi) {
998 OverlapVal = I->first; // Found overlap with scalar.
999 OverlapStmt = I->second;
1000 }
Mike Stump11289f42009-09-09 15:08:12 +00001001
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001002 // Find the smallest value bigger than the upper bound.
1003 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1004 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1005 OverlapVal = (I-1)->first; // Found overlap with scalar.
1006 OverlapStmt = (I-1)->second;
1007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001009 // Check to see if this case stmt overlaps with the subsequent
1010 // case range.
1011 if (i && CRLo <= HiVals[i-1]) {
1012 OverlapVal = HiVals[i-1]; // Found overlap with range.
1013 OverlapStmt = CaseRanges[i-1].second;
1014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001016 if (OverlapStmt) {
1017 // If we have a duplicate, report it.
1018 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1019 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001020 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001021 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001022 // FIXME: We really want to remove the bogus case stmt from the
1023 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001024 CaseListIsErroneous = true;
1025 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001026 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001027 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001028
John McCalld3dfbd62010-05-18 03:19:21 +00001029 // Complain if we have a constant condition and we didn't find a match.
1030 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1031 // TODO: it would be nice if we printed enums as enums, chars as
1032 // chars, etc.
1033 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1034 << ConstantCondValue.toString(10)
1035 << CondExpr->getSourceRange();
1036 }
1037
1038 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001039 // values. We only issue a warning if there is not 'default:', but
1040 // we still do the analysis to preserve this information in the AST
1041 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001042 //
Chris Lattner51679082010-09-16 17:09:42 +00001043 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001044
Douglas Gregorbd6839732010-02-08 22:24:16 +00001045 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001046 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001047 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001048 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +00001049 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001050 EnumValsTy EnumVals;
1051
John McCalld3dfbd62010-05-18 03:19:21 +00001052 // Gather all enum values, set their type and sort them,
1053 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001054 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001055 llvm::APSInt Val = EDI->getInitVal();
1056 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001057 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001058 }
1059 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +00001060 EnumValsTy::iterator EIend =
1061 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001062
1063 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001064 EnumValsTy::const_iterator EI = EnumVals.begin();
1065 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1066 CI != CaseVals.end(); CI++) {
1067 while (EI != EIend && EI->first < CI->first)
1068 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001069 if (EI == EIend || EI->first > CI->first) {
1070 Expr *CaseExpr = CI->second->getLHS();
1071 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1072 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1073 << CondTypeBeforePromotion;
1074 }
David Blaikiee476f972012-01-22 02:31:55 +00001075 }
1076 // See which of case ranges aren't in enum
1077 EI = EnumVals.begin();
1078 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1079 RI != CaseRanges.end() && EI != EIend; RI++) {
1080 while (EI != EIend && EI->first < RI->first)
1081 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001082
David Blaikiee476f972012-01-22 02:31:55 +00001083 if (EI == EIend || EI->first != RI->first) {
Dmitri Gribenko58683752013-12-05 22:52:07 +00001084 Expr *CaseExpr = RI->second->getLHS();
1085 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1086 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1087 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +00001088 }
David Blaikiee476f972012-01-22 02:31:55 +00001089
Chad Rosier02a84392012-08-10 17:56:09 +00001090 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001091 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1092 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1093 while (EI != EIend && EI->first < Hi)
1094 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001095 if (EI == EIend || EI->first != Hi) {
1096 Expr *CaseExpr = RI->second->getRHS();
1097 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1098 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1099 << CondTypeBeforePromotion;
1100 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
Ted Kremenekc42f3452010-09-09 00:05:53 +00001103 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +00001104 CaseValsTy::const_iterator CI = CaseVals.begin();
1105 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001106 bool hasCasesNotInSwitch = false;
1107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001108 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001109
David Blaikiee476f972012-01-22 02:31:55 +00001110 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001111 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001112 while (CI != CaseVals.end() && CI->first < EI->first)
1113 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001114
Douglas Gregorbd6839732010-02-08 22:24:16 +00001115 if (CI != CaseVals.end() && CI->first == EI->first)
1116 continue;
1117
Ted Kremenekc42f3452010-09-09 00:05:53 +00001118 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001119 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001120 llvm::APSInt Hi =
1121 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001122 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001123 if (EI->first <= Hi)
1124 break;
1125 }
1126
Ted Kremenekc42f3452010-09-09 00:05:53 +00001127 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001128 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001129 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001130 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
David Blaikie60ac6382012-01-23 04:46:12 +00001133 if (TheDefaultStmt && UnhandledNames.empty())
1134 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001135
Chris Lattner51679082010-09-16 17:09:42 +00001136 // Produce a nice diagnostic if multiple values aren't handled.
1137 switch (UnhandledNames.size()) {
1138 case 0: break;
1139 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001140 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001141 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001142 << UnhandledNames[0];
1143 break;
1144 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001145 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001146 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001147 << UnhandledNames[0] << UnhandledNames[1];
1148 break;
1149 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001150 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1151 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001152 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1153 break;
1154 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001155 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1156 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001157 << (unsigned)UnhandledNames.size()
1158 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1159 break;
1160 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001161
1162 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001163 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001164 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001165 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001166
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001167 if (BodyStmt)
1168 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1169 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001170
Mike Stump87c57ac2009-05-16 07:39:55 +00001171 // FIXME: If the case list was broken is some way, we don't have a good system
1172 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001173 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001174 return StmtError();
1175
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001176 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001177}
1178
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001179void
1180Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1181 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001182 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001183 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001184
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001185 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001186 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001187 SrcType->isIntegerType()) {
1188 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1189 SrcExpr->isIntegerConstantExpr(Context)) {
1190 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001191 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001192 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1193
1194 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001195 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001196 const EnumDecl *ED = ET->getDecl();
Joey Gouly1ba27332013-06-06 13:48:00 +00001197 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1198 EnumValsTy;
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001199 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001200
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001201 // Gather all enum values, set their type and sort them,
1202 // allowing easier comparison with rhs constant.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001203 for (auto *EDI : ED->enumerators()) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001204 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly1ba27332013-06-06 13:48:00 +00001205 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001206 EnumVals.push_back(std::make_pair(Val, EDI));
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001207 }
1208 if (EnumVals.empty())
1209 return;
1210 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1211 EnumValsTy::iterator EIend =
Joey Gouly1ba27332013-06-06 13:48:00 +00001212 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001213
Joey Gouly1ba27332013-06-06 13:48:00 +00001214 // See which values aren't in the enum.
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001215 EnumValsTy::const_iterator EI = EnumVals.begin();
1216 while (EI != EIend && EI->first < RhsVal)
1217 EI++;
1218 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly1ba27332013-06-06 13:48:00 +00001219 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001220 << DstType.getUnqualifiedType();
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001221 }
1222 }
1223 }
1224}
1225
John McCalldadc5752010-08-24 06:29:42 +00001226StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001228 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001229 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230
Craig Topperc3ec1492014-05-26 06:22:03 +00001231 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001232 if (CondVar) {
1233 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001234 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001235 if (CondResult.isInvalid())
1236 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001237 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001238 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001239 if (!ConditionExpr)
1240 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001241 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242
John McCallb268a282010-08-23 23:25:46 +00001243 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001244
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001245 if (isa<NullStmt>(Body))
1246 getCurCompoundScope().setHasEmptyLoopBodies();
1247
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001248 return new (Context)
1249 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001250}
1251
John McCalldadc5752010-08-24 06:29:42 +00001252StmtResult
John McCallb268a282010-08-23 23:25:46 +00001253Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001254 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001255 Expr *Cond, SourceLocation CondRParen) {
1256 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001257
Serge Pavlov09f99242014-01-23 15:05:00 +00001258 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001259 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001260 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001261 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001262 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001263
Richard Smith945f8d32013-01-14 22:39:08 +00001264 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001265 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001266 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001267 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268
John McCallb268a282010-08-23 23:25:46 +00001269 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001270
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001271 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001272}
1273
Richard Trieu451a5db2012-04-30 18:01:30 +00001274namespace {
1275 // This visitor will traverse a conditional statement and store all
1276 // the evaluated decls into a vector. Simple is set to true if none
1277 // of the excluded constructs are used.
1278 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001279 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001280 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001281 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001282 public:
1283 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001284
Craig Topper4dd9b432014-08-17 23:49:53 +00001285 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001286 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001287 Inherited(S.Context),
1288 Decls(Decls),
1289 Ranges(Ranges),
1290 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001291
Richard Trieu9d228802013-05-31 22:46:45 +00001292 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001293
Richard Trieu9d228802013-05-31 22:46:45 +00001294 // Replaces the method in EvaluatedExprVisitor.
1295 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001296 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001297 }
1298
1299 // Any Stmt not whitelisted will cause the condition to be marked complex.
1300 void VisitStmt(Stmt *S) {
1301 Simple = false;
1302 }
1303
1304 void VisitBinaryOperator(BinaryOperator *E) {
1305 Visit(E->getLHS());
1306 Visit(E->getRHS());
1307 }
1308
1309 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001310 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001311 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001312
Richard Trieu9d228802013-05-31 22:46:45 +00001313 void VisitUnaryOperator(UnaryOperator *E) {
1314 // Skip checking conditionals with derefernces.
1315 if (E->getOpcode() == UO_Deref)
1316 Simple = false;
1317 else
1318 Visit(E->getSubExpr());
1319 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001320
Richard Trieu9d228802013-05-31 22:46:45 +00001321 void VisitConditionalOperator(ConditionalOperator *E) {
1322 Visit(E->getCond());
1323 Visit(E->getTrueExpr());
1324 Visit(E->getFalseExpr());
1325 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001326
Richard Trieu9d228802013-05-31 22:46:45 +00001327 void VisitParenExpr(ParenExpr *E) {
1328 Visit(E->getSubExpr());
1329 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001330
Richard Trieu9d228802013-05-31 22:46:45 +00001331 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1332 Visit(E->getOpaqueValue()->getSourceExpr());
1333 Visit(E->getFalseExpr());
1334 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001335
Richard Trieu9d228802013-05-31 22:46:45 +00001336 void VisitIntegerLiteral(IntegerLiteral *E) { }
1337 void VisitFloatingLiteral(FloatingLiteral *E) { }
1338 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1339 void VisitCharacterLiteral(CharacterLiteral *E) { }
1340 void VisitGNUNullExpr(GNUNullExpr *E) { }
1341 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 void VisitDeclRefExpr(DeclRefExpr *E) {
1344 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1345 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 Ranges.push_back(E->getSourceRange());
1348
1349 Decls.insert(VD);
1350 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001351
1352 }; // end class DeclExtractor
1353
1354 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001355 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001356 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001357 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001358 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001359
Richard Trieu9d228802013-05-31 22:46:45 +00001360 public:
1361 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001362
Craig Topper4dd9b432014-08-17 23:49:53 +00001363 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001364 Stmt *Statement) :
1365 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1366 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001367
Richard Trieu9d228802013-05-31 22:46:45 +00001368 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001369 }
1370
Richard Trieu9d228802013-05-31 22:46:45 +00001371 void VisitReturnStmt(ReturnStmt *S) {
1372 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001373 }
1374
Richard Trieu9d228802013-05-31 22:46:45 +00001375 void VisitBreakStmt(BreakStmt *S) {
1376 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001377 }
1378
Richard Trieu9d228802013-05-31 22:46:45 +00001379 void VisitGotoStmt(GotoStmt *S) {
1380 FoundDecl = true;
1381 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001382
Richard Trieu9d228802013-05-31 22:46:45 +00001383 void VisitCastExpr(CastExpr *E) {
1384 if (E->getCastKind() == CK_LValueToRValue)
1385 CheckLValueToRValueCast(E->getSubExpr());
1386 else
1387 Visit(E->getSubExpr());
1388 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001389
Richard Trieu9d228802013-05-31 22:46:45 +00001390 void CheckLValueToRValueCast(Expr *E) {
1391 E = E->IgnoreParenImpCasts();
1392
1393 if (isa<DeclRefExpr>(E)) {
1394 return;
1395 }
1396
1397 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1398 Visit(CO->getCond());
1399 CheckLValueToRValueCast(CO->getTrueExpr());
1400 CheckLValueToRValueCast(CO->getFalseExpr());
1401 return;
1402 }
1403
1404 if (BinaryConditionalOperator *BCO =
1405 dyn_cast<BinaryConditionalOperator>(E)) {
1406 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1407 CheckLValueToRValueCast(BCO->getFalseExpr());
1408 return;
1409 }
1410
1411 Visit(E);
1412 }
1413
1414 void VisitDeclRefExpr(DeclRefExpr *E) {
1415 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1416 if (Decls.count(VD))
1417 FoundDecl = true;
1418 }
1419
1420 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001421
1422 }; // end class DeclMatcher
1423
1424 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1425 Expr *Third, Stmt *Body) {
1426 // Condition is empty
1427 if (!Second) return;
1428
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001429 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1430 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001431 return;
1432
1433 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1434 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001435 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001436 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001437 DE.Visit(Second);
1438
1439 // Don't analyze complex conditionals.
1440 if (!DE.isSimple()) return;
1441
1442 // No decls found.
1443 if (Decls.size() == 0) return;
1444
Richard Trieu0030f1d2012-05-04 03:01:54 +00001445 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001446 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1447 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001448 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001449 if ((*I)->getType().isVolatileQualified() ||
1450 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001451
1452 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1453 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1454 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1455 return;
1456
1457 // Load decl names into diagnostic.
1458 if (Decls.size() > 4)
1459 PDiag << 0;
1460 else {
1461 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001462 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1463 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001464 I != E; ++I)
1465 PDiag << (*I)->getDeclName();
1466 }
1467
1468 // Load SourceRanges into diagnostic if there is room.
1469 // Otherwise, load the SourceRange of the conditional expression.
1470 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001471 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001472 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001473 I != E; ++I)
1474 PDiag << *I;
1475 else
1476 PDiag << Second->getSourceRange();
1477
1478 S.Diag(Ranges.begin()->getBegin(), PDiag);
1479 }
1480
Richard Trieu4e7c9622013-08-06 21:31:54 +00001481 // If Statement is an incemement or decrement, return true and sets the
1482 // variables Increment and DRE.
1483 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1484 DeclRefExpr *&DRE) {
1485 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1486 switch (UO->getOpcode()) {
1487 default: return false;
1488 case UO_PostInc:
1489 case UO_PreInc:
1490 Increment = true;
1491 break;
1492 case UO_PostDec:
1493 case UO_PreDec:
1494 Increment = false;
1495 break;
1496 }
1497 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1498 return DRE;
1499 }
1500
1501 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1502 FunctionDecl *FD = Call->getDirectCallee();
1503 if (!FD || !FD->isOverloadedOperator()) return false;
1504 switch (FD->getOverloadedOperator()) {
1505 default: return false;
1506 case OO_PlusPlus:
1507 Increment = true;
1508 break;
1509 case OO_MinusMinus:
1510 Increment = false;
1511 break;
1512 }
1513 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1514 return DRE;
1515 }
1516
1517 return false;
1518 }
1519
Serge Pavlov09f99242014-01-23 15:05:00 +00001520 // A visitor to determine if a continue or break statement is a
1521 // subexpression.
1522 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1523 SourceLocation BreakLoc;
1524 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001525 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001526 BreakContinueFinder(Sema &S, Stmt* Body) :
1527 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001528 Visit(Body);
1529 }
1530
Serge Pavlov09f99242014-01-23 15:05:00 +00001531 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001532
1533 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001534 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001535 }
1536
Serge Pavlov09f99242014-01-23 15:05:00 +00001537 void VisitBreakStmt(BreakStmt* E) {
1538 BreakLoc = E->getBreakLoc();
1539 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001540
Serge Pavlov09f99242014-01-23 15:05:00 +00001541 bool ContinueFound() { return ContinueLoc.isValid(); }
1542 bool BreakFound() { return BreakLoc.isValid(); }
1543 SourceLocation GetContinueLoc() { return ContinueLoc; }
1544 SourceLocation GetBreakLoc() { return BreakLoc; }
1545
1546 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001547
1548 // Emit a warning when a loop increment/decrement appears twice per loop
1549 // iteration. The conditions which trigger this warning are:
1550 // 1) The last statement in the loop body and the third expression in the
1551 // for loop are both increment or both decrement of the same variable
1552 // 2) No continue statements in the loop body.
1553 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1554 // Return when there is nothing to check.
1555 if (!Body || !Third) return;
1556
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001557 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1558 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001559 return;
1560
1561 // Get the last statement from the loop body.
1562 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1563 if (!CS || CS->body_empty()) return;
1564 Stmt *LastStmt = CS->body_back();
1565 if (!LastStmt) return;
1566
1567 bool LoopIncrement, LastIncrement;
1568 DeclRefExpr *LoopDRE, *LastDRE;
1569
1570 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1571 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1572
1573 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001574 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001575 if (LoopIncrement != LastIncrement ||
1576 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1577
Serge Pavlov09f99242014-01-23 15:05:00 +00001578 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001579
1580 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1581 << LastDRE->getDecl() << LastIncrement;
1582 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1583 << LoopIncrement;
1584 }
1585
Richard Trieu451a5db2012-04-30 18:01:30 +00001586} // end namespace
1587
Serge Pavlov09f99242014-01-23 15:05:00 +00001588
1589void Sema::CheckBreakContinueBinding(Expr *E) {
1590 if (!E || getLangOpts().CPlusPlus)
1591 return;
1592 BreakContinueFinder BCFinder(*this, E);
1593 Scope *BreakParent = CurScope->getBreakParent();
1594 if (BCFinder.BreakFound() && BreakParent) {
1595 if (BreakParent->getFlags() & Scope::SwitchScope) {
1596 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1597 } else {
1598 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1599 << "break";
1600 }
1601 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1602 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1603 << "continue";
1604 }
1605}
1606
John McCalldadc5752010-08-24 06:29:42 +00001607StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001608Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001609 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001610 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001611 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001612 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001613 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001614 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1615 // declare identifiers for objects having storage class 'auto' or
1616 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001617 for (auto *DI : DS->decls()) {
1618 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001619 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001620 VD = nullptr;
1621 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001622 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1623 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001624 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001625 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001626 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001627 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001628
Serge Pavlov09f99242014-01-23 15:05:00 +00001629 CheckBreakContinueBinding(second.get());
1630 CheckBreakContinueBinding(third.get());
1631
Richard Trieu451a5db2012-04-30 18:01:30 +00001632 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001633 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001634
John McCalldadc5752010-08-24 06:29:42 +00001635 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001636 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001637 if (secondVar) {
1638 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001639 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001640 if (SecondResult.isInvalid())
1641 return StmtError();
1642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001644 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001645
Anders Carlsson1682af52009-08-01 01:39:59 +00001646 DiagnoseUnusedExprResult(First);
1647 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001648 DiagnoseUnusedExprResult(Body);
1649
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001650 if (isa<NullStmt>(Body))
1651 getCurCompoundScope().setHasEmptyLoopBodies();
1652
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001653 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1654 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001655}
1656
John McCall34376a62010-12-04 03:47:34 +00001657/// In an Objective C collection iteration statement:
1658/// for (x in y)
1659/// x can be an arbitrary l-value expression. Bind it up as a
1660/// full-expression.
1661StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001662 // Reduce placeholder expressions here. Note that this rejects the
1663 // use of pseudo-object l-values in this position.
1664 ExprResult result = CheckPlaceholderExpr(E);
1665 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001666 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001667
Richard Smith945f8d32013-01-14 22:39:08 +00001668 ExprResult FullExpr = ActOnFinishFullExpr(E);
1669 if (FullExpr.isInvalid())
1670 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001671 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001672}
1673
John McCall53848232011-07-27 01:07:15 +00001674ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001675Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1676 if (!collection)
1677 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001678
Kaelyn Takata15867822014-11-21 18:48:04 +00001679 ExprResult result = CorrectDelayedTyposInExpr(collection);
1680 if (!result.isUsable())
1681 return ExprError();
1682 collection = result.get();
1683
John McCall53848232011-07-27 01:07:15 +00001684 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001685 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001686
1687 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001688 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001689 if (result.isInvalid())
1690 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001691 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001692
1693 // The operand needs to have object-pointer type.
1694 // TODO: should we do a contextual conversion?
1695 const ObjCObjectPointerType *pointerType =
1696 collection->getType()->getAs<ObjCObjectPointerType>();
1697 if (!pointerType)
1698 return Diag(forLoc, diag::err_collection_expr_type)
1699 << collection->getType() << collection->getSourceRange();
1700
1701 // Check that the operand provides
1702 // - countByEnumeratingWithState:objects:count:
1703 const ObjCObjectType *objectType = pointerType->getObjectType();
1704 ObjCInterfaceDecl *iface = objectType->getInterface();
1705
1706 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001707 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001708 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001709 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001710 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001711 ? diag::err_arc_collection_forward
1712 : 0,
1713 collection)) {
John McCall53848232011-07-27 01:07:15 +00001714 // Otherwise, if we have any useful type information, check that
1715 // the type declares the appropriate method.
1716 } else if (iface || !objectType->qual_empty()) {
1717 IdentifierInfo *selectorIdents[] = {
1718 &Context.Idents.get("countByEnumeratingWithState"),
1719 &Context.Idents.get("objects"),
1720 &Context.Idents.get("count")
1721 };
1722 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1723
Craig Topperc3ec1492014-05-26 06:22:03 +00001724 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001725
1726 // If there's an interface, look in both the public and private APIs.
1727 if (iface) {
1728 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001729 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001730 }
1731
1732 // Also check protocol qualifiers.
1733 if (!method)
1734 method = LookupMethodInQualifiedType(selector, pointerType,
1735 /*instance*/ true);
1736
1737 // If we didn't find it anywhere, give up.
1738 if (!method) {
1739 Diag(forLoc, diag::warn_collection_expr_type)
1740 << collection->getType() << selector << collection->getSourceRange();
1741 }
1742
1743 // TODO: check for an incompatible signature?
1744 }
1745
1746 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001747 return collection;
John McCall53848232011-07-27 01:07:15 +00001748}
1749
John McCalldadc5752010-08-24 06:29:42 +00001750StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001751Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001752 Stmt *First, Expr *collection,
1753 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001754
1755 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001756 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001757
Fariborz Jahanian93977672008-01-10 20:33:58 +00001758 if (First) {
1759 QualType FirstType;
1760 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001761 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001762 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1763 diag::err_toomany_element_decls));
1764
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001765 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1766 if (!D || D->isInvalidDecl())
1767 return StmtError();
1768
John McCall31168b02011-06-15 23:02:42 +00001769 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001770 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1771 // declare identifiers for objects having storage class 'auto' or
1772 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001773 if (!D->hasLocalStorage())
1774 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001775 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001776
1777 // If the type contained 'auto', deduce the 'auto' to 'id'.
1778 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001779 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1780 VK_RValue);
1781 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001782 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1783 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001784 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001785 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001786 D->setInvalidDecl();
1787 return StmtError();
1788 }
1789
Richard Smith061f1e22013-04-30 21:23:01 +00001790 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001791
1792 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001793 SourceLocation Loc =
1794 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001795 Diag(Loc, diag::warn_auto_var_is_id)
1796 << D->getDeclName();
1797 }
1798 }
1799
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001800 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001801 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001802 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001803 return StmtError(Diag(First->getLocStart(),
1804 diag::err_selector_element_not_lvalue)
1805 << First->getSourceRange());
1806
Mike Stump11289f42009-09-09 15:08:12 +00001807 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001808 if (FirstType.isConstQualified())
1809 Diag(ForLoc, diag::err_selector_element_const_type)
1810 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001811 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001812 if (!FirstType->isDependentType() &&
1813 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001814 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001815 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1816 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001817 }
Chad Rosier02a84392012-08-10 17:56:09 +00001818
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001819 if (CollectionExprResult.isInvalid())
1820 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001821
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001822 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001823 if (CollectionExprResult.isInvalid())
1824 return StmtError();
1825
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001826 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1827 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001828}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001829
Richard Smith02e85f32011-04-14 22:09:26 +00001830/// Finish building a variable declaration for a for-range statement.
1831/// \return true if an error occurs.
1832static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001833 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001834 // Deduce the type for the iterator variable now rather than leaving it to
1835 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001836 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001837 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001838 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001839 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001840 SemaRef.Diag(Loc, DiagID) << Init->getType();
1841 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001842 Decl->setInvalidDecl();
1843 return true;
1844 }
Richard Smith061f1e22013-04-30 21:23:01 +00001845 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001846
John McCall31168b02011-06-15 23:02:42 +00001847 // In ARC, infer lifetime.
1848 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1849 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001850 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001851 SemaRef.inferObjCARCLifetime(Decl))
1852 Decl->setInvalidDecl();
1853
Richard Smith02e85f32011-04-14 22:09:26 +00001854 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1855 /*TypeMayContainAuto=*/false);
1856 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001857 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001858 return false;
1859}
1860
Sam Panzer0f384432012-08-21 00:52:01 +00001861namespace {
1862
Richard Smith02e85f32011-04-14 22:09:26 +00001863/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001864/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001865/// nor from the diagnostics produced when analysing the implicit expressions
1866/// required in a for-range statement.
1867void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001868 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001869 CallExpr *CE = dyn_cast<CallExpr>(E);
1870 if (!CE)
1871 return;
1872 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1873 if (!D)
1874 return;
1875 SourceLocation Loc = D->getLocation();
1876
1877 std::string Description;
1878 bool IsTemplate = false;
1879 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1880 Description = SemaRef.getTemplateArgumentBindingsText(
1881 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1882 IsTemplate = true;
1883 }
1884
1885 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1886 << BEF << IsTemplate << Description << E->getType();
1887}
1888
Sam Panzer0f384432012-08-21 00:52:01 +00001889/// Build a variable declaration for a for-range statement.
1890VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1891 QualType Type, const char *Name) {
1892 DeclContext *DC = SemaRef.CurContext;
1893 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1894 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1895 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001896 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001897 Decl->setImplicit();
1898 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001899}
1900
1901}
1902
Fariborz Jahanian00213472012-07-06 19:04:04 +00001903static bool ObjCEnumerationCollection(Expr *Collection) {
1904 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001905 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001906}
1907
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001908/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001909///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001910/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001911/// A range-based for statement is equivalent to
1912///
1913/// {
1914/// auto && __range = range-init;
1915/// for ( auto __begin = begin-expr,
1916/// __end = end-expr;
1917/// __begin != __end;
1918/// ++__begin ) {
1919/// for-range-declaration = *__begin;
1920/// statement
1921/// }
1922/// }
1923///
1924/// The body of the loop is not available yet, since it cannot be analysed until
1925/// we have determined the type of the for-range-declaration.
1926StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001927Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001928 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001929 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001930 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001931 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001932
Richard Smith3249fed2013-08-21 01:40:36 +00001933 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001934 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001935
1936 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1937 assert(DS && "first part of for range not a decl stmt");
1938
1939 if (!DS->isSingleDecl()) {
1940 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1941 return StmtError();
1942 }
Richard Smith02e85f32011-04-14 22:09:26 +00001943
Richard Smith3249fed2013-08-21 01:40:36 +00001944 Decl *LoopVar = DS->getSingleDecl();
1945 if (LoopVar->isInvalidDecl() || !Range ||
1946 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1947 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001948 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001949 }
Richard Smith02e85f32011-04-14 22:09:26 +00001950
1951 // Build auto && __range = range-init
1952 SourceLocation RangeLoc = Range->getLocStart();
1953 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1954 Context.getAutoRRefDeductType(),
1955 "__range");
1956 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001957 diag::err_for_range_deduction_failure)) {
1958 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001959 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001960 }
Richard Smith02e85f32011-04-14 22:09:26 +00001961
1962 // Claim the type doesn't contain auto: we've already done the checking.
1963 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001964 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001965 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001966 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001967 if (RangeDecl.isInvalid()) {
1968 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001969 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001970 }
Richard Smith02e85f32011-04-14 22:09:26 +00001971
1972 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001973 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1974 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001975}
1976
1977/// \brief Create the initialization, compare, and increment steps for
1978/// the range-based for loop expression.
1979/// This function does not handle array-based for loops,
1980/// which are created in Sema::BuildCXXForRangeStmt.
1981///
1982/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1983/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1984/// CandidateSet and BEF are set and some non-success value is returned on
1985/// failure.
1986static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1987 Expr *BeginRange, Expr *EndRange,
1988 QualType RangeType,
1989 VarDecl *BeginVar,
1990 VarDecl *EndVar,
1991 SourceLocation ColonLoc,
1992 OverloadCandidateSet *CandidateSet,
1993 ExprResult *BeginExpr,
1994 ExprResult *EndExpr,
1995 Sema::BeginEndFunction *BEF) {
1996 DeclarationNameInfo BeginNameInfo(
1997 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1998 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1999 ColonLoc);
2000
2001 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2002 Sema::LookupMemberName);
2003 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2004
2005 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2006 // - if _RangeT is a class type, the unqualified-ids begin and end are
2007 // looked up in the scope of class _RangeT as if by class member access
2008 // lookup (3.4.5), and if either (or both) finds at least one
2009 // declaration, begin-expr and end-expr are __range.begin() and
2010 // __range.end(), respectively;
2011 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2012 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2013
2014 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2015 SourceLocation RangeLoc = BeginVar->getLocation();
2016 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2017
2018 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2019 << RangeLoc << BeginRange->getType() << *BEF;
2020 return Sema::FRS_DiagnosticIssued;
2021 }
2022 } else {
2023 // - otherwise, begin-expr and end-expr are begin(__range) and
2024 // end(__range), respectively, where begin and end are looked up with
2025 // argument-dependent lookup (3.4.2). For the purposes of this name
2026 // lookup, namespace std is an associated namespace.
2027
2028 }
2029
2030 *BEF = Sema::BEF_begin;
2031 Sema::ForRangeStatus RangeStatus =
2032 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2033 Sema::BEF_begin, BeginNameInfo,
2034 BeginMemberLookup, CandidateSet,
2035 BeginRange, BeginExpr);
2036
2037 if (RangeStatus != Sema::FRS_Success)
2038 return RangeStatus;
2039 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2040 diag::err_for_range_iter_deduction_failure)) {
2041 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2042 return Sema::FRS_DiagnosticIssued;
2043 }
2044
2045 *BEF = Sema::BEF_end;
2046 RangeStatus =
2047 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2048 Sema::BEF_end, EndNameInfo,
2049 EndMemberLookup, CandidateSet,
2050 EndRange, EndExpr);
2051 if (RangeStatus != Sema::FRS_Success)
2052 return RangeStatus;
2053 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2054 diag::err_for_range_iter_deduction_failure)) {
2055 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2056 return Sema::FRS_DiagnosticIssued;
2057 }
2058 return Sema::FRS_Success;
2059}
2060
2061/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002062/// If the attempt fails, this function will return a valid, null StmtResult
2063/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002064static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2065 SourceLocation ForLoc,
2066 Stmt *LoopVarDecl,
2067 SourceLocation ColonLoc,
2068 Expr *Range,
2069 SourceLocation RangeLoc,
2070 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002071 // Determine whether we can rebuild the for-range statement with a
2072 // dereferenced range expression.
2073 ExprResult AdjustedRange;
2074 {
2075 Sema::SFINAETrap Trap(SemaRef);
2076
2077 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2078 if (AdjustedRange.isInvalid())
2079 return StmtResult();
2080
2081 StmtResult SR =
2082 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2083 AdjustedRange.get(), RParenLoc,
2084 Sema::BFRK_Check);
2085 if (SR.isInvalid())
2086 return StmtResult();
2087 }
2088
2089 // The attempt to dereference worked well enough that it could produce a valid
2090 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2091 // case there are any other (non-fatal) problems with it.
2092 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2093 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2094 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2095 AdjustedRange.get(), RParenLoc,
2096 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002097}
2098
Richard Smith3249fed2013-08-21 01:40:36 +00002099namespace {
2100/// RAII object to automatically invalidate a declaration if an error occurs.
2101struct InvalidateOnErrorScope {
2102 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2103 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2104 ~InvalidateOnErrorScope() {
2105 if (Enabled && Trap.hasErrorOccurred())
2106 D->setInvalidDecl();
2107 }
2108
2109 DiagnosticErrorTrap Trap;
2110 Decl *D;
2111 bool Enabled;
2112};
2113}
2114
Richard Smitha05b3b52012-09-20 21:52:32 +00002115/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002116StmtResult
2117Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2118 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2119 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002120 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002121 Scope *S = getCurScope();
2122
2123 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2124 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2125 QualType RangeVarType = RangeVar->getType();
2126
2127 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2128 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2129
Richard Smith3249fed2013-08-21 01:40:36 +00002130 // If we hit any errors, mark the loop variable as invalid if its type
2131 // contains 'auto'.
2132 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2133 LoopVar->getType()->isUndeducedType());
2134
Richard Smith02e85f32011-04-14 22:09:26 +00002135 StmtResult BeginEndDecl = BeginEnd;
2136 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2137
Richard Smith27d807c2013-04-30 13:56:41 +00002138 if (RangeVarType->isDependentType()) {
2139 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002140 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002141
2142 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2143 // them in properly when we instantiate the loop.
2144 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2145 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2146 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002147 SourceLocation RangeLoc = RangeVar->getLocation();
2148
Ted Kremenekbed648e2011-10-10 22:36:28 +00002149 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2150
2151 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2152 VK_LValue, ColonLoc);
2153 if (BeginRangeRef.isInvalid())
2154 return StmtError();
2155
2156 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2157 VK_LValue, ColonLoc);
2158 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002159 return StmtError();
2160
2161 QualType AutoType = Context.getAutoDeductType();
2162 Expr *Range = RangeVar->getInit();
2163 if (!Range)
2164 return StmtError();
2165 QualType RangeType = Range->getType();
2166
2167 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002168 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002169 return StmtError();
2170
2171 // Build auto __begin = begin-expr, __end = end-expr.
2172 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2173 "__begin");
2174 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2175 "__end");
2176
2177 // Build begin-expr and end-expr and attach to __begin and __end variables.
2178 ExprResult BeginExpr, EndExpr;
2179 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2180 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2181 // __range + __bound, respectively, where __bound is the array bound. If
2182 // _RangeT is an array of unknown size or an array of incomplete type,
2183 // the program is ill-formed;
2184
2185 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002186 BeginExpr = BeginRangeRef;
2187 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002188 diag::err_for_range_iter_deduction_failure)) {
2189 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2190 return StmtError();
2191 }
2192
2193 // Find the array bound.
2194 ExprResult BoundExpr;
2195 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002196 BoundExpr = IntegerLiteral::Create(
2197 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002198 else if (const VariableArrayType *VAT =
2199 dyn_cast<VariableArrayType>(UnqAT))
2200 BoundExpr = VAT->getSizeExpr();
2201 else {
2202 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2203 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002204 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002205 }
2206
2207 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002208 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002209 BoundExpr.get());
2210 if (EndExpr.isInvalid())
2211 return StmtError();
2212 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2213 diag::err_for_range_iter_deduction_failure)) {
2214 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2215 return StmtError();
2216 }
2217 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002218 OverloadCandidateSet CandidateSet(RangeLoc,
2219 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002220 Sema::BeginEndFunction BEFFailure;
2221 ForRangeStatus RangeStatus =
2222 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2223 EndRangeRef.get(), RangeType,
2224 BeginVar, EndVar, ColonLoc, &CandidateSet,
2225 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002226
Richard Smitha05b3b52012-09-20 21:52:32 +00002227 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002228 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002229 // If the range is being built from an array parameter, emit a
2230 // a diagnostic that it is being treated as a pointer.
2231 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2232 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2233 QualType ArrayTy = PVD->getOriginalType();
2234 QualType PointerTy = PVD->getType();
2235 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2236 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2237 << RangeLoc << PVD << ArrayTy << PointerTy;
2238 Diag(PVD->getLocation(), diag::note_declared_at);
2239 return StmtError();
2240 }
2241 }
2242 }
2243
2244 // If building the range failed, try dereferencing the range expression
2245 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002246 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2247 LoopVarDecl, ColonLoc,
2248 Range, RangeLoc,
2249 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002250 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002251 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002252 }
2253
Sam Panzer0f384432012-08-21 00:52:01 +00002254 // Otherwise, emit diagnostics if we haven't already.
2255 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002256 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002257 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2258 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002259 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002260 }
2261 // Return an error if no fix was discovered.
2262 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002263 return StmtError();
2264 }
2265
Sam Panzer0f384432012-08-21 00:52:01 +00002266 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2267 "invalid range expression in for loop");
2268
2269 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002270 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2271 if (!Context.hasSameType(BeginType, EndType)) {
2272 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2273 << BeginType << EndType;
2274 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2275 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2276 }
2277
2278 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2279 // Claim the type doesn't contain auto: we've already done the checking.
2280 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002281 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002282 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002283 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2284
Ted Kremenekbed648e2011-10-10 22:36:28 +00002285 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2286 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002287 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002288 if (BeginRef.isInvalid())
2289 return StmtError();
2290
Richard Smith02e85f32011-04-14 22:09:26 +00002291 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2292 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002293 if (EndRef.isInvalid())
2294 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002295
2296 // Build and check __begin != __end expression.
2297 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2298 BeginRef.get(), EndRef.get());
2299 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2300 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2301 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002302 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2303 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002304 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2305 if (!Context.hasSameType(BeginType, EndType))
2306 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2307 return StmtError();
2308 }
2309
2310 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002311 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2312 VK_LValue, ColonLoc);
2313 if (BeginRef.isInvalid())
2314 return StmtError();
2315
Richard Smith02e85f32011-04-14 22:09:26 +00002316 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2317 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2318 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002319 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2320 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002321 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2322 return StmtError();
2323 }
2324
2325 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002326 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2327 VK_LValue, ColonLoc);
2328 if (BeginRef.isInvalid())
2329 return StmtError();
2330
Richard Smith02e85f32011-04-14 22:09:26 +00002331 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2332 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002333 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2334 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002335 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2336 return StmtError();
2337 }
2338
Richard Smitha05b3b52012-09-20 21:52:32 +00002339 // Attach *__begin as initializer for VD. Don't touch it if we're just
2340 // trying to determine whether this would be a valid range.
2341 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002342 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2343 /*TypeMayContainAuto=*/true);
2344 if (LoopVar->isInvalidDecl())
2345 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2346 }
2347 }
2348
Richard Smitha05b3b52012-09-20 21:52:32 +00002349 // Don't bother to actually allocate the result if we're just trying to
2350 // determine whether it would be valid.
2351 if (Kind == BFRK_Check)
2352 return StmtResult();
2353
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002354 return new (Context) CXXForRangeStmt(
2355 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2356 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002357}
2358
Chad Rosier02a84392012-08-10 17:56:09 +00002359/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002360/// statement.
2361StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2362 if (!S || !B)
2363 return StmtError();
2364 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002365
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002366 ForStmt->setBody(B);
2367 return S;
2368}
2369
Richard Smith02e85f32011-04-14 22:09:26 +00002370/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2371/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2372/// body cannot be performed until after the type of the range variable is
2373/// determined.
2374StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2375 if (!S || !B)
2376 return StmtError();
2377
Fariborz Jahanian00213472012-07-06 19:04:04 +00002378 if (isa<ObjCForCollectionStmt>(S))
2379 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002380
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002381 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2382 ForStmt->setBody(B);
2383
2384 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2385 diag::warn_empty_range_based_for_body);
2386
Richard Smith02e85f32011-04-14 22:09:26 +00002387 return S;
2388}
2389
Chris Lattnercab02a62011-02-17 20:34:02 +00002390StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2391 SourceLocation LabelLoc,
2392 LabelDecl *TheDecl) {
2393 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002394 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002395 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002396}
Chris Lattner1c310502007-05-31 06:00:00 +00002397
John McCalldadc5752010-08-24 06:29:42 +00002398StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002399Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002400 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002401 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002402 if (!E->isTypeDependent()) {
2403 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002404 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002405 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002406 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002407 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2408 if (ExprRes.isInvalid())
2409 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002410 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002411 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002412 return StmtError();
2413 }
John McCalla95172b2010-08-01 00:26:45 +00002414
Richard Smith945f8d32013-01-14 22:39:08 +00002415 ExprResult ExprRes = ActOnFinishFullExpr(E);
2416 if (ExprRes.isInvalid())
2417 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002418 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002419
John McCallaab3e412010-08-25 08:40:02 +00002420 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002421
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002422 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002423}
2424
John McCalldadc5752010-08-24 06:29:42 +00002425StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002426Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002427 Scope *S = CurScope->getContinueParent();
2428 if (!S) {
2429 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002430 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002431 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002432
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002433 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002434}
2435
John McCalldadc5752010-08-24 06:29:42 +00002436StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002437Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002438 Scope *S = CurScope->getBreakParent();
2439 if (!S) {
2440 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002441 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002442 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002443 if (S->isOpenMPLoopScope())
2444 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2445 << "break");
Sebastian Redl573feed2009-01-18 13:19:59 +00002446
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002447 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002448}
2449
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002451/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002452///
Douglas Gregor5d369002011-01-21 18:05:27 +00002453/// \param ReturnType If we're determining the copy elision candidate for
2454/// a return statement, this is the return type of the function. If we're
2455/// determining the copy elision candidate for a throw expression, this will
2456/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002457///
Douglas Gregor5d369002011-01-21 18:05:27 +00002458/// \param E The expression being returned from the function or block, or
2459/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002460///
Douglas Gregor86394412011-05-20 15:00:53 +00002461/// \param AllowFunctionParameter Whether we allow function parameters to
2462/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2463/// we re-use this logic to determine whether we should try to move as part of
2464/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002465///
2466/// \returns The NRVO candidate variable, if the return statement may use the
2467/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002468VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2469 Expr *E,
2470 bool AllowFunctionParameter) {
2471 if (!getLangOpts().CPlusPlus)
2472 return nullptr;
2473
2474 // - in a return statement in a function [where] ...
2475 // ... the expression is the name of a non-volatile automatic object ...
2476 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2477 if (!DR || DR->refersToEnclosingLocal())
2478 return nullptr;
2479 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2480 if (!VD)
2481 return nullptr;
2482
2483 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2484 return VD;
2485 return nullptr;
2486}
2487
2488bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2489 bool AllowFunctionParameter) {
2490 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002491 // - in a return statement in a function with ...
2492 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002493 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002494 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002495 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002496 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002497 if (!VDType->isDependentType() &&
2498 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2499 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002501
John McCall03318c12011-11-11 03:57:31 +00002502 // ...object (other than a function or catch-clause parameter)...
2503 if (VD->getKind() != Decl::Var &&
2504 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002505 return false;
2506 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002507
John McCall03318c12011-11-11 03:57:31 +00002508 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002509 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002510
2511 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002512 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002513
2514 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002515 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002516
2517 // Variables with higher required alignment than their type's ABI
2518 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002519 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002520 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002521 return false;
John McCall03318c12011-11-11 03:57:31 +00002522
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002523 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002524}
2525
Douglas Gregor626fbed2011-01-21 21:08:57 +00002526/// \brief Perform the initialization of a potentially-movable value, which
2527/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002528///
2529/// This routine implements C++0x [class.copy]p33, which attempts to treat
2530/// returned lvalues as rvalues in certain cases (to prefer move construction),
2531/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002533Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2534 const VarDecl *NRVOCandidate,
2535 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002536 Expr *Value,
2537 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002538 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539 // When the criteria for elision of a copy operation are met or would
2540 // be met save for the fact that the source object is a function
2541 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002542 // overload resolution to select the constructor for the copy is first
2543 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002544 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002545 if (AllowNRVO &&
2546 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002547 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002548 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002549
Douglas Gregorf282a762011-01-21 19:38:21 +00002550 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002552 = InitializationKind::CreateCopy(Value->getLocStart(),
2553 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002554 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002555
2556 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002557 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002558 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002559 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002560 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002561 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2562 StepEnd = Seq.step_end();
2563 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002564 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002565 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002566
2567 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002568 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569
Douglas Gregorf282a762011-01-21 19:38:21 +00002570 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002571 = Constructor->getParamDecl(0)->getType()
2572 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002573
Douglas Gregorf282a762011-01-21 19:38:21 +00002574 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002576 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2577 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002578 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579
Douglas Gregorf282a762011-01-21 19:38:21 +00002580 // Promote "AsRvalue" to the heap, since we now need this
2581 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002582 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002583 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002584
Douglas Gregorf282a762011-01-21 19:38:21 +00002585 // Complete type-checking the initialization of the return type
2586 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002587 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002588 }
2589 }
2590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002591
Douglas Gregorf282a762011-01-21 19:38:21 +00002592 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002593 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002594 // (again) now with the return value expression as written.
2595 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002596 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002597
Douglas Gregorf282a762011-01-21 19:38:21 +00002598 return Res;
2599}
2600
Richard Smith4db51c22013-09-25 05:02:54 +00002601/// \brief Determine whether the declared return type of the specified function
2602/// contains 'auto'.
2603static bool hasDeducedReturnType(FunctionDecl *FD) {
2604 const FunctionProtoType *FPT =
2605 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002606 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002607}
2608
Eli Friedman34b49062012-01-26 03:00:14 +00002609/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2610/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002611///
John McCalldadc5752010-08-24 06:29:42 +00002612StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002613Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2614 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002615 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002616 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002617 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002618 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002619
Richard Smith4db51c22013-09-25 05:02:54 +00002620 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2621 // In C++1y, the return type may involve 'auto'.
2622 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2623 FunctionDecl *FD = CurLambda->CallOperator;
2624 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002625 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002626
2627 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2628 assert(AT && "lost auto type from lambda return type");
2629 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2630 FD->setInvalidDecl();
2631 return StmtError();
2632 }
Alp Toker314cc812014-01-25 16:55:45 +00002633 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002634 } else if (CurCap->HasImplicitReturnType) {
2635 // For blocks/lambdas with implicit return types, we check each return
2636 // statement individually, and deduce the common return type when the block
2637 // or lambda is completed.
2638 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002639 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002640 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2641 if (Result.isInvalid())
2642 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002643 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002644
Richard Smith4db51c22013-09-25 05:02:54 +00002645 if (!CurContext->isDependentContext())
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002646 FnRetType = RetValExp->getType();
Richard Smith4db51c22013-09-25 05:02:54 +00002647 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002648 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002649 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002650 if (RetValExp) {
2651 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2652 // initializer list, because it is not an expression (even
2653 // though we represent it as one). We still deduce 'void'.
2654 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2655 << RetValExp->getSourceRange();
2656 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002657
Jordan Rosed39e5f12012-07-02 21:19:23 +00002658 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002659 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002660
2661 // Although we'll properly infer the type of the block once it's completed,
2662 // make sure we provide a return type now for better error recovery.
2663 if (CurCap->ReturnType.isNull())
2664 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002665 }
Eli Friedman34b49062012-01-26 03:00:14 +00002666 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002667
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002668 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002669 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2670 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2671 return StmtError();
2672 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002673 } else if (CapturedRegionScopeInfo *CurRegion =
2674 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2675 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2676 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002677 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002678 assert(CurLambda && "unknown kind of captured scope");
2679 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2680 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002681 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2682 return StmtError();
2683 }
2684 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002685
Steve Naroffc540d662008-09-03 18:15:37 +00002686 // Otherwise, verify that this result type matches the previous one. We are
2687 // pickier with blocks than for normal functions because we don't have GCC
2688 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002689 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002690 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002691 // Delay processing for now. TODO: there are lots of dependent
2692 // types we can conclusively prove aren't void.
2693 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002694 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002695 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002696 (RetValExp->isTypeDependent() ||
2697 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002698 if (!getLangOpts().CPlusPlus &&
2699 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002700 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002701 else {
2702 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002703 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002704 }
Steve Naroffc540d662008-09-03 18:15:37 +00002705 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002706 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002707 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2708 } else if (!RetValExp->isTypeDependent()) {
2709 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002710
John McCall5500ef22011-08-17 22:09:46 +00002711 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2712 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2713 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002714
John McCall5500ef22011-08-17 22:09:46 +00002715 // In C++ the return statement is handled via a copy initialization.
2716 // the C version of which boils down to CheckSingleAssignmentConstraints.
2717 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2718 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2719 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002720 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002721 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2722 FnRetType, RetValExp);
2723 if (Res.isInvalid()) {
2724 // FIXME: Cleanup temporaries here, anyway?
2725 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002726 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002727 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002728 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002729 } else {
2730 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002731 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002732
John McCall75f92b52011-08-17 21:34:14 +00002733 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002734 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2735 if (ER.isInvalid())
2736 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002737 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002738 }
John McCall5500ef22011-08-17 22:09:46 +00002739 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2740 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002741
Jordan Rosed39e5f12012-07-02 21:19:23 +00002742 // If we need to check for the named return value optimization,
2743 // or if we need to infer the return type,
2744 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002745 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002746 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002747
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002748 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002749}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002750
Nico Weber72889432014-09-06 01:25:55 +00002751namespace {
2752/// \brief Marks all typedefs in all local classes in a type referenced.
2753///
2754/// In a function like
2755/// auto f() {
2756/// struct S { typedef int a; };
2757/// return S();
2758/// }
2759///
2760/// the local type escapes and could be referenced in some TUs but not in
2761/// others. Pretend that all local typedefs are always referenced, to not warn
2762/// on this. This isn't necessary if f has internal linkage, or the typedef
2763/// is private.
2764class LocalTypedefNameReferencer
2765 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2766public:
2767 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2768 bool VisitRecordType(const RecordType *RT);
2769private:
2770 Sema &S;
2771};
2772bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2773 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2774 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2775 R->isDependentType())
2776 return true;
2777 for (auto *TmpD : R->decls())
2778 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2779 if (T->getAccess() != AS_private || R->hasFriends())
2780 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2781 return true;
2782}
2783}
2784
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002785TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002786 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002787 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2788 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002789 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002790}
2791
Richard Smith2a7d4812013-05-04 07:00:32 +00002792/// Deduce the return type for a function from a returned expression, per
2793/// C++1y [dcl.spec.auto]p6.
2794bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2795 SourceLocation ReturnLoc,
2796 Expr *&RetExpr,
2797 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002798 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00002799 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002800
Richard Smithc58f38f2013-08-14 20:16:31 +00002801 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2802 // If the deduction is for a return statement and the initializer is
2803 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002804 Diag(RetExpr->getExprLoc(),
2805 getCurLambda() ? diag::err_lambda_return_init_list
2806 : diag::err_auto_fn_return_init_list)
2807 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002808 return true;
2809 }
2810
2811 if (FD->isDependentContext()) {
2812 // C++1y [dcl.spec.auto]p12:
2813 // Return type deduction [...] occurs when the definition is
2814 // instantiated even if the function body contains a return
2815 // statement with a non-type-dependent operand.
2816 assert(AT->isDeduced() && "should have deduced to dependent type");
2817 return false;
2818 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002819 // If the deduction is for a return statement and the initializer is
2820 // a braced-init-list, the program is ill-formed.
2821 if (isa<InitListExpr>(RetExpr)) {
2822 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2823 return true;
2824 }
2825
2826 // Otherwise, [...] deduce a value for U using the rules of template
2827 // argument deduction.
2828 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2829
2830 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2831 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2832 << OrigResultType.getType() << RetExpr->getType();
2833
2834 if (DAR != DAR_Succeeded)
2835 return true;
Nico Weber72889432014-09-06 01:25:55 +00002836
2837 // If a local type is part of the returned type, mark its fields as
2838 // referenced.
2839 LocalTypedefNameReferencer Referencer(*this);
2840 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00002841 } else {
2842 // In the case of a return with no operand, the initializer is considered
2843 // to be void().
2844 //
2845 // Deduction here can only succeed if the return type is exactly 'cv auto'
2846 // or 'decltype(auto)', so just check for that case directly.
2847 if (!OrigResultType.getType()->getAs<AutoType>()) {
2848 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2849 << OrigResultType.getType();
2850 return true;
2851 }
2852 // We always deduce U = void in this case.
2853 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2854 if (Deduced.isNull())
2855 return true;
2856 }
2857
2858 // If a function with a declared return type that contains a placeholder type
2859 // has multiple return statements, the return type is deduced for each return
2860 // statement. [...] if the type deduced is not the same in each deduction,
2861 // the program is ill-formed.
2862 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2863 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002864 if (!FD->isDependentContext() &&
2865 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002866 const LambdaScopeInfo *LambdaSI = getCurLambda();
2867 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2868 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2869 << NewAT->getDeducedType() << AT->getDeducedType()
2870 << true /*IsLambda*/;
2871 } else {
2872 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2873 << (AT->isDecltypeAuto() ? 1 : 0)
2874 << NewAT->getDeducedType() << AT->getDeducedType();
2875 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002876 return true;
2877 }
2878 } else if (!FD->isInvalidDecl()) {
2879 // Update all declarations of the function to have the deduced return type.
2880 Context.adjustDeducedFunctionResultType(FD, Deduced);
2881 }
2882
2883 return false;
2884}
2885
John McCalldadc5752010-08-24 06:29:42 +00002886StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002887Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2888 Scope *CurScope) {
2889 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2890 if (R.isInvalid()) {
2891 return R;
2892 }
2893
2894 if (VarDecl *VD =
2895 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2896 CurScope->addNRVOCandidate(VD);
2897 } else {
2898 CurScope->setNoNRVO();
2899 }
2900
2901 return R;
2902}
2903
2904StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002905 // Check for unexpanded parameter packs.
2906 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2907 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002908
Eli Friedman34b49062012-01-26 03:00:14 +00002909 if (isa<CapturingScopeInfo>(getCurFunction()))
2910 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002911
Chris Lattner79413952008-12-04 23:50:19 +00002912 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002913 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002914 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002915 bool isObjCMethod = false;
2916
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002917 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002918 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002919 if (FD->hasAttrs())
2920 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002921 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002922 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002923 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002924 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002925 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002926 isObjCMethod = true;
2927 if (MD->hasAttrs())
2928 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002929 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2930 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002931 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002932 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002933 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2934 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002935 }
2936 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002937 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002938
Richard Smith2a7d4812013-05-04 07:00:32 +00002939 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2940 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002941 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002942 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2943 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002944 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002945 FD->setInvalidDecl();
2946 return StmtError();
2947 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002948 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002949 }
2950 }
2951 }
2952
Richard Smithc58f38f2013-08-14 20:16:31 +00002953 bool HasDependentReturnType = FnRetType->isDependentType();
2954
Craig Topperc3ec1492014-05-26 06:22:03 +00002955 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002956 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002957 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002958 if (isa<InitListExpr>(RetValExp)) {
2959 // We simply never allow init lists as the return value of void
2960 // functions. This is compatible because this was never allowed before,
2961 // so there's no legacy code to deal with.
2962 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2963 int FunctionKind = 0;
2964 if (isa<ObjCMethodDecl>(CurDecl))
2965 FunctionKind = 1;
2966 else if (isa<CXXConstructorDecl>(CurDecl))
2967 FunctionKind = 2;
2968 else if (isa<CXXDestructorDecl>(CurDecl))
2969 FunctionKind = 3;
2970
2971 Diag(ReturnLoc, diag::err_return_init_list)
2972 << CurDecl->getDeclName() << FunctionKind
2973 << RetValExp->getSourceRange();
2974
2975 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002976 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002977 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002978 // C99 6.8.6.4p1 (ext_ since GCC warns)
2979 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002980 if (RetValExp->getType()->isVoidType()) {
2981 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2982 if (isa<CXXConstructorDecl>(CurDecl) ||
2983 isa<CXXDestructorDecl>(CurDecl))
2984 D = diag::err_ctor_dtor_returns_void;
2985 else
2986 D = diag::ext_return_has_void_expr;
2987 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002988 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002989 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002990 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00002991 if (Result.isInvalid())
2992 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002993 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002994 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002995 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002996 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002997 // return of void in constructor/destructor is illegal in C++.
2998 if (D == diag::err_ctor_dtor_returns_void) {
2999 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3000 Diag(ReturnLoc, D)
3001 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3002 << RetValExp->getSourceRange();
3003 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003004 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003005 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003006 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003007 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003008
3009 int FunctionKind = 0;
3010 if (isa<ObjCMethodDecl>(CurDecl))
3011 FunctionKind = 1;
3012 else if (isa<CXXConstructorDecl>(CurDecl))
3013 FunctionKind = 2;
3014 else if (isa<CXXDestructorDecl>(CurDecl))
3015 FunctionKind = 3;
3016
Nick Lewycky1be750a2011-06-01 07:44:31 +00003017 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003018 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003019 << RetValExp->getSourceRange();
3020 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003021 }
Mike Stump11289f42009-09-09 15:08:12 +00003022
Sebastian Redleef474c2012-02-22 10:50:08 +00003023 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003024 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3025 if (ER.isInvalid())
3026 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003027 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003028 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030
Craig Topperc3ec1492014-05-26 06:22:03 +00003031 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003032 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003033 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
3034 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003035 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003036
3037 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00003038 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003039 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003040 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003041 Result = new (Context) ReturnStmt(ReturnLoc);
3042 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003043 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003044 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003045
3046 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3047
3048 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3049 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3050 // function return.
3051
3052 // In C++ the return statement is handled via a copy initialization,
3053 // the C version of which boils down to CheckSingleAssignmentConstraints.
3054 if (RetValExp)
3055 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003056 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003057 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003059 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003060 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003061 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003062 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003063 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003064 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003065 return StmtError();
3066 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003067 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003068
3069 // If we have a related result type, we need to implicitly
3070 // convert back to the formal result type. We can't pretend to
3071 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003072 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003073 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003074 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3075 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003076 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3077 if (Res.isInvalid()) {
3078 // FIXME: Clean up temporaries here anyway?
3079 return StmtError();
3080 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003081 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003082 }
3083
Artyom Skrobov9f213442014-01-24 11:10:39 +00003084 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3085 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087
John McCallacf0ee52010-10-08 02:01:28 +00003088 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003089 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3090 if (ER.isInvalid())
3091 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003092 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003093 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003094 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
3097 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003098 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003099 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003100 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003101
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003102 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003103}
3104
John McCalldadc5752010-08-24 06:29:42 +00003105StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003106Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003107 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003108 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003109 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003110 if (Var && Var->isInvalidDecl())
3111 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003113 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003114}
3115
John McCalldadc5752010-08-24 06:29:42 +00003116StmtResult
John McCallb268a282010-08-23 23:25:46 +00003117Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003118 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003119}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003120
John McCalldadc5752010-08-24 06:29:42 +00003121StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003123 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003124 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003125 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3126
John McCallaab3e412010-08-25 08:40:02 +00003127 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003128 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003129 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3130 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003131}
3132
John McCall0bd3e402012-05-08 21:41:25 +00003133StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003134 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003135 ExprResult Result = DefaultLvalueConversion(Throw);
3136 if (Result.isInvalid())
3137 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003138
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003139 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003140 if (Result.isInvalid())
3141 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003142 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003143
Douglas Gregor2900c162010-04-22 21:44:01 +00003144 QualType ThrowType = Throw->getType();
3145 // Make sure the expression type is an ObjC pointer or "void *".
3146 if (!ThrowType->isDependentType() &&
3147 !ThrowType->isObjCObjectPointerType()) {
3148 const PointerType *PT = ThrowType->getAs<PointerType>();
3149 if (!PT || !PT->getPointeeType()->isVoidType())
3150 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3151 << Throw->getType() << Throw->getSourceRange());
3152 }
3153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003155 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003156}
3157
John McCalldadc5752010-08-24 06:29:42 +00003158StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003160 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003161 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003162 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3163
John McCallb268a282010-08-23 23:25:46 +00003164 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003165 // @throw without an expression designates a rethrow (which much occur
3166 // in the context of an @catch clause).
3167 Scope *AtCatchParent = CurScope;
3168 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3169 AtCatchParent = AtCatchParent->getParent();
3170 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003171 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172 }
John McCallb268a282010-08-23 23:25:46 +00003173 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003174}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003175
John McCalld9bb7432011-07-27 21:50:02 +00003176ExprResult
3177Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3178 ExprResult result = DefaultLvalueConversion(operand);
3179 if (result.isInvalid())
3180 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003181 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003182
3183 // Make sure the expression type is an ObjC pointer or "void *".
3184 QualType type = operand->getType();
3185 if (!type->isDependentType() &&
3186 !type->isObjCObjectPointerType()) {
3187 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003188 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3189 if (getLangOpts().CPlusPlus) {
3190 if (RequireCompleteType(atLoc, type,
3191 diag::err_incomplete_receiver_type))
3192 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3193 << type << operand->getSourceRange();
3194
3195 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3196 if (!result.isUsable())
3197 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3198 << type << operand->getSourceRange();
3199
3200 operand = result.get();
3201 } else {
3202 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3203 << type << operand->getSourceRange();
3204 }
3205 }
John McCalld9bb7432011-07-27 21:50:02 +00003206 }
3207
3208 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003209 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003210}
3211
John McCalldadc5752010-08-24 06:29:42 +00003212StmtResult
John McCallb268a282010-08-23 23:25:46 +00003213Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3214 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003215 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003216 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003217 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003218}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003219
3220/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3221/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003222StmtResult
John McCall48871652010-08-21 09:40:31 +00003223Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003224 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003225 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003226 return new (Context)
3227 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003228}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003229
John McCall31168b02011-06-15 23:02:42 +00003230StmtResult
3231Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3232 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003233 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003234}
3235
Dan Gohman28ade552010-07-26 21:25:24 +00003236namespace {
3237
Sebastian Redl63c4da02009-07-29 17:15:45 +00003238class TypeWithHandler {
3239 QualType t;
3240 CXXCatchStmt *stmt;
3241public:
3242 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3243 : t(type), stmt(statement) {}
3244
John McCall8ccfcb52009-09-24 19:53:00 +00003245 // An arbitrary order is fine as long as it places identical
3246 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003247 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003248 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003249 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003250 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003251 return false;
3252 else
3253 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3254 }
Mike Stump11289f42009-09-09 15:08:12 +00003255
Sebastian Redl63c4da02009-07-29 17:15:45 +00003256 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003257 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003258 }
Mike Stump11289f42009-09-09 15:08:12 +00003259
Sebastian Redl63c4da02009-07-29 17:15:45 +00003260 CXXCatchStmt *getCatchStmt() const { return stmt; }
3261 SourceLocation getTypeSpecStartLoc() const {
3262 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3263 }
3264};
3265
Dan Gohman28ade552010-07-26 21:25:24 +00003266}
3267
Sebastian Redl9b244a82008-12-22 21:35:02 +00003268/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3269/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003270StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3271 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003272 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003273 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003274 !getSourceManager().isInSystemHeader(TryLoc))
3275 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003276
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003277 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3278 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3279
Robert Wilhelmcafda822013-08-22 09:20:03 +00003280 const unsigned NumHandlers = Handlers.size();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003281 assert(NumHandlers > 0 &&
3282 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003283
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003284 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003285
3286 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003287 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003288 if (!Handler->getExceptionDecl()) {
3289 if (i < NumHandlers - 1)
3290 return StmtError(Diag(Handler->getLocStart(),
3291 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003292
Sebastian Redl63c4da02009-07-29 17:15:45 +00003293 continue;
3294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Sebastian Redl63c4da02009-07-29 17:15:45 +00003296 const QualType CaughtType = Handler->getCaughtType();
3297 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3298 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003299 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003300
3301 // Detect handlers for the same type as an earlier one.
3302 if (NumHandlers > 1) {
3303 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003304
Sebastian Redl63c4da02009-07-29 17:15:45 +00003305 TypeWithHandler prev = TypesWithHandlers[0];
3306 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3307 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003308
Sebastian Redl63c4da02009-07-29 17:15:45 +00003309 if (curr == prev) {
3310 Diag(curr.getTypeSpecStartLoc(),
3311 diag::warn_exception_caught_by_earlier_handler)
3312 << curr.getCatchStmt()->getCaughtType().getAsString();
3313 Diag(prev.getTypeSpecStartLoc(),
3314 diag::note_previous_exception_handler)
3315 << prev.getCatchStmt()->getCaughtType().getAsString();
3316 }
Mike Stump11289f42009-09-09 15:08:12 +00003317
Sebastian Redl63c4da02009-07-29 17:15:45 +00003318 prev = curr;
3319 }
3320 }
Mike Stump11289f42009-09-09 15:08:12 +00003321
John McCallaab3e412010-08-25 08:40:02 +00003322 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003323
Sebastian Redl9b244a82008-12-22 21:35:02 +00003324 // FIXME: We should detect handlers that cannot catch anything because an
3325 // earlier handler catches a superclass. Need to find a method that is not
3326 // quadratic for this.
3327 // Neither of these are explicitly forbidden, but every compiler detects them
3328 // and warns.
3329
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003330 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003331}
John Wiegley1c0675e2011-04-28 01:08:34 +00003332
Warren Huntf6be4cb2014-07-25 20:52:51 +00003333StmtResult
3334Sema::ActOnSEHTryBlock(bool IsCXXTry,
3335 SourceLocation TryLoc,
3336 Stmt *TryBlock,
3337 Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003338 assert(TryBlock && Handler);
3339
3340 getCurFunction()->setHasBranchProtectedScope();
3341
Warren Huntf6be4cb2014-07-25 20:52:51 +00003342 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003343}
3344
3345StmtResult
3346Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3347 Expr *FilterExpr,
3348 Stmt *Block) {
3349 assert(FilterExpr && Block);
3350
3351 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003352 return StmtError(Diag(FilterExpr->getExprLoc(),
3353 diag::err_filter_expression_integral)
3354 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003355 }
3356
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003357 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003358}
3359
3360StmtResult
3361Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3362 Stmt *Block) {
3363 assert(Block);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003364 return SEHFinallyStmt::Create(Context,Loc,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003365}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003366
Nico Weberc7d05962014-07-06 22:32:59 +00003367StmtResult
3368Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003369 Scope *SEHTryParent = CurScope;
3370 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3371 SEHTryParent = SEHTryParent->getParent();
3372 if (!SEHTryParent)
3373 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3374
Nico Weber9b982072014-07-07 00:12:30 +00003375 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003376}
3377
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003378StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3379 bool IsIfExists,
3380 NestedNameSpecifierLoc QualifierLoc,
3381 DeclarationNameInfo NameInfo,
3382 Stmt *Nested)
3383{
3384 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003385 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003386 cast<CompoundStmt>(Nested));
3387}
3388
3389
Chad Rosier02a84392012-08-10 17:56:09 +00003390StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003391 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003392 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003393 UnqualifiedId &Name,
3394 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003395 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003396 SS.getWithLocInContext(Context),
3397 GetNameFromUnqualifiedId(Name),
3398 Nested);
3399}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003400
3401RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003402Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3403 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003404 DeclContext *DC = CurContext;
3405 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3406 DC = DC->getParent();
3407
Craig Topperc3ec1492014-05-26 06:22:03 +00003408 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003409 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003410 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3411 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003412 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003413 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003414
Alexey Bataev330de032014-10-29 12:21:55 +00003415 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003416 DC->addDecl(RD);
3417 RD->setImplicit();
3418 RD->startDefinition();
3419
Alexey Bataev9959db52014-05-06 10:08:46 +00003420 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003421 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003422 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003423 return RD;
3424}
3425
3426static void buildCapturedStmtCaptureList(
3427 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3428 SmallVectorImpl<Expr *> &CaptureInits,
3429 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3430
3431 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3432 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3433
3434 if (Cap->isThisCapture()) {
3435 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3436 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003437 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003438 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003439 } else if (Cap->isVLATypeCapture()) {
3440 Captures.push_back(
3441 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3442 CaptureInits.push_back(nullptr);
3443 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003444 }
3445
3446 assert(Cap->isReferenceCapture() &&
3447 "non-reference capture not yet implemented");
3448
3449 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3450 CapturedStmt::VCK_ByRef,
3451 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003452 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003453 }
3454}
3455
3456void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003457 CapturedRegionKind Kind,
3458 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003459 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003460 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003461
Alexey Bataev9959db52014-05-06 10:08:46 +00003462 // Build the context parameter
3463 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3464 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3465 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3466 ImplicitParamDecl *Param
3467 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3468 DC->addDecl(Param);
3469
3470 CD->setContextParam(0, Param);
3471
3472 // Enter the capturing scope for this captured region.
3473 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3474
3475 if (CurScope)
3476 PushDeclContext(CurScope, CD);
3477 else
3478 CurContext = CD;
3479
3480 PushExpressionEvaluationContext(PotentiallyEvaluated);
3481}
3482
3483void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3484 CapturedRegionKind Kind,
3485 ArrayRef<CapturedParamNameType> Params) {
3486 CapturedDecl *CD = nullptr;
3487 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3488
3489 // Build the context parameter
3490 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3491 bool ContextIsFound = false;
3492 unsigned ParamNum = 0;
3493 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3494 E = Params.end();
3495 I != E; ++I, ++ParamNum) {
3496 if (I->second.isNull()) {
3497 assert(!ContextIsFound &&
3498 "null type has been found already for '__context' parameter");
3499 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3500 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3501 ImplicitParamDecl *Param
3502 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3503 DC->addDecl(Param);
3504 CD->setContextParam(ParamNum, Param);
3505 ContextIsFound = true;
3506 } else {
3507 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3508 ImplicitParamDecl *Param
3509 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3510 DC->addDecl(Param);
3511 CD->setParam(ParamNum, Param);
3512 }
3513 }
3514 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003515 if (!ContextIsFound) {
3516 // Add __context implicitly if it is not specified.
3517 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3518 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3519 ImplicitParamDecl *Param =
3520 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3521 DC->addDecl(Param);
3522 CD->setContextParam(ParamNum, Param);
3523 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003524 // Enter the capturing scope for this captured region.
3525 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3526
3527 if (CurScope)
3528 PushDeclContext(CurScope, CD);
3529 else
3530 CurContext = CD;
3531
3532 PushExpressionEvaluationContext(PotentiallyEvaluated);
3533}
3534
Wei Pan17fbf6e2013-05-04 03:59:06 +00003535void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003536 DiscardCleanupsInEvaluationContext();
3537 PopExpressionEvaluationContext();
3538
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003539 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3540 RecordDecl *Record = RSI->TheRecordDecl;
3541 Record->setInvalidDecl();
3542
Aaron Ballman62e47c42014-03-10 13:43:55 +00003543 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003544 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3545 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003546
Wei Pan17fbf6e2013-05-04 03:59:06 +00003547 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003548 PopFunctionScopeInfo();
3549}
3550
3551StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3552 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3553
3554 SmallVector<CapturedStmt::Capture, 4> Captures;
3555 SmallVector<Expr *, 4> CaptureInits;
3556 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3557
3558 CapturedDecl *CD = RSI->TheCapturedDecl;
3559 RecordDecl *RD = RSI->TheRecordDecl;
3560
Wei Pan17fbf6e2013-05-04 03:59:06 +00003561 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3562 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003563 CaptureInits, CD, RD);
3564
3565 CD->setBody(Res->getCapturedStmt());
3566 RD->completeDefinition();
3567
Wei Pan17fbf6e2013-05-04 03:59:06 +00003568 DiscardCleanupsInEvaluationContext();
3569 PopExpressionEvaluationContext();
3570
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003571 PopDeclContext();
3572 PopFunctionScopeInfo();
3573
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003574 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003575}