blob: dc5619db9a468efd99af82ed0d624ea1c2b91d19 [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"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000022#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000024#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000035using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000036using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000037
Richard Smith945f8d32013-01-14 22:39:08 +000038StmtResult Sema::ActOnExprStmt(ExprResult FE) {
39 if (FE.isInvalid())
40 return StmtError();
41
42 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
43 /*DiscardedValue*/ true);
44 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000045 return StmtError();
46
Chris Lattner903eb512008-07-25 23:18:17 +000047 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
48 // void expression for its side effects. Conversion to void allows any
49 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000050
Chris Lattner903eb512008-07-25 23:18:17 +000051 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000052 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000053}
54
55
John McCalleaef89b2013-03-22 02:10:40 +000056StmtResult Sema::ActOnExprStmtError() {
57 DiscardCleanupsInEvaluationContext();
58 return StmtError();
59}
60
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000061StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000062 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000063 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000064}
65
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000066StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000068 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattnercbafe8d2009-04-12 20:13:14 +000070 // If we have an invalid decl, just return an error.
71 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000072
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000073 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000074}
Chris Lattneraf8d5812006-11-10 05:07:45 +000075
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000076void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000077 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000078
Douglas Gregor2eb1c572013-04-08 20:52:24 +000079 // If we don't have a declaration, or we have an invalid declaration,
80 // just return.
81 if (DG.isNull() || !DG.isSingleDecl())
82 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083
Douglas Gregor2eb1c572013-04-08 20:52:24 +000084 Decl *decl = DG.getSingleDecl();
85 if (!decl || decl->isInvalidDecl())
86 return;
87
88 // Only variable declarations are permitted.
89 VarDecl *var = dyn_cast<VarDecl>(decl);
90 if (!var) {
91 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
92 decl->setInvalidDecl();
93 return;
94 }
John McCall31168b02011-06-15 23:02:42 +000095
John McCalld4631322011-06-17 06:42:21 +000096 // foreach variables are never actually initialized in the way that
97 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +000098 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +000099
John McCalld4631322011-06-17 06:42:21 +0000100 // In ARC, we don't need to retain the iteration variable of a fast
101 // enumeration loop. Rather than actually trying to catch that
102 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000103 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000104 QualType type = var->getType();
105
106 // Only do this if we inferred the lifetime. Inferred lifetime
107 // will show up as a local qualifier because explicit lifetime
108 // should have shown up as an AttributedType instead.
109 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
110 // Add 'const' and mark the variable as pseudo-strong.
111 var->setType(type.withConst());
112 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000113 }
114 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000115}
116
Richard Trieu99e1c952014-03-11 03:11:08 +0000117/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
118/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000119///
120/// Adding a cast to void (or other expression wrappers) will prevent the
121/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000122static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000123 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000124 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125
126 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000127 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000128 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129
Richard Trieu99e1c952014-03-11 03:11:08 +0000130 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000132 IsNotEqual = Op->getOpcode() == BO_NE;
133 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000134 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000135 switch (Op->getOperator()) {
136 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000137 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000138 case OO_EqualEqual:
139 case OO_ExclaimEqual:
140 IsRelational = false;
141 break;
142 case OO_Less:
143 case OO_Greater:
144 case OO_GreaterEqual:
145 case OO_LessEqual:
146 IsRelational = true;
147 break;
148 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000149
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000150 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000151 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
152 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000153 } else {
154 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000155 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 }
157
158 // Suppress warnings when the operator, suspicious as it may be, comes from
159 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000160 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000161 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000162
Chandler Carruthe2669392011-08-17 09:34:37 +0000163 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000164 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000165
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000166 // If the LHS is a plausible entity to assign to, provide a fixit hint to
167 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000168 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000169 if (IsNotEqual)
170 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
171 << FixItHint::CreateReplacement(Loc, "|=");
172 else
173 S.Diag(Loc, diag::note_equality_comparison_to_assign)
174 << FixItHint::CreateReplacement(Loc, "=");
175 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000176
177 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000178}
179
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000180void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000181 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
182 return DiagnoseUnusedExprResult(Label->getSubStmt());
183
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000184 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000185 if (!E)
186 return;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000187 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000188 // In most cases, we don't want to warn if the expression is written in a
189 // macro body, or if the macro comes from a system header. If the offending
190 // expression is a call to a function with the warn_unused_result attribute,
191 // we warn no matter the location. Because of the order in which the various
192 // checks need to happen, we factor out the macro-related test here.
193 bool ShouldSuppress =
194 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
195 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000196
Eli Friedmanc11535c2012-05-24 00:47:05 +0000197 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000198 SourceLocation Loc;
199 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000200 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000201 return;
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner6dc7e572012-08-31 22:39:21 +0000203 // If this is a GNU statement expression expanded from a macro, it is probably
204 // unused because it is a function-like macro that can be used as either an
205 // expression or statement. Don't warn, because it is almost certainly a
206 // false positive.
207 if (isa<StmtExpr>(E) && Loc.isMacroID())
208 return;
209
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000210 // Okay, we have an unused result. Depending on what the base expression is,
211 // we might want to make a more specific diagnostic. Check for one of these
212 // cases now.
213 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000214 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000215 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000216 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
217 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000218
Chandler Carruthe2669392011-08-17 09:34:37 +0000219 if (DiagnoseUnusedComparison(*this, E))
220 return;
221
Eli Friedmanc11535c2012-05-24 00:47:05 +0000222 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000223 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000224 if (E->getType()->isVoidType())
225 return;
226
Chris Lattner1a6babf2009-10-13 04:53:48 +0000227 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000228 // a more specific message to make it clear what is happening. If the call
229 // is written in a macro body, only warn if it has the warn_unused_result
230 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000231 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000232 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000233 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000234 return;
235 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000236 if (ShouldSuppress)
237 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000238 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000239 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
240 return;
241 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000242 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000243 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
244 return;
245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000246 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000247 } else if (ShouldSuppress)
248 return;
249
250 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000251 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000252 Diag(Loc, diag::err_arc_unused_init_message) << R1;
253 return;
254 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000255 const ObjCMethodDecl *MD = ME->getMethodDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +0000256 if (MD && MD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000257 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000258 return;
259 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
261 const Expr *Source = POE->getSyntacticForm();
262 if (isa<ObjCSubscriptRefExpr>(Source))
263 DiagID = diag::warn_unused_container_subscript_expr;
264 else
265 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000266 } else if (const CXXFunctionalCastExpr *FC
267 = dyn_cast<CXXFunctionalCastExpr>(E)) {
268 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
269 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
270 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000271 }
John McCall2351cb92010-04-06 22:24:14 +0000272 // Diagnose "(void*) blah" as a typo for "(void) blah".
273 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
274 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
275 QualType T = TI->getType();
276
277 // We really do want to use the non-canonical type here.
278 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000279 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000280
281 Diag(Loc, diag::warn_unused_voidptr)
282 << FixItHint::CreateRemoval(TL.getStarLoc());
283 return;
284 }
285 }
286
Eli Friedmanc11535c2012-05-24 00:47:05 +0000287 if (E->isGLValue() && E->getType().isVolatileQualified()) {
288 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
289 return;
290 }
291
Craig Topperc3ec1492014-05-26 06:22:03 +0000292 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000293}
294
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000295void Sema::ActOnStartOfCompoundStmt() {
296 PushCompoundScope();
297}
298
299void Sema::ActOnFinishOfCompoundStmt() {
300 PopCompoundScope();
301}
302
303sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
304 return getCurFunction()->CompoundScopes.back();
305}
306
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000307StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
308 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
309 const unsigned NumElts = Elts.size();
310
Chris Lattnerd864daf2007-08-27 04:29:41 +0000311 // If we're in C89 mode, check that we don't have any decls after stmts. If
312 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000313 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000314 // Note that __extension__ can be around a decl.
315 unsigned i = 0;
316 // Skip over all declarations.
317 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
318 /*empty*/;
319
320 // We found the end of the list or a statement. Scan for another declstmt.
321 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
322 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattnerd864daf2007-08-27 04:29:41 +0000324 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000325 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000326 Diag(D->getLocation(), diag::ext_mixed_decls_code);
327 }
328 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000329 // Warn about unused expressions in statements.
330 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000331 // Ignore statements that are last in a statement expression.
332 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000333 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000334
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000335 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000336 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000337
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000338 // Check for suspicious empty body (null statement) in `for' and `while'
339 // statements. Don't do anything for template instantiations, this just adds
340 // noise.
341 if (NumElts != 0 && !CurrentInstantiationScope &&
342 getCurCompoundScope().HasEmptyLoopBodies) {
343 for (unsigned i = 0; i != NumElts - 1; ++i)
344 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
345 }
346
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000347 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000348}
349
John McCalldadc5752010-08-24 06:29:42 +0000350StmtResult
John McCallb268a282010-08-23 23:25:46 +0000351Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
352 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000353 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000354 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000355
John McCallaab3e412010-08-25 08:40:02 +0000356 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000357 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000358 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000359 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000360
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000361 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000362 // C99 6.8.4.2p3: The expression shall be an integer constant.
363 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000364 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000365 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000366 if (!LHSVal)
367 return StmtError();
368 }
Richard Smithf8379a02012-01-18 23:55:52 +0000369
370 // GCC extension: The expression shall be an integer constant.
371
Richard Smithf4c51d92012-02-04 09:53:13 +0000372 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000373 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000374 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000375 }
376 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000377
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000378 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000379 getLangOpts().CPlusPlus11).get();
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000380 if (RHSVal)
381 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000382 getLangOpts().CPlusPlus11).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000383
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000384 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
385 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000386 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000387 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000388}
389
Chris Lattner34a22092009-03-04 04:23:07 +0000390/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000391void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000392 DiagnoseUnusedExprResult(SubStmt);
393
Chris Lattner34a22092009-03-04 04:23:07 +0000394 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000395 CS->setSubStmt(SubStmt);
396}
397
John McCalldadc5752010-08-24 06:29:42 +0000398StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000399Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000400 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000401 DiagnoseUnusedExprResult(SubStmt);
402
John McCallaab3e412010-08-25 08:40:02 +0000403 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000404 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000405 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000406 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000407
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000408 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000409 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000410 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000411}
412
John McCalldadc5752010-08-24 06:29:42 +0000413StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000414Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
415 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000416 // If the label was multiply defined, reject it now.
417 if (TheDecl->getStmt()) {
418 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
419 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000420 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000421 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000422
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000423 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000424 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
425 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000426 if (!TheDecl->isGnuLocal()) {
427 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000428 TheDecl->setLocation(IdentLoc);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000429 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000430 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000431}
432
Richard Smithc202b282012-04-14 00:33:13 +0000433StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000434 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000435 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000436 // Fill in the declaration and return it.
437 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000438 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000439}
440
John McCalldadc5752010-08-24 06:29:42 +0000441StmtResult
John McCall48871652010-08-21 09:40:31 +0000442Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000443 Stmt *thenStmt, SourceLocation ElseLoc,
444 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000445 // If the condition was invalid, discard the if statement. We could recover
446 // better by replacing it with a valid expr, but don't do that yet.
447 if (!CondVal.get() && !CondVar) {
448 getCurFunction()->setHasDroppedStmt();
449 return StmtError();
450 }
451
John McCalldadc5752010-08-24 06:29:42 +0000452 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000453
Craig Topperc3ec1492014-05-26 06:22:03 +0000454 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000455 if (CondVar) {
456 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000457 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000458 if (CondResult.isInvalid())
459 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000460 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000461 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000462 if (!ConditionExpr)
463 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000465 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000466
John McCallb268a282010-08-23 23:25:46 +0000467 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000468 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
469 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000470 }
471
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000472 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000473
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000474 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
475 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000476}
Steve Naroff86272ea2007-05-29 02:14:17 +0000477
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000478/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
479/// the specified width and sign. If an overflow occurs, detect it and emit
480/// the specified diagnostic.
481void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
482 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000483 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000484 unsigned DiagID) {
485 // Perform a conversion to the promoted condition type if needed.
486 if (NewWidth > Val.getBitWidth()) {
487 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000488 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000489 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000490
491 // If the input was signed and negative and the output is
492 // unsigned, don't bother to warn: this is implementation-defined
493 // behavior.
494 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000495 } else if (NewWidth < Val.getBitWidth()) {
496 // If this is a truncation, check for overflow.
497 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000498 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000499 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000500 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000501 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000502 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000503 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000505 // Regardless of whether a diagnostic was emitted, really do the
506 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000507 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000508 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000509 } else if (NewSign != Val.isSigned()) {
510 // Convert the sign to match the sign of the condition. This can cause
511 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000512 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000513 // behavior.
514 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000515 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000516 }
517}
518
Chris Lattner67998452007-08-23 18:29:20 +0000519namespace {
520 struct CaseCompareFunctor {
521 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
522 const llvm::APSInt &RHS) {
523 return LHS.first < RHS;
524 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000525 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
526 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
527 return LHS.first < RHS.first;
528 }
Chris Lattner67998452007-08-23 18:29:20 +0000529 bool operator()(const llvm::APSInt &LHS,
530 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
531 return LHS < RHS.first;
532 }
533 };
534}
535
Chris Lattner4b2ff022007-09-21 18:15:22 +0000536/// CmpCaseVals - Comparison predicate for sorting case values.
537///
538static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
539 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
540 if (lhs.first < rhs.first)
541 return true;
542
543 if (lhs.first == rhs.first &&
544 lhs.second->getCaseLoc().getRawEncoding()
545 < rhs.second->getCaseLoc().getRawEncoding())
546 return true;
547 return false;
548}
549
Douglas Gregorbd6839732010-02-08 22:24:16 +0000550/// CmpEnumVals - Comparison predicate for sorting enumeration values.
551///
552static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
553 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
554{
555 return lhs.first < rhs.first;
556}
557
558/// EqEnumVals - Comparison preficate for uniqing enumeration values.
559///
560static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
561 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
562{
563 return lhs.first == rhs.first;
564}
565
Chris Lattnera96d4272009-10-16 16:45:22 +0000566/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
567/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000568static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
569 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
570 expr = cleanups->getSubExpr();
571 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
572 if (impcast->getCastKind() != CK_IntegralCast) break;
573 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000574 }
575 return expr->getType();
576}
577
John McCalldadc5752010-08-24 06:29:42 +0000578StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000580 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000581 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000582
Craig Topperc3ec1492014-05-26 06:22:03 +0000583 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000584 if (CondVar) {
585 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000586 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
587 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000588 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000590 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
John McCallb268a282010-08-23 23:25:46 +0000593 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000594 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregore2b37442012-05-04 22:38:52 +0000596 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
597 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000598
Douglas Gregore2b37442012-05-04 22:38:52 +0000599 public:
600 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000601 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
602 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000603
Craig Toppere14c0f82014-03-12 04:55:44 +0000604 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
605 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000606 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
607 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000608
Craig Toppere14c0f82014-03-12 04:55:44 +0000609 SemaDiagnosticBuilder diagnoseIncomplete(
610 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000611 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
612 << T << Cond->getSourceRange();
613 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000614
Craig Toppere14c0f82014-03-12 04:55:44 +0000615 SemaDiagnosticBuilder diagnoseExplicitConv(
616 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000617 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
618 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000619
Craig Toppere14c0f82014-03-12 04:55:44 +0000620 SemaDiagnosticBuilder noteExplicitConv(
621 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000622 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
623 << ConvTy->isEnumeralType() << ConvTy;
624 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000625
Craig Toppere14c0f82014-03-12 04:55:44 +0000626 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
627 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000628 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
629 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000630
Craig Toppere14c0f82014-03-12 04:55:44 +0000631 SemaDiagnosticBuilder noteAmbiguous(
632 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000633 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
634 << ConvTy->isEnumeralType() << ConvTy;
635 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000636
Craig Toppere14c0f82014-03-12 04:55:44 +0000637 SemaDiagnosticBuilder diagnoseConversion(
638 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000639 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000640 }
641 } SwitchDiagnoser(Cond);
642
Richard Smithccc11812013-05-21 19:05:48 +0000643 CondResult =
644 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000645 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000646 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000647
John McCall5939b162011-08-06 07:30:58 +0000648 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
649 CondResult = UsualUnaryConversions(Cond);
650 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000651 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000652
John McCall48871652010-08-21 09:40:31 +0000653 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000654 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000655 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000656 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000657 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000658 }
John McCalla95172b2010-08-01 00:26:45 +0000659
John McCallaab3e412010-08-25 08:40:02 +0000660 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
John McCallb268a282010-08-23 23:25:46 +0000662 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000663 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000664 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000665}
666
Gabor Greif16e02862010-10-01 22:05:14 +0000667static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
668 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000669 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000670 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000671 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000672 Val.setIsSigned(IsSigned);
673}
674
Dmitri Gribenko58683752013-12-05 22:52:07 +0000675/// Returns true if we should emit a diagnostic about this case expression not
676/// being a part of the enum used in the switch controlling expression.
677static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
678 const EnumDecl *ED,
679 const Expr *CaseExpr) {
680 // Don't warn if the 'case' expression refers to a static const variable of
681 // the enum type.
682 CaseExpr = CaseExpr->IgnoreParenImpCasts();
683 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
684 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
685 if (!VD->hasGlobalStorage())
686 return true;
687 QualType VarType = VD->getType();
688 if (!VarType.isConstQualified())
689 return true;
690 QualType EnumType = Ctx.getTypeDeclType(ED);
691 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
692 return false;
693 }
694 }
695 return true;
696}
697
John McCalldadc5752010-08-24 06:29:42 +0000698StmtResult
John McCallb268a282010-08-23 23:25:46 +0000699Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
700 Stmt *BodyStmt) {
701 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000702 assert(SS == getCurFunction()->SwitchStack.back() &&
703 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000704
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000705 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000706 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000707 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000708
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000709 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000710 if (!CondExpr) return StmtError();
711
712 QualType CondType = CondExpr->getType();
713
John McCalld3dfbd62010-05-18 03:19:21 +0000714 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000715 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000716 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000717
Chris Lattnera96d4272009-10-16 16:45:22 +0000718 // C++ 6.4.2.p2:
719 // Integral promotions are performed (on the switch condition).
720 //
721 // A case value unrepresentable by the original switch condition
722 // type (before the promotion) doesn't make sense, even when it can
723 // be represented by the promoted type. Therefore we need to find
724 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000725 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000726 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000728 // appropriate type now, just return an error.
729 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000730 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000731
Chris Lattner4ebae652010-04-16 23:34:13 +0000732 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000733 // switch(bool_expr) {...} is often a programmer error, e.g.
734 // switch(n && mask) { ... } // Doh - should be "n & mask".
735 // One can always use an if statement instead of switch(bool_expr).
736 Diag(SwitchLoc, diag::warn_bool_switch_condition)
737 << CondExpr->getSourceRange();
738 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000739 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000740
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000741 // Get the bitwidth of the switched-on value before promotions. We must
742 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000743 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000744 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000745 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000746 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier02a84392012-08-10 17:56:09 +0000747 bool CondIsSigned
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000748 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000750 // Accumulate all of the case values in a vector so that we can sort them
751 // and detect duplicates. This vector contains the APInt for the case after
752 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000753 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000754 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000756 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000757 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
758 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000759
Craig Topperc3ec1492014-05-26 06:22:03 +0000760 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner10cb5e52007-08-23 06:23:56 +0000762 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000763
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000764 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000765 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000766
Anders Carlsson51873c22007-07-22 07:07:56 +0000767 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000768 if (TheDefaultStmt) {
769 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000770 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000771
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000772 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000773 // we'll return a valid AST. This requires recursing down the AST and
774 // finding it, not something we are set up to do right now. For now,
775 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000776 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000777 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000778 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000780 } else {
781 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattnera65e1f32008-01-16 19:17:22 +0000783 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000784
785 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
786 HasDependentValue = true;
787 break;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Richard Smithf8379a02012-01-18 23:55:52 +0000790 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000791
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000792 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000793 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
794 // constant expression of the promoted type of the switch condition.
795 ExprResult ConvLo =
796 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
797 if (ConvLo.isInvalid()) {
798 CaseListIsErroneous = true;
799 continue;
800 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000801 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000802 } else {
803 // We already verified that the expression has a i-c-e value (C99
804 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000805 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000806
807 // If the LHS is not the same type as the condition, insert an implicit
808 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000809 Lo = DefaultLvalueConversion(Lo).get();
810 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000811 }
812
813 // Convert the value to the same width/sign as the condition had prior to
814 // integral promotions.
815 //
816 // FIXME: This causes us to reject valid code:
817 // switch ((char)c) { case 256: case 0: return 0; }
818 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000819 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000820 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000821 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000822
Chris Lattnera65e1f32008-01-16 19:17:22 +0000823 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chris Lattner10cb5e52007-08-23 06:23:56 +0000825 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000826 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000827 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000828 CS->getRHS()->isValueDependent()) {
829 HasDependentValue = true;
830 break;
831 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000832 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000833 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000834 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000835 }
836 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000837
838 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000839 // If we don't have a default statement, check whether the
840 // condition is constant.
841 llvm::APSInt ConstantCondValue;
842 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000843 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000844 HasConstantCond
Richard Smith5fab0c92011-12-28 19:48:30 +0000845 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
846 Expr::SE_AllowSideEffects);
847 assert(!HasConstantCond ||
848 (ConstantCondValue.getBitWidth() == CondWidth &&
849 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000850 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000851 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000852
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000853 // Sort all the scalar case values so we can easily detect duplicates.
854 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
855
856 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000857 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
858 if (ShouldCheckConstantCond &&
859 CaseVals[i].first == ConstantCondValue)
860 ShouldCheckConstantCond = false;
861
862 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000863 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000864 // First, determine if either case value has a name
865 StringRef PrevString, CurrString;
866 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
867 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
868 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
869 PrevString = DeclRef->getDecl()->getName();
870 }
871 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
872 CurrString = DeclRef->getDecl()->getName();
873 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000874 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000875 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000876
877 if (PrevString == CurrString)
878 Diag(CaseVals[i].second->getLHS()->getLocStart(),
879 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000880 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000881 else
882 Diag(CaseVals[i].second->getLHS()->getLocStart(),
883 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000884 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
885 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000886 CaseValStr;
887
John McCalld3dfbd62010-05-18 03:19:21 +0000888 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000889 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000890 // FIXME: We really want to remove the bogus case stmt from the
891 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000892 CaseListIsErroneous = true;
893 }
894 }
895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000897 // Detect duplicate case ranges, which usually don't exist at all in
898 // the first place.
899 if (!CaseRanges.empty()) {
900 // Sort all the case ranges by their low value so we can easily detect
901 // overlaps between ranges.
902 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000903
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000904 // Scan the ranges, computing the high values and removing empty ranges.
905 std::vector<llvm::APSInt> HiVals;
906 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000907 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000908 CaseStmt *CR = CaseRanges[i].second;
909 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000910 llvm::APSInt HiVal;
911
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000912 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000913 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
914 // constant expression of the promoted type of the switch condition.
915 ExprResult ConvHi =
916 CheckConvertedConstantExpression(Hi, CondType, HiVal,
917 CCEK_CaseValue);
918 if (ConvHi.isInvalid()) {
919 CaseListIsErroneous = true;
920 continue;
921 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000922 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000923 } else {
924 HiVal = Hi->EvaluateKnownConstInt(Context);
925
926 // If the RHS is not the same type as the condition, insert an
927 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000928 Hi = DefaultLvalueConversion(Hi).get();
929 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000932 // Convert the value to the same width/sign as the condition.
933 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000934 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000935 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000936
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000937 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000938
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000939 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000940 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000941 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
942 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000943 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000944 CaseRanges.erase(CaseRanges.begin()+i);
945 --i, --e;
946 continue;
947 }
John McCalld3dfbd62010-05-18 03:19:21 +0000948
949 if (ShouldCheckConstantCond &&
950 LoVal <= ConstantCondValue &&
951 ConstantCondValue <= HiVal)
952 ShouldCheckConstantCond = false;
953
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000954 HiVals.push_back(HiVal);
955 }
Mike Stump11289f42009-09-09 15:08:12 +0000956
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000957 // Rescan the ranges, looking for overlap with singleton values and other
958 // ranges. Since the range list is sorted, we only need to compare case
959 // ranges with their neighbors.
960 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
961 llvm::APSInt &CRLo = CaseRanges[i].first;
962 llvm::APSInt &CRHi = HiVals[i];
963 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000965 // Check to see whether the case range overlaps with any
966 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +0000967 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000968 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000969
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000970 // Find the smallest value >= the lower bound. If I is in the
971 // case range, then we have overlap.
972 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
973 CaseVals.end(), CRLo,
974 CaseCompareFunctor());
975 if (I != CaseVals.end() && I->first < CRHi) {
976 OverlapVal = I->first; // Found overlap with scalar.
977 OverlapStmt = I->second;
978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000980 // Find the smallest value bigger than the upper bound.
981 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
982 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
983 OverlapVal = (I-1)->first; // Found overlap with scalar.
984 OverlapStmt = (I-1)->second;
985 }
Mike Stump11289f42009-09-09 15:08:12 +0000986
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000987 // Check to see if this case stmt overlaps with the subsequent
988 // case range.
989 if (i && CRLo <= HiVals[i-1]) {
990 OverlapVal = HiVals[i-1]; // Found overlap with range.
991 OverlapStmt = CaseRanges[i-1].second;
992 }
Mike Stump11289f42009-09-09 15:08:12 +0000993
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000994 if (OverlapStmt) {
995 // If we have a duplicate, report it.
996 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
997 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000998 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000999 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001000 // FIXME: We really want to remove the bogus case stmt from the
1001 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001002 CaseListIsErroneous = true;
1003 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001004 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001005 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001006
John McCalld3dfbd62010-05-18 03:19:21 +00001007 // Complain if we have a constant condition and we didn't find a match.
1008 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1009 // TODO: it would be nice if we printed enums as enums, chars as
1010 // chars, etc.
1011 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1012 << ConstantCondValue.toString(10)
1013 << CondExpr->getSourceRange();
1014 }
1015
1016 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001017 // values. We only issue a warning if there is not 'default:', but
1018 // we still do the analysis to preserve this information in the AST
1019 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001020 //
Chris Lattner51679082010-09-16 17:09:42 +00001021 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001022
Douglas Gregorbd6839732010-02-08 22:24:16 +00001023 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001024 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001025 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001026 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +00001027 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001028 EnumValsTy EnumVals;
1029
John McCalld3dfbd62010-05-18 03:19:21 +00001030 // Gather all enum values, set their type and sort them,
1031 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001032 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001033 llvm::APSInt Val = EDI->getInitVal();
1034 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001035 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001036 }
1037 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +00001038 EnumValsTy::iterator EIend =
1039 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001040
1041 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001042 EnumValsTy::const_iterator EI = EnumVals.begin();
1043 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1044 CI != CaseVals.end(); CI++) {
1045 while (EI != EIend && EI->first < CI->first)
1046 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001047 if (EI == EIend || EI->first > CI->first) {
1048 Expr *CaseExpr = CI->second->getLHS();
1049 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1050 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1051 << CondTypeBeforePromotion;
1052 }
David Blaikiee476f972012-01-22 02:31:55 +00001053 }
1054 // See which of case ranges aren't in enum
1055 EI = EnumVals.begin();
1056 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1057 RI != CaseRanges.end() && EI != EIend; RI++) {
1058 while (EI != EIend && EI->first < RI->first)
1059 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001060
David Blaikiee476f972012-01-22 02:31:55 +00001061 if (EI == EIend || EI->first != RI->first) {
Dmitri Gribenko58683752013-12-05 22:52:07 +00001062 Expr *CaseExpr = RI->second->getLHS();
1063 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1064 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1065 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +00001066 }
David Blaikiee476f972012-01-22 02:31:55 +00001067
Chad Rosier02a84392012-08-10 17:56:09 +00001068 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001069 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1070 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1071 while (EI != EIend && EI->first < Hi)
1072 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001073 if (EI == EIend || EI->first != Hi) {
1074 Expr *CaseExpr = RI->second->getRHS();
1075 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1076 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1077 << CondTypeBeforePromotion;
1078 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Ted Kremenekc42f3452010-09-09 00:05:53 +00001081 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +00001082 CaseValsTy::const_iterator CI = CaseVals.begin();
1083 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001084 bool hasCasesNotInSwitch = false;
1085
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001086 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087
David Blaikiee476f972012-01-22 02:31:55 +00001088 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001089 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001090 while (CI != CaseVals.end() && CI->first < EI->first)
1091 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001092
Douglas Gregorbd6839732010-02-08 22:24:16 +00001093 if (CI != CaseVals.end() && CI->first == EI->first)
1094 continue;
1095
Ted Kremenekc42f3452010-09-09 00:05:53 +00001096 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001097 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001098 llvm::APSInt Hi =
1099 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001100 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001101 if (EI->first <= Hi)
1102 break;
1103 }
1104
Ted Kremenekc42f3452010-09-09 00:05:53 +00001105 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001106 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001107 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001108 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
David Blaikie60ac6382012-01-23 04:46:12 +00001111 if (TheDefaultStmt && UnhandledNames.empty())
1112 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001113
Chris Lattner51679082010-09-16 17:09:42 +00001114 // Produce a nice diagnostic if multiple values aren't handled.
1115 switch (UnhandledNames.size()) {
1116 case 0: break;
1117 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001118 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001119 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001120 << UnhandledNames[0];
1121 break;
1122 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001123 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001124 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001125 << UnhandledNames[0] << UnhandledNames[1];
1126 break;
1127 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001128 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1129 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001130 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1131 break;
1132 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001133 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1134 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001135 << (unsigned)UnhandledNames.size()
1136 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1137 break;
1138 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001139
1140 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001141 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001142 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001143 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001144
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001145 if (BodyStmt)
1146 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1147 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001148
Mike Stump87c57ac2009-05-16 07:39:55 +00001149 // FIXME: If the case list was broken is some way, we don't have a good system
1150 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001151 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001152 return StmtError();
1153
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001154 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001155}
1156
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001157void
1158Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1159 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001160 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001161 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001162
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001163 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001164 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001165 SrcType->isIntegerType()) {
1166 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1167 SrcExpr->isIntegerConstantExpr(Context)) {
1168 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001169 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001170 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1171
1172 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001173 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001174 const EnumDecl *ED = ET->getDecl();
Joey Gouly1ba27332013-06-06 13:48:00 +00001175 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1176 EnumValsTy;
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001177 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001178
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001179 // Gather all enum values, set their type and sort them,
1180 // allowing easier comparison with rhs constant.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001181 for (auto *EDI : ED->enumerators()) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001182 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly1ba27332013-06-06 13:48:00 +00001183 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001184 EnumVals.push_back(std::make_pair(Val, EDI));
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001185 }
1186 if (EnumVals.empty())
1187 return;
1188 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1189 EnumValsTy::iterator EIend =
Joey Gouly1ba27332013-06-06 13:48:00 +00001190 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001191
Joey Gouly1ba27332013-06-06 13:48:00 +00001192 // See which values aren't in the enum.
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001193 EnumValsTy::const_iterator EI = EnumVals.begin();
1194 while (EI != EIend && EI->first < RhsVal)
1195 EI++;
1196 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly1ba27332013-06-06 13:48:00 +00001197 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001198 << DstType.getUnqualifiedType();
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001199 }
1200 }
1201 }
1202}
1203
John McCalldadc5752010-08-24 06:29:42 +00001204StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001206 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001207 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208
Craig Topperc3ec1492014-05-26 06:22:03 +00001209 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001210 if (CondVar) {
1211 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001212 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001213 if (CondResult.isInvalid())
1214 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001215 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001216 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001217 if (!ConditionExpr)
1218 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001219 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001220
John McCallb268a282010-08-23 23:25:46 +00001221 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001223 if (isa<NullStmt>(Body))
1224 getCurCompoundScope().setHasEmptyLoopBodies();
1225
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001226 return new (Context)
1227 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001228}
1229
John McCalldadc5752010-08-24 06:29:42 +00001230StmtResult
John McCallb268a282010-08-23 23:25:46 +00001231Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001232 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001233 Expr *Cond, SourceLocation CondRParen) {
1234 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001235
Serge Pavlov09f99242014-01-23 15:05:00 +00001236 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001237 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001238 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001239 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001240 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001241
Richard Smith945f8d32013-01-14 22:39:08 +00001242 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001243 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001244 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001245 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001246
John McCallb268a282010-08-23 23:25:46 +00001247 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001248
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001249 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001250}
1251
Richard Trieu451a5db2012-04-30 18:01:30 +00001252namespace {
1253 // This visitor will traverse a conditional statement and store all
1254 // the evaluated decls into a vector. Simple is set to true if none
1255 // of the excluded constructs are used.
1256 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1257 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001258 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001259 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001260 public:
1261 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001262
Richard Trieu9d228802013-05-31 22:46:45 +00001263 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001264 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001265 Inherited(S.Context),
1266 Decls(Decls),
1267 Ranges(Ranges),
1268 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001269
Richard Trieu9d228802013-05-31 22:46:45 +00001270 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001271
Richard Trieu9d228802013-05-31 22:46:45 +00001272 // Replaces the method in EvaluatedExprVisitor.
1273 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001274 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001275 }
1276
1277 // Any Stmt not whitelisted will cause the condition to be marked complex.
1278 void VisitStmt(Stmt *S) {
1279 Simple = false;
1280 }
1281
1282 void VisitBinaryOperator(BinaryOperator *E) {
1283 Visit(E->getLHS());
1284 Visit(E->getRHS());
1285 }
1286
1287 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001288 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001289 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001290
Richard Trieu9d228802013-05-31 22:46:45 +00001291 void VisitUnaryOperator(UnaryOperator *E) {
1292 // Skip checking conditionals with derefernces.
1293 if (E->getOpcode() == UO_Deref)
1294 Simple = false;
1295 else
1296 Visit(E->getSubExpr());
1297 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001298
Richard Trieu9d228802013-05-31 22:46:45 +00001299 void VisitConditionalOperator(ConditionalOperator *E) {
1300 Visit(E->getCond());
1301 Visit(E->getTrueExpr());
1302 Visit(E->getFalseExpr());
1303 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001304
Richard Trieu9d228802013-05-31 22:46:45 +00001305 void VisitParenExpr(ParenExpr *E) {
1306 Visit(E->getSubExpr());
1307 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001308
Richard Trieu9d228802013-05-31 22:46:45 +00001309 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1310 Visit(E->getOpaqueValue()->getSourceExpr());
1311 Visit(E->getFalseExpr());
1312 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001313
Richard Trieu9d228802013-05-31 22:46:45 +00001314 void VisitIntegerLiteral(IntegerLiteral *E) { }
1315 void VisitFloatingLiteral(FloatingLiteral *E) { }
1316 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1317 void VisitCharacterLiteral(CharacterLiteral *E) { }
1318 void VisitGNUNullExpr(GNUNullExpr *E) { }
1319 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001320
Richard Trieu9d228802013-05-31 22:46:45 +00001321 void VisitDeclRefExpr(DeclRefExpr *E) {
1322 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1323 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001324
Richard Trieu9d228802013-05-31 22:46:45 +00001325 Ranges.push_back(E->getSourceRange());
1326
1327 Decls.insert(VD);
1328 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001329
1330 }; // end class DeclExtractor
1331
1332 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001333 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001334 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1335 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1336 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001337
Richard Trieu9d228802013-05-31 22:46:45 +00001338 public:
1339 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001340
Richard Trieu9d228802013-05-31 22:46:45 +00001341 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1342 Stmt *Statement) :
1343 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1344 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001345
Richard Trieu9d228802013-05-31 22:46:45 +00001346 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001347 }
1348
Richard Trieu9d228802013-05-31 22:46:45 +00001349 void VisitReturnStmt(ReturnStmt *S) {
1350 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001351 }
1352
Richard Trieu9d228802013-05-31 22:46:45 +00001353 void VisitBreakStmt(BreakStmt *S) {
1354 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001355 }
1356
Richard Trieu9d228802013-05-31 22:46:45 +00001357 void VisitGotoStmt(GotoStmt *S) {
1358 FoundDecl = true;
1359 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001360
Richard Trieu9d228802013-05-31 22:46:45 +00001361 void VisitCastExpr(CastExpr *E) {
1362 if (E->getCastKind() == CK_LValueToRValue)
1363 CheckLValueToRValueCast(E->getSubExpr());
1364 else
1365 Visit(E->getSubExpr());
1366 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001367
Richard Trieu9d228802013-05-31 22:46:45 +00001368 void CheckLValueToRValueCast(Expr *E) {
1369 E = E->IgnoreParenImpCasts();
1370
1371 if (isa<DeclRefExpr>(E)) {
1372 return;
1373 }
1374
1375 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1376 Visit(CO->getCond());
1377 CheckLValueToRValueCast(CO->getTrueExpr());
1378 CheckLValueToRValueCast(CO->getFalseExpr());
1379 return;
1380 }
1381
1382 if (BinaryConditionalOperator *BCO =
1383 dyn_cast<BinaryConditionalOperator>(E)) {
1384 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1385 CheckLValueToRValueCast(BCO->getFalseExpr());
1386 return;
1387 }
1388
1389 Visit(E);
1390 }
1391
1392 void VisitDeclRefExpr(DeclRefExpr *E) {
1393 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1394 if (Decls.count(VD))
1395 FoundDecl = true;
1396 }
1397
1398 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001399
1400 }; // end class DeclMatcher
1401
1402 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1403 Expr *Third, Stmt *Body) {
1404 // Condition is empty
1405 if (!Second) return;
1406
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001407 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1408 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001409 return;
1410
1411 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1412 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001413 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001414 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001415 DE.Visit(Second);
1416
1417 // Don't analyze complex conditionals.
1418 if (!DE.isSimple()) return;
1419
1420 // No decls found.
1421 if (Decls.size() == 0) return;
1422
Richard Trieu0030f1d2012-05-04 03:01:54 +00001423 // Don't warn on volatile, static, or global variables.
Richard Trieu451a5db2012-04-30 18:01:30 +00001424 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1425 E = Decls.end();
1426 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001427 if ((*I)->getType().isVolatileQualified() ||
1428 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001429
1430 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1431 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1432 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1433 return;
1434
1435 // Load decl names into diagnostic.
1436 if (Decls.size() > 4)
1437 PDiag << 0;
1438 else {
1439 PDiag << Decls.size();
1440 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1441 E = Decls.end();
1442 I != E; ++I)
1443 PDiag << (*I)->getDeclName();
1444 }
1445
1446 // Load SourceRanges into diagnostic if there is room.
1447 // Otherwise, load the SourceRange of the conditional expression.
1448 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001449 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001450 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001451 I != E; ++I)
1452 PDiag << *I;
1453 else
1454 PDiag << Second->getSourceRange();
1455
1456 S.Diag(Ranges.begin()->getBegin(), PDiag);
1457 }
1458
Richard Trieu4e7c9622013-08-06 21:31:54 +00001459 // If Statement is an incemement or decrement, return true and sets the
1460 // variables Increment and DRE.
1461 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1462 DeclRefExpr *&DRE) {
1463 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1464 switch (UO->getOpcode()) {
1465 default: return false;
1466 case UO_PostInc:
1467 case UO_PreInc:
1468 Increment = true;
1469 break;
1470 case UO_PostDec:
1471 case UO_PreDec:
1472 Increment = false;
1473 break;
1474 }
1475 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1476 return DRE;
1477 }
1478
1479 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1480 FunctionDecl *FD = Call->getDirectCallee();
1481 if (!FD || !FD->isOverloadedOperator()) return false;
1482 switch (FD->getOverloadedOperator()) {
1483 default: return false;
1484 case OO_PlusPlus:
1485 Increment = true;
1486 break;
1487 case OO_MinusMinus:
1488 Increment = false;
1489 break;
1490 }
1491 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1492 return DRE;
1493 }
1494
1495 return false;
1496 }
1497
Serge Pavlov09f99242014-01-23 15:05:00 +00001498 // A visitor to determine if a continue or break statement is a
1499 // subexpression.
1500 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1501 SourceLocation BreakLoc;
1502 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001503 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001504 BreakContinueFinder(Sema &S, Stmt* Body) :
1505 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001506 Visit(Body);
1507 }
1508
Serge Pavlov09f99242014-01-23 15:05:00 +00001509 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001510
1511 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001512 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001513 }
1514
Serge Pavlov09f99242014-01-23 15:05:00 +00001515 void VisitBreakStmt(BreakStmt* E) {
1516 BreakLoc = E->getBreakLoc();
1517 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001518
Serge Pavlov09f99242014-01-23 15:05:00 +00001519 bool ContinueFound() { return ContinueLoc.isValid(); }
1520 bool BreakFound() { return BreakLoc.isValid(); }
1521 SourceLocation GetContinueLoc() { return ContinueLoc; }
1522 SourceLocation GetBreakLoc() { return BreakLoc; }
1523
1524 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001525
1526 // Emit a warning when a loop increment/decrement appears twice per loop
1527 // iteration. The conditions which trigger this warning are:
1528 // 1) The last statement in the loop body and the third expression in the
1529 // for loop are both increment or both decrement of the same variable
1530 // 2) No continue statements in the loop body.
1531 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1532 // Return when there is nothing to check.
1533 if (!Body || !Third) return;
1534
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001535 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1536 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001537 return;
1538
1539 // Get the last statement from the loop body.
1540 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1541 if (!CS || CS->body_empty()) return;
1542 Stmt *LastStmt = CS->body_back();
1543 if (!LastStmt) return;
1544
1545 bool LoopIncrement, LastIncrement;
1546 DeclRefExpr *LoopDRE, *LastDRE;
1547
1548 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1549 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1550
1551 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001552 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001553 if (LoopIncrement != LastIncrement ||
1554 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1555
Serge Pavlov09f99242014-01-23 15:05:00 +00001556 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001557
1558 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1559 << LastDRE->getDecl() << LastIncrement;
1560 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1561 << LoopIncrement;
1562 }
1563
Richard Trieu451a5db2012-04-30 18:01:30 +00001564} // end namespace
1565
Serge Pavlov09f99242014-01-23 15:05:00 +00001566
1567void Sema::CheckBreakContinueBinding(Expr *E) {
1568 if (!E || getLangOpts().CPlusPlus)
1569 return;
1570 BreakContinueFinder BCFinder(*this, E);
1571 Scope *BreakParent = CurScope->getBreakParent();
1572 if (BCFinder.BreakFound() && BreakParent) {
1573 if (BreakParent->getFlags() & Scope::SwitchScope) {
1574 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1575 } else {
1576 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1577 << "break";
1578 }
1579 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1580 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1581 << "continue";
1582 }
1583}
1584
John McCalldadc5752010-08-24 06:29:42 +00001585StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001586Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001587 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001588 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001589 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001590 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001591 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001592 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1593 // declare identifiers for objects having storage class 'auto' or
1594 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001595 for (auto *DI : DS->decls()) {
1596 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001597 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001598 VD = nullptr;
1599 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001600 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1601 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001602 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001603 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001604 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001605 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001606
Serge Pavlov09f99242014-01-23 15:05:00 +00001607 CheckBreakContinueBinding(second.get());
1608 CheckBreakContinueBinding(third.get());
1609
Richard Trieu451a5db2012-04-30 18:01:30 +00001610 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001611 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001612
John McCalldadc5752010-08-24 06:29:42 +00001613 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001614 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001615 if (secondVar) {
1616 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001617 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001618 if (SecondResult.isInvalid())
1619 return StmtError();
1620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001622 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623
Anders Carlsson1682af52009-08-01 01:39:59 +00001624 DiagnoseUnusedExprResult(First);
1625 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001626 DiagnoseUnusedExprResult(Body);
1627
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001628 if (isa<NullStmt>(Body))
1629 getCurCompoundScope().setHasEmptyLoopBodies();
1630
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001631 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1632 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001633}
1634
John McCall34376a62010-12-04 03:47:34 +00001635/// In an Objective C collection iteration statement:
1636/// for (x in y)
1637/// x can be an arbitrary l-value expression. Bind it up as a
1638/// full-expression.
1639StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001640 // Reduce placeholder expressions here. Note that this rejects the
1641 // use of pseudo-object l-values in this position.
1642 ExprResult result = CheckPlaceholderExpr(E);
1643 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001644 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001645
Richard Smith945f8d32013-01-14 22:39:08 +00001646 ExprResult FullExpr = ActOnFinishFullExpr(E);
1647 if (FullExpr.isInvalid())
1648 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001649 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001650}
1651
John McCall53848232011-07-27 01:07:15 +00001652ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001653Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1654 if (!collection)
1655 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001656
John McCall53848232011-07-27 01:07:15 +00001657 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001658 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001659
1660 // Perform normal l-value conversion.
1661 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1662 if (result.isInvalid())
1663 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001664 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001665
1666 // The operand needs to have object-pointer type.
1667 // TODO: should we do a contextual conversion?
1668 const ObjCObjectPointerType *pointerType =
1669 collection->getType()->getAs<ObjCObjectPointerType>();
1670 if (!pointerType)
1671 return Diag(forLoc, diag::err_collection_expr_type)
1672 << collection->getType() << collection->getSourceRange();
1673
1674 // Check that the operand provides
1675 // - countByEnumeratingWithState:objects:count:
1676 const ObjCObjectType *objectType = pointerType->getObjectType();
1677 ObjCInterfaceDecl *iface = objectType->getInterface();
1678
1679 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001680 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001681 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001682 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001683 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001684 ? diag::err_arc_collection_forward
1685 : 0,
1686 collection)) {
John McCall53848232011-07-27 01:07:15 +00001687 // Otherwise, if we have any useful type information, check that
1688 // the type declares the appropriate method.
1689 } else if (iface || !objectType->qual_empty()) {
1690 IdentifierInfo *selectorIdents[] = {
1691 &Context.Idents.get("countByEnumeratingWithState"),
1692 &Context.Idents.get("objects"),
1693 &Context.Idents.get("count")
1694 };
1695 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1696
Craig Topperc3ec1492014-05-26 06:22:03 +00001697 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001698
1699 // If there's an interface, look in both the public and private APIs.
1700 if (iface) {
1701 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001702 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001703 }
1704
1705 // Also check protocol qualifiers.
1706 if (!method)
1707 method = LookupMethodInQualifiedType(selector, pointerType,
1708 /*instance*/ true);
1709
1710 // If we didn't find it anywhere, give up.
1711 if (!method) {
1712 Diag(forLoc, diag::warn_collection_expr_type)
1713 << collection->getType() << selector << collection->getSourceRange();
1714 }
1715
1716 // TODO: check for an incompatible signature?
1717 }
1718
1719 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001720 return collection;
John McCall53848232011-07-27 01:07:15 +00001721}
1722
John McCalldadc5752010-08-24 06:29:42 +00001723StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001724Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001725 Stmt *First, Expr *collection,
1726 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001727
1728 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001729 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001730
Fariborz Jahanian93977672008-01-10 20:33:58 +00001731 if (First) {
1732 QualType FirstType;
1733 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001734 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001735 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1736 diag::err_toomany_element_decls));
1737
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001738 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1739 if (!D || D->isInvalidDecl())
1740 return StmtError();
1741
John McCall31168b02011-06-15 23:02:42 +00001742 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001743 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1744 // declare identifiers for objects having storage class 'auto' or
1745 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001746 if (!D->hasLocalStorage())
1747 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001748 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001749
1750 // If the type contained 'auto', deduce the 'auto' to 'id'.
1751 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001752 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1753 VK_RValue);
1754 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001755 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1756 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001757 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001758 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001759 D->setInvalidDecl();
1760 return StmtError();
1761 }
1762
Richard Smith061f1e22013-04-30 21:23:01 +00001763 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001764
1765 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001766 SourceLocation Loc =
1767 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001768 Diag(Loc, diag::warn_auto_var_is_id)
1769 << D->getDeclName();
1770 }
1771 }
1772
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001773 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001774 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001775 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001776 return StmtError(Diag(First->getLocStart(),
1777 diag::err_selector_element_not_lvalue)
1778 << First->getSourceRange());
1779
Mike Stump11289f42009-09-09 15:08:12 +00001780 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001781 if (FirstType.isConstQualified())
1782 Diag(ForLoc, diag::err_selector_element_const_type)
1783 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001784 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001785 if (!FirstType->isDependentType() &&
1786 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001787 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001788 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1789 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001790 }
Chad Rosier02a84392012-08-10 17:56:09 +00001791
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001792 if (CollectionExprResult.isInvalid())
1793 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001794
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001795 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001796 if (CollectionExprResult.isInvalid())
1797 return StmtError();
1798
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001799 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1800 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001801}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001802
Richard Smith02e85f32011-04-14 22:09:26 +00001803/// Finish building a variable declaration for a for-range statement.
1804/// \return true if an error occurs.
1805static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001806 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001807 // Deduce the type for the iterator variable now rather than leaving it to
1808 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001809 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001810 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001811 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001812 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001813 SemaRef.Diag(Loc, DiagID) << Init->getType();
1814 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001815 Decl->setInvalidDecl();
1816 return true;
1817 }
Richard Smith061f1e22013-04-30 21:23:01 +00001818 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001819
John McCall31168b02011-06-15 23:02:42 +00001820 // In ARC, infer lifetime.
1821 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1822 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001823 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001824 SemaRef.inferObjCARCLifetime(Decl))
1825 Decl->setInvalidDecl();
1826
Richard Smith02e85f32011-04-14 22:09:26 +00001827 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1828 /*TypeMayContainAuto=*/false);
1829 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001830 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001831 return false;
1832}
1833
Sam Panzer0f384432012-08-21 00:52:01 +00001834namespace {
1835
Richard Smith02e85f32011-04-14 22:09:26 +00001836/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001837/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001838/// nor from the diagnostics produced when analysing the implicit expressions
1839/// required in a for-range statement.
1840void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001841 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001842 CallExpr *CE = dyn_cast<CallExpr>(E);
1843 if (!CE)
1844 return;
1845 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1846 if (!D)
1847 return;
1848 SourceLocation Loc = D->getLocation();
1849
1850 std::string Description;
1851 bool IsTemplate = false;
1852 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1853 Description = SemaRef.getTemplateArgumentBindingsText(
1854 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1855 IsTemplate = true;
1856 }
1857
1858 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1859 << BEF << IsTemplate << Description << E->getType();
1860}
1861
Sam Panzer0f384432012-08-21 00:52:01 +00001862/// Build a variable declaration for a for-range statement.
1863VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1864 QualType Type, const char *Name) {
1865 DeclContext *DC = SemaRef.CurContext;
1866 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1867 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1868 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001869 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001870 Decl->setImplicit();
1871 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001872}
1873
1874}
1875
Fariborz Jahanian00213472012-07-06 19:04:04 +00001876static bool ObjCEnumerationCollection(Expr *Collection) {
1877 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001878 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001879}
1880
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001881/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001882///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001883/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001884/// A range-based for statement is equivalent to
1885///
1886/// {
1887/// auto && __range = range-init;
1888/// for ( auto __begin = begin-expr,
1889/// __end = end-expr;
1890/// __begin != __end;
1891/// ++__begin ) {
1892/// for-range-declaration = *__begin;
1893/// statement
1894/// }
1895/// }
1896///
1897/// The body of the loop is not available yet, since it cannot be analysed until
1898/// we have determined the type of the for-range-declaration.
1899StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001900Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001901 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001902 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001903 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001904 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001905
Richard Smith3249fed2013-08-21 01:40:36 +00001906 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001907 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001908
1909 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1910 assert(DS && "first part of for range not a decl stmt");
1911
1912 if (!DS->isSingleDecl()) {
1913 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1914 return StmtError();
1915 }
Richard Smith02e85f32011-04-14 22:09:26 +00001916
Richard Smith3249fed2013-08-21 01:40:36 +00001917 Decl *LoopVar = DS->getSingleDecl();
1918 if (LoopVar->isInvalidDecl() || !Range ||
1919 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1920 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001921 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001922 }
Richard Smith02e85f32011-04-14 22:09:26 +00001923
1924 // Build auto && __range = range-init
1925 SourceLocation RangeLoc = Range->getLocStart();
1926 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1927 Context.getAutoRRefDeductType(),
1928 "__range");
1929 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001930 diag::err_for_range_deduction_failure)) {
1931 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001932 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001933 }
Richard Smith02e85f32011-04-14 22:09:26 +00001934
1935 // Claim the type doesn't contain auto: we've already done the checking.
1936 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001937 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001938 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001939 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001940 if (RangeDecl.isInvalid()) {
1941 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001942 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001943 }
Richard Smith02e85f32011-04-14 22:09:26 +00001944
1945 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001946 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1947 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001948}
1949
1950/// \brief Create the initialization, compare, and increment steps for
1951/// the range-based for loop expression.
1952/// This function does not handle array-based for loops,
1953/// which are created in Sema::BuildCXXForRangeStmt.
1954///
1955/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1956/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1957/// CandidateSet and BEF are set and some non-success value is returned on
1958/// failure.
1959static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1960 Expr *BeginRange, Expr *EndRange,
1961 QualType RangeType,
1962 VarDecl *BeginVar,
1963 VarDecl *EndVar,
1964 SourceLocation ColonLoc,
1965 OverloadCandidateSet *CandidateSet,
1966 ExprResult *BeginExpr,
1967 ExprResult *EndExpr,
1968 Sema::BeginEndFunction *BEF) {
1969 DeclarationNameInfo BeginNameInfo(
1970 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1971 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1972 ColonLoc);
1973
1974 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1975 Sema::LookupMemberName);
1976 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1977
1978 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1979 // - if _RangeT is a class type, the unqualified-ids begin and end are
1980 // looked up in the scope of class _RangeT as if by class member access
1981 // lookup (3.4.5), and if either (or both) finds at least one
1982 // declaration, begin-expr and end-expr are __range.begin() and
1983 // __range.end(), respectively;
1984 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1985 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1986
1987 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1988 SourceLocation RangeLoc = BeginVar->getLocation();
1989 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1990
1991 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1992 << RangeLoc << BeginRange->getType() << *BEF;
1993 return Sema::FRS_DiagnosticIssued;
1994 }
1995 } else {
1996 // - otherwise, begin-expr and end-expr are begin(__range) and
1997 // end(__range), respectively, where begin and end are looked up with
1998 // argument-dependent lookup (3.4.2). For the purposes of this name
1999 // lookup, namespace std is an associated namespace.
2000
2001 }
2002
2003 *BEF = Sema::BEF_begin;
2004 Sema::ForRangeStatus RangeStatus =
2005 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2006 Sema::BEF_begin, BeginNameInfo,
2007 BeginMemberLookup, CandidateSet,
2008 BeginRange, BeginExpr);
2009
2010 if (RangeStatus != Sema::FRS_Success)
2011 return RangeStatus;
2012 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2013 diag::err_for_range_iter_deduction_failure)) {
2014 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2015 return Sema::FRS_DiagnosticIssued;
2016 }
2017
2018 *BEF = Sema::BEF_end;
2019 RangeStatus =
2020 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2021 Sema::BEF_end, EndNameInfo,
2022 EndMemberLookup, CandidateSet,
2023 EndRange, EndExpr);
2024 if (RangeStatus != Sema::FRS_Success)
2025 return RangeStatus;
2026 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2027 diag::err_for_range_iter_deduction_failure)) {
2028 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2029 return Sema::FRS_DiagnosticIssued;
2030 }
2031 return Sema::FRS_Success;
2032}
2033
2034/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002035/// If the attempt fails, this function will return a valid, null StmtResult
2036/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002037static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2038 SourceLocation ForLoc,
2039 Stmt *LoopVarDecl,
2040 SourceLocation ColonLoc,
2041 Expr *Range,
2042 SourceLocation RangeLoc,
2043 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002044 // Determine whether we can rebuild the for-range statement with a
2045 // dereferenced range expression.
2046 ExprResult AdjustedRange;
2047 {
2048 Sema::SFINAETrap Trap(SemaRef);
2049
2050 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2051 if (AdjustedRange.isInvalid())
2052 return StmtResult();
2053
2054 StmtResult SR =
2055 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2056 AdjustedRange.get(), RParenLoc,
2057 Sema::BFRK_Check);
2058 if (SR.isInvalid())
2059 return StmtResult();
2060 }
2061
2062 // The attempt to dereference worked well enough that it could produce a valid
2063 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2064 // case there are any other (non-fatal) problems with it.
2065 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2066 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2067 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2068 AdjustedRange.get(), RParenLoc,
2069 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002070}
2071
Richard Smith3249fed2013-08-21 01:40:36 +00002072namespace {
2073/// RAII object to automatically invalidate a declaration if an error occurs.
2074struct InvalidateOnErrorScope {
2075 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2076 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2077 ~InvalidateOnErrorScope() {
2078 if (Enabled && Trap.hasErrorOccurred())
2079 D->setInvalidDecl();
2080 }
2081
2082 DiagnosticErrorTrap Trap;
2083 Decl *D;
2084 bool Enabled;
2085};
2086}
2087
Richard Smitha05b3b52012-09-20 21:52:32 +00002088/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002089StmtResult
2090Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2091 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2092 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002093 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002094 Scope *S = getCurScope();
2095
2096 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2097 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2098 QualType RangeVarType = RangeVar->getType();
2099
2100 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2101 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2102
Richard Smith3249fed2013-08-21 01:40:36 +00002103 // If we hit any errors, mark the loop variable as invalid if its type
2104 // contains 'auto'.
2105 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2106 LoopVar->getType()->isUndeducedType());
2107
Richard Smith02e85f32011-04-14 22:09:26 +00002108 StmtResult BeginEndDecl = BeginEnd;
2109 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2110
Richard Smith27d807c2013-04-30 13:56:41 +00002111 if (RangeVarType->isDependentType()) {
2112 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002113 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002114
2115 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2116 // them in properly when we instantiate the loop.
2117 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2118 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2119 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002120 SourceLocation RangeLoc = RangeVar->getLocation();
2121
Ted Kremenekbed648e2011-10-10 22:36:28 +00002122 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2123
2124 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2125 VK_LValue, ColonLoc);
2126 if (BeginRangeRef.isInvalid())
2127 return StmtError();
2128
2129 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2130 VK_LValue, ColonLoc);
2131 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002132 return StmtError();
2133
2134 QualType AutoType = Context.getAutoDeductType();
2135 Expr *Range = RangeVar->getInit();
2136 if (!Range)
2137 return StmtError();
2138 QualType RangeType = Range->getType();
2139
2140 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002141 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002142 return StmtError();
2143
2144 // Build auto __begin = begin-expr, __end = end-expr.
2145 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2146 "__begin");
2147 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2148 "__end");
2149
2150 // Build begin-expr and end-expr and attach to __begin and __end variables.
2151 ExprResult BeginExpr, EndExpr;
2152 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2153 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2154 // __range + __bound, respectively, where __bound is the array bound. If
2155 // _RangeT is an array of unknown size or an array of incomplete type,
2156 // the program is ill-formed;
2157
2158 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002159 BeginExpr = BeginRangeRef;
2160 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002161 diag::err_for_range_iter_deduction_failure)) {
2162 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2163 return StmtError();
2164 }
2165
2166 // Find the array bound.
2167 ExprResult BoundExpr;
2168 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002169 BoundExpr = IntegerLiteral::Create(
2170 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002171 else if (const VariableArrayType *VAT =
2172 dyn_cast<VariableArrayType>(UnqAT))
2173 BoundExpr = VAT->getSizeExpr();
2174 else {
2175 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2176 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002177 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002178 }
2179
2180 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002181 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002182 BoundExpr.get());
2183 if (EndExpr.isInvalid())
2184 return StmtError();
2185 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2186 diag::err_for_range_iter_deduction_failure)) {
2187 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2188 return StmtError();
2189 }
2190 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002191 OverloadCandidateSet CandidateSet(RangeLoc,
2192 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002193 Sema::BeginEndFunction BEFFailure;
2194 ForRangeStatus RangeStatus =
2195 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2196 EndRangeRef.get(), RangeType,
2197 BeginVar, EndVar, ColonLoc, &CandidateSet,
2198 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002199
Richard Smitha05b3b52012-09-20 21:52:32 +00002200 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002201 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002202 // If the range is being built from an array parameter, emit a
2203 // a diagnostic that it is being treated as a pointer.
2204 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2205 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2206 QualType ArrayTy = PVD->getOriginalType();
2207 QualType PointerTy = PVD->getType();
2208 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2209 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2210 << RangeLoc << PVD << ArrayTy << PointerTy;
2211 Diag(PVD->getLocation(), diag::note_declared_at);
2212 return StmtError();
2213 }
2214 }
2215 }
2216
2217 // If building the range failed, try dereferencing the range expression
2218 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002219 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2220 LoopVarDecl, ColonLoc,
2221 Range, RangeLoc,
2222 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002223 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002224 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002225 }
2226
Sam Panzer0f384432012-08-21 00:52:01 +00002227 // Otherwise, emit diagnostics if we haven't already.
2228 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002229 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002230 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2231 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002232 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002233 }
2234 // Return an error if no fix was discovered.
2235 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002236 return StmtError();
2237 }
2238
Sam Panzer0f384432012-08-21 00:52:01 +00002239 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2240 "invalid range expression in for loop");
2241
2242 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002243 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2244 if (!Context.hasSameType(BeginType, EndType)) {
2245 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2246 << BeginType << EndType;
2247 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2248 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2249 }
2250
2251 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2252 // Claim the type doesn't contain auto: we've already done the checking.
2253 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002254 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002255 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002256 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2257
Ted Kremenekbed648e2011-10-10 22:36:28 +00002258 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2259 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002260 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002261 if (BeginRef.isInvalid())
2262 return StmtError();
2263
Richard Smith02e85f32011-04-14 22:09:26 +00002264 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2265 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002266 if (EndRef.isInvalid())
2267 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002268
2269 // Build and check __begin != __end expression.
2270 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2271 BeginRef.get(), EndRef.get());
2272 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2273 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2274 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002275 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2276 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002277 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2278 if (!Context.hasSameType(BeginType, EndType))
2279 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2280 return StmtError();
2281 }
2282
2283 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002284 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2285 VK_LValue, ColonLoc);
2286 if (BeginRef.isInvalid())
2287 return StmtError();
2288
Richard Smith02e85f32011-04-14 22:09:26 +00002289 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2290 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2291 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002292 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2293 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002294 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2295 return StmtError();
2296 }
2297
2298 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002299 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2300 VK_LValue, ColonLoc);
2301 if (BeginRef.isInvalid())
2302 return StmtError();
2303
Richard Smith02e85f32011-04-14 22:09:26 +00002304 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2305 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002306 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2307 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002308 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2309 return StmtError();
2310 }
2311
Richard Smitha05b3b52012-09-20 21:52:32 +00002312 // Attach *__begin as initializer for VD. Don't touch it if we're just
2313 // trying to determine whether this would be a valid range.
2314 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002315 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2316 /*TypeMayContainAuto=*/true);
2317 if (LoopVar->isInvalidDecl())
2318 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2319 }
2320 }
2321
Richard Smitha05b3b52012-09-20 21:52:32 +00002322 // Don't bother to actually allocate the result if we're just trying to
2323 // determine whether it would be valid.
2324 if (Kind == BFRK_Check)
2325 return StmtResult();
2326
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002327 return new (Context) CXXForRangeStmt(
2328 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2329 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002330}
2331
Chad Rosier02a84392012-08-10 17:56:09 +00002332/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002333/// statement.
2334StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2335 if (!S || !B)
2336 return StmtError();
2337 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002338
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002339 ForStmt->setBody(B);
2340 return S;
2341}
2342
Richard Smith02e85f32011-04-14 22:09:26 +00002343/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2344/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2345/// body cannot be performed until after the type of the range variable is
2346/// determined.
2347StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2348 if (!S || !B)
2349 return StmtError();
2350
Fariborz Jahanian00213472012-07-06 19:04:04 +00002351 if (isa<ObjCForCollectionStmt>(S))
2352 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002353
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002354 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2355 ForStmt->setBody(B);
2356
2357 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2358 diag::warn_empty_range_based_for_body);
2359
Richard Smith02e85f32011-04-14 22:09:26 +00002360 return S;
2361}
2362
Chris Lattnercab02a62011-02-17 20:34:02 +00002363StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2364 SourceLocation LabelLoc,
2365 LabelDecl *TheDecl) {
2366 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002367 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002368 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002369}
Chris Lattner1c310502007-05-31 06:00:00 +00002370
John McCalldadc5752010-08-24 06:29:42 +00002371StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002372Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002373 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002374 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002375 if (!E->isTypeDependent()) {
2376 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002377 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002378 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002379 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002380 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2381 if (ExprRes.isInvalid())
2382 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002383 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002384 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002385 return StmtError();
2386 }
John McCalla95172b2010-08-01 00:26:45 +00002387
Richard Smith945f8d32013-01-14 22:39:08 +00002388 ExprResult ExprRes = ActOnFinishFullExpr(E);
2389 if (ExprRes.isInvalid())
2390 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002391 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002392
John McCallaab3e412010-08-25 08:40:02 +00002393 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002394
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002395 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002396}
2397
John McCalldadc5752010-08-24 06:29:42 +00002398StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002399Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002400 Scope *S = CurScope->getContinueParent();
2401 if (!S) {
2402 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002403 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002404 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002405
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002406 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002407}
2408
John McCalldadc5752010-08-24 06:29:42 +00002409StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002410Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002411 Scope *S = CurScope->getBreakParent();
2412 if (!S) {
2413 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002414 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002415 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002416 if (S->isOpenMPLoopScope())
2417 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2418 << "break");
Sebastian Redl573feed2009-01-18 13:19:59 +00002419
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002420 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002421}
2422
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002423/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002424/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002425///
Douglas Gregor5d369002011-01-21 18:05:27 +00002426/// \param ReturnType If we're determining the copy elision candidate for
2427/// a return statement, this is the return type of the function. If we're
2428/// determining the copy elision candidate for a throw expression, this will
2429/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002430///
Douglas Gregor5d369002011-01-21 18:05:27 +00002431/// \param E The expression being returned from the function or block, or
2432/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002433///
Douglas Gregor86394412011-05-20 15:00:53 +00002434/// \param AllowFunctionParameter Whether we allow function parameters to
2435/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2436/// we re-use this logic to determine whether we should try to move as part of
2437/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002438///
2439/// \returns The NRVO candidate variable, if the return statement may use the
2440/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002441VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2442 Expr *E,
2443 bool AllowFunctionParameter) {
2444 if (!getLangOpts().CPlusPlus)
2445 return nullptr;
2446
2447 // - in a return statement in a function [where] ...
2448 // ... the expression is the name of a non-volatile automatic object ...
2449 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2450 if (!DR || DR->refersToEnclosingLocal())
2451 return nullptr;
2452 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2453 if (!VD)
2454 return nullptr;
2455
2456 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2457 return VD;
2458 return nullptr;
2459}
2460
2461bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2462 bool AllowFunctionParameter) {
2463 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002464 // - in a return statement in a function with ...
2465 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002466 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002467 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002468 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002469 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002470 if (!VDType->isDependentType() &&
2471 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2472 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002474
John McCall03318c12011-11-11 03:57:31 +00002475 // ...object (other than a function or catch-clause parameter)...
2476 if (VD->getKind() != Decl::Var &&
2477 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002478 return false;
2479 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480
John McCall03318c12011-11-11 03:57:31 +00002481 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002482 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002483
2484 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002485 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002486
2487 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002488 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002489
2490 // Variables with higher required alignment than their type's ABI
2491 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002492 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002493 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002494 return false;
John McCall03318c12011-11-11 03:57:31 +00002495
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002496 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002497}
2498
Douglas Gregor626fbed2011-01-21 21:08:57 +00002499/// \brief Perform the initialization of a potentially-movable value, which
2500/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002501///
2502/// This routine implements C++0x [class.copy]p33, which attempts to treat
2503/// returned lvalues as rvalues in certain cases (to prefer move construction),
2504/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002505ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002506Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2507 const VarDecl *NRVOCandidate,
2508 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002509 Expr *Value,
2510 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002511 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002512 // When the criteria for elision of a copy operation are met or would
2513 // be met save for the fact that the source object is a function
2514 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002515 // overload resolution to select the constructor for the copy is first
2516 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002517 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002518 if (AllowNRVO &&
2519 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002520 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002521 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002522
Douglas Gregorf282a762011-01-21 19:38:21 +00002523 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002525 = InitializationKind::CreateCopy(Value->getLocStart(),
2526 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002527 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002528
2529 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002530 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002531 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002532 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002533 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002534 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2535 StepEnd = Seq.step_end();
2536 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002537 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002538 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
2540 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002541 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542
Douglas Gregorf282a762011-01-21 19:38:21 +00002543 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002544 = Constructor->getParamDecl(0)->getType()
2545 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002546
Douglas Gregorf282a762011-01-21 19:38:21 +00002547 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002549 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2550 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552
Douglas Gregorf282a762011-01-21 19:38:21 +00002553 // Promote "AsRvalue" to the heap, since we now need this
2554 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002555 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002556 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557
Douglas Gregorf282a762011-01-21 19:38:21 +00002558 // Complete type-checking the initialization of the return type
2559 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002560 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002561 }
2562 }
2563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002564
Douglas Gregorf282a762011-01-21 19:38:21 +00002565 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002566 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002567 // (again) now with the return value expression as written.
2568 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002569 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570
Douglas Gregorf282a762011-01-21 19:38:21 +00002571 return Res;
2572}
2573
Richard Smith4db51c22013-09-25 05:02:54 +00002574/// \brief Determine whether the declared return type of the specified function
2575/// contains 'auto'.
2576static bool hasDeducedReturnType(FunctionDecl *FD) {
2577 const FunctionProtoType *FPT =
2578 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002579 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002580}
2581
Eli Friedman34b49062012-01-26 03:00:14 +00002582/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2583/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002584///
John McCalldadc5752010-08-24 06:29:42 +00002585StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002586Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2587 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002588 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002589 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002590 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002591 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002592
Richard Smith4db51c22013-09-25 05:02:54 +00002593 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2594 // In C++1y, the return type may involve 'auto'.
2595 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2596 FunctionDecl *FD = CurLambda->CallOperator;
2597 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002598 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002599
2600 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2601 assert(AT && "lost auto type from lambda return type");
2602 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2603 FD->setInvalidDecl();
2604 return StmtError();
2605 }
Alp Toker314cc812014-01-25 16:55:45 +00002606 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002607 } else if (CurCap->HasImplicitReturnType) {
2608 // For blocks/lambdas with implicit return types, we check each return
2609 // statement individually, and deduce the common return type when the block
2610 // or lambda is completed.
2611 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002612 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002613 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2614 if (Result.isInvalid())
2615 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002616 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002617
Richard Smith4db51c22013-09-25 05:02:54 +00002618 if (!CurContext->isDependentContext())
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002619 FnRetType = RetValExp->getType();
Richard Smith4db51c22013-09-25 05:02:54 +00002620 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002621 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002622 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002623 if (RetValExp) {
2624 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2625 // initializer list, because it is not an expression (even
2626 // though we represent it as one). We still deduce 'void'.
2627 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2628 << RetValExp->getSourceRange();
2629 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002630
Jordan Rosed39e5f12012-07-02 21:19:23 +00002631 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002632 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002633
2634 // Although we'll properly infer the type of the block once it's completed,
2635 // make sure we provide a return type now for better error recovery.
2636 if (CurCap->ReturnType.isNull())
2637 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002638 }
Eli Friedman34b49062012-01-26 03:00:14 +00002639 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002640
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002641 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002642 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2643 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2644 return StmtError();
2645 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002646 } else if (CapturedRegionScopeInfo *CurRegion =
2647 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2648 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2649 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002650 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002651 assert(CurLambda && "unknown kind of captured scope");
2652 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2653 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002654 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2655 return StmtError();
2656 }
2657 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002658
Steve Naroffc540d662008-09-03 18:15:37 +00002659 // Otherwise, verify that this result type matches the previous one. We are
2660 // pickier with blocks than for normal functions because we don't have GCC
2661 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002662 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002663 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002664 // Delay processing for now. TODO: there are lots of dependent
2665 // types we can conclusively prove aren't void.
2666 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002667 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002668 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002669 (RetValExp->isTypeDependent() ||
2670 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002671 if (!getLangOpts().CPlusPlus &&
2672 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002673 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002674 else {
2675 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002676 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002677 }
Steve Naroffc540d662008-09-03 18:15:37 +00002678 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002679 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002680 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2681 } else if (!RetValExp->isTypeDependent()) {
2682 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002683
John McCall5500ef22011-08-17 22:09:46 +00002684 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2685 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2686 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002687
John McCall5500ef22011-08-17 22:09:46 +00002688 // In C++ the return statement is handled via a copy initialization.
2689 // the C version of which boils down to CheckSingleAssignmentConstraints.
2690 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2691 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2692 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002693 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002694 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2695 FnRetType, RetValExp);
2696 if (Res.isInvalid()) {
2697 // FIXME: Cleanup temporaries here, anyway?
2698 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002699 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002700 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002701 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002702 } else {
2703 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002704 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002705
John McCall75f92b52011-08-17 21:34:14 +00002706 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002707 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2708 if (ER.isInvalid())
2709 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002710 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002711 }
John McCall5500ef22011-08-17 22:09:46 +00002712 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2713 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002714
Jordan Rosed39e5f12012-07-02 21:19:23 +00002715 // If we need to check for the named return value optimization,
2716 // or if we need to infer the return type,
2717 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002718 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002719 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002720
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002721 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002722}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002723
Richard Smith2a7d4812013-05-04 07:00:32 +00002724/// Deduce the return type for a function from a returned expression, per
2725/// C++1y [dcl.spec.auto]p6.
2726bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2727 SourceLocation ReturnLoc,
2728 Expr *&RetExpr,
2729 AutoType *AT) {
2730 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00002731 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith2a7d4812013-05-04 07:00:32 +00002732 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002733
Richard Smithc58f38f2013-08-14 20:16:31 +00002734 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2735 // If the deduction is for a return statement and the initializer is
2736 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002737 Diag(RetExpr->getExprLoc(),
2738 getCurLambda() ? diag::err_lambda_return_init_list
2739 : diag::err_auto_fn_return_init_list)
2740 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002741 return true;
2742 }
2743
2744 if (FD->isDependentContext()) {
2745 // C++1y [dcl.spec.auto]p12:
2746 // Return type deduction [...] occurs when the definition is
2747 // instantiated even if the function body contains a return
2748 // statement with a non-type-dependent operand.
2749 assert(AT->isDeduced() && "should have deduced to dependent type");
2750 return false;
2751 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002752 // If the deduction is for a return statement and the initializer is
2753 // a braced-init-list, the program is ill-formed.
2754 if (isa<InitListExpr>(RetExpr)) {
2755 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2756 return true;
2757 }
2758
2759 // Otherwise, [...] deduce a value for U using the rules of template
2760 // argument deduction.
2761 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2762
2763 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2764 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2765 << OrigResultType.getType() << RetExpr->getType();
2766
2767 if (DAR != DAR_Succeeded)
2768 return true;
2769 } else {
2770 // In the case of a return with no operand, the initializer is considered
2771 // to be void().
2772 //
2773 // Deduction here can only succeed if the return type is exactly 'cv auto'
2774 // or 'decltype(auto)', so just check for that case directly.
2775 if (!OrigResultType.getType()->getAs<AutoType>()) {
2776 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2777 << OrigResultType.getType();
2778 return true;
2779 }
2780 // We always deduce U = void in this case.
2781 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2782 if (Deduced.isNull())
2783 return true;
2784 }
2785
2786 // If a function with a declared return type that contains a placeholder type
2787 // has multiple return statements, the return type is deduced for each return
2788 // statement. [...] if the type deduced is not the same in each deduction,
2789 // the program is ill-formed.
2790 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2791 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002792 if (!FD->isDependentContext() &&
2793 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002794 const LambdaScopeInfo *LambdaSI = getCurLambda();
2795 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2796 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2797 << NewAT->getDeducedType() << AT->getDeducedType()
2798 << true /*IsLambda*/;
2799 } else {
2800 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2801 << (AT->isDecltypeAuto() ? 1 : 0)
2802 << NewAT->getDeducedType() << AT->getDeducedType();
2803 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002804 return true;
2805 }
2806 } else if (!FD->isInvalidDecl()) {
2807 // Update all declarations of the function to have the deduced return type.
2808 Context.adjustDeducedFunctionResultType(FD, Deduced);
2809 }
2810
2811 return false;
2812}
2813
John McCalldadc5752010-08-24 06:29:42 +00002814StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002815Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2816 Scope *CurScope) {
2817 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2818 if (R.isInvalid()) {
2819 return R;
2820 }
2821
2822 if (VarDecl *VD =
2823 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2824 CurScope->addNRVOCandidate(VD);
2825 } else {
2826 CurScope->setNoNRVO();
2827 }
2828
2829 return R;
2830}
2831
2832StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002833 // Check for unexpanded parameter packs.
2834 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2835 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002836
Eli Friedman34b49062012-01-26 03:00:14 +00002837 if (isa<CapturingScopeInfo>(getCurFunction()))
2838 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002839
Chris Lattner79413952008-12-04 23:50:19 +00002840 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002841 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002842 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002843 bool isObjCMethod = false;
2844
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002845 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002846 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002847 if (FD->hasAttrs())
2848 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002849 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002850 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002851 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002852 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002853 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002854 isObjCMethod = true;
2855 if (MD->hasAttrs())
2856 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002857 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2858 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002859 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002860 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002861 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2862 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002863 }
2864 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002865 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002866
Richard Smith2a7d4812013-05-04 07:00:32 +00002867 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2868 // deduction.
Richard Smith2a7d4812013-05-04 07:00:32 +00002869 if (getLangOpts().CPlusPlus1y) {
2870 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2871 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002872 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002873 FD->setInvalidDecl();
2874 return StmtError();
2875 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002876 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002877 }
2878 }
2879 }
2880
Richard Smithc58f38f2013-08-14 20:16:31 +00002881 bool HasDependentReturnType = FnRetType->isDependentType();
2882
Craig Topperc3ec1492014-05-26 06:22:03 +00002883 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002884 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002885 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002886 if (isa<InitListExpr>(RetValExp)) {
2887 // We simply never allow init lists as the return value of void
2888 // functions. This is compatible because this was never allowed before,
2889 // so there's no legacy code to deal with.
2890 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2891 int FunctionKind = 0;
2892 if (isa<ObjCMethodDecl>(CurDecl))
2893 FunctionKind = 1;
2894 else if (isa<CXXConstructorDecl>(CurDecl))
2895 FunctionKind = 2;
2896 else if (isa<CXXDestructorDecl>(CurDecl))
2897 FunctionKind = 3;
2898
2899 Diag(ReturnLoc, diag::err_return_init_list)
2900 << CurDecl->getDeclName() << FunctionKind
2901 << RetValExp->getSourceRange();
2902
2903 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002904 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002905 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002906 // C99 6.8.6.4p1 (ext_ since GCC warns)
2907 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002908 if (RetValExp->getType()->isVoidType()) {
2909 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2910 if (isa<CXXConstructorDecl>(CurDecl) ||
2911 isa<CXXDestructorDecl>(CurDecl))
2912 D = diag::err_ctor_dtor_returns_void;
2913 else
2914 D = diag::ext_return_has_void_expr;
2915 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002916 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002917 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002918 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00002919 if (Result.isInvalid())
2920 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002921 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002922 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002923 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002924 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002925 // return of void in constructor/destructor is illegal in C++.
2926 if (D == diag::err_ctor_dtor_returns_void) {
2927 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2928 Diag(ReturnLoc, D)
2929 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
2930 << RetValExp->getSourceRange();
2931 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002932 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002933 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002934 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002935 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002936
2937 int FunctionKind = 0;
2938 if (isa<ObjCMethodDecl>(CurDecl))
2939 FunctionKind = 1;
2940 else if (isa<CXXConstructorDecl>(CurDecl))
2941 FunctionKind = 2;
2942 else if (isa<CXXDestructorDecl>(CurDecl))
2943 FunctionKind = 3;
2944
Nick Lewycky1be750a2011-06-01 07:44:31 +00002945 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002946 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002947 << RetValExp->getSourceRange();
2948 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002949 }
Mike Stump11289f42009-09-09 15:08:12 +00002950
Sebastian Redleef474c2012-02-22 10:50:08 +00002951 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002952 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2953 if (ER.isInvalid())
2954 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002955 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00002956 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958
Craig Topperc3ec1492014-05-26 06:22:03 +00002959 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00002960 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002961 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2962 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002963 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002964
2965 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002966 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002967 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002968 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002969 Result = new (Context) ReturnStmt(ReturnLoc);
2970 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00002971 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00002972 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002973
2974 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
2975
2976 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2977 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2978 // function return.
2979
2980 // In C++ the return statement is handled via a copy initialization,
2981 // the C version of which boils down to CheckSingleAssignmentConstraints.
2982 if (RetValExp)
2983 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00002984 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002985 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002986 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00002987 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002988 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002989 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00002990 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002991 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00002992 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002993 return StmtError();
2994 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002995 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00002996
2997 // If we have a related result type, we need to implicitly
2998 // convert back to the formal result type. We can't pretend to
2999 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003000 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003001 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003002 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3003 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003004 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3005 if (Res.isInvalid()) {
3006 // FIXME: Clean up temporaries here anyway?
3007 return StmtError();
3008 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003009 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003010 }
3011
Artyom Skrobov9f213442014-01-24 11:10:39 +00003012 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3013 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003015
John McCallacf0ee52010-10-08 02:01:28 +00003016 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003017 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3018 if (ER.isInvalid())
3019 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003020 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003021 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003022 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024
3025 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003026 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003027 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003028 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003029
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003030 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003031}
3032
John McCalldadc5752010-08-24 06:29:42 +00003033StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003034Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003035 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003036 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003037 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003038 if (Var && Var->isInvalidDecl())
3039 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003040
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003041 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003042}
3043
John McCalldadc5752010-08-24 06:29:42 +00003044StmtResult
John McCallb268a282010-08-23 23:25:46 +00003045Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003046 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003047}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003048
John McCalldadc5752010-08-24 06:29:42 +00003049StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003051 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003052 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003053 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3054
John McCallaab3e412010-08-25 08:40:02 +00003055 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003056 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003057 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3058 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003059}
3060
John McCall0bd3e402012-05-08 21:41:25 +00003061StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003062 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003063 ExprResult Result = DefaultLvalueConversion(Throw);
3064 if (Result.isInvalid())
3065 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003066
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003067 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003068 if (Result.isInvalid())
3069 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003070 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003071
Douglas Gregor2900c162010-04-22 21:44:01 +00003072 QualType ThrowType = Throw->getType();
3073 // Make sure the expression type is an ObjC pointer or "void *".
3074 if (!ThrowType->isDependentType() &&
3075 !ThrowType->isObjCObjectPointerType()) {
3076 const PointerType *PT = ThrowType->getAs<PointerType>();
3077 if (!PT || !PT->getPointeeType()->isVoidType())
3078 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3079 << Throw->getType() << Throw->getSourceRange());
3080 }
3081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003083 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003084}
3085
John McCalldadc5752010-08-24 06:29:42 +00003086StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003088 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003089 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003090 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3091
John McCallb268a282010-08-23 23:25:46 +00003092 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003093 // @throw without an expression designates a rethrow (which much occur
3094 // in the context of an @catch clause).
3095 Scope *AtCatchParent = CurScope;
3096 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3097 AtCatchParent = AtCatchParent->getParent();
3098 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003099 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003100 }
John McCallb268a282010-08-23 23:25:46 +00003101 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003102}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003103
John McCalld9bb7432011-07-27 21:50:02 +00003104ExprResult
3105Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3106 ExprResult result = DefaultLvalueConversion(operand);
3107 if (result.isInvalid())
3108 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003109 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003110
3111 // Make sure the expression type is an ObjC pointer or "void *".
3112 QualType type = operand->getType();
3113 if (!type->isDependentType() &&
3114 !type->isObjCObjectPointerType()) {
3115 const PointerType *pointerType = type->getAs<PointerType>();
3116 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3117 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3118 << type << operand->getSourceRange();
3119 }
3120
3121 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003122 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003123}
3124
John McCalldadc5752010-08-24 06:29:42 +00003125StmtResult
John McCallb268a282010-08-23 23:25:46 +00003126Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3127 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003128 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003129 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003130 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003131}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003132
3133/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3134/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003135StmtResult
John McCall48871652010-08-21 09:40:31 +00003136Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003137 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003138 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003139 return new (Context)
3140 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003141}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003142
John McCall31168b02011-06-15 23:02:42 +00003143StmtResult
3144Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3145 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003146 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003147}
3148
Dan Gohman28ade552010-07-26 21:25:24 +00003149namespace {
3150
Sebastian Redl63c4da02009-07-29 17:15:45 +00003151class TypeWithHandler {
3152 QualType t;
3153 CXXCatchStmt *stmt;
3154public:
3155 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3156 : t(type), stmt(statement) {}
3157
John McCall8ccfcb52009-09-24 19:53:00 +00003158 // An arbitrary order is fine as long as it places identical
3159 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003160 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003161 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003162 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003163 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003164 return false;
3165 else
3166 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3167 }
Mike Stump11289f42009-09-09 15:08:12 +00003168
Sebastian Redl63c4da02009-07-29 17:15:45 +00003169 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003170 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003171 }
Mike Stump11289f42009-09-09 15:08:12 +00003172
Sebastian Redl63c4da02009-07-29 17:15:45 +00003173 CXXCatchStmt *getCatchStmt() const { return stmt; }
3174 SourceLocation getTypeSpecStartLoc() const {
3175 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3176 }
3177};
3178
Dan Gohman28ade552010-07-26 21:25:24 +00003179}
3180
Sebastian Redl9b244a82008-12-22 21:35:02 +00003181/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3182/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003183StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3184 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003185 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003186 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003187 !getSourceManager().isInSystemHeader(TryLoc))
3188 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003189
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003190 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3191 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3192
Robert Wilhelmcafda822013-08-22 09:20:03 +00003193 const unsigned NumHandlers = Handlers.size();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003194 assert(NumHandlers > 0 &&
3195 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003196
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003197 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003198
3199 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003200 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003201 if (!Handler->getExceptionDecl()) {
3202 if (i < NumHandlers - 1)
3203 return StmtError(Diag(Handler->getLocStart(),
3204 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003205
Sebastian Redl63c4da02009-07-29 17:15:45 +00003206 continue;
3207 }
Mike Stump11289f42009-09-09 15:08:12 +00003208
Sebastian Redl63c4da02009-07-29 17:15:45 +00003209 const QualType CaughtType = Handler->getCaughtType();
3210 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3211 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003212 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003213
3214 // Detect handlers for the same type as an earlier one.
3215 if (NumHandlers > 1) {
3216 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003217
Sebastian Redl63c4da02009-07-29 17:15:45 +00003218 TypeWithHandler prev = TypesWithHandlers[0];
3219 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3220 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003221
Sebastian Redl63c4da02009-07-29 17:15:45 +00003222 if (curr == prev) {
3223 Diag(curr.getTypeSpecStartLoc(),
3224 diag::warn_exception_caught_by_earlier_handler)
3225 << curr.getCatchStmt()->getCaughtType().getAsString();
3226 Diag(prev.getTypeSpecStartLoc(),
3227 diag::note_previous_exception_handler)
3228 << prev.getCatchStmt()->getCaughtType().getAsString();
3229 }
Mike Stump11289f42009-09-09 15:08:12 +00003230
Sebastian Redl63c4da02009-07-29 17:15:45 +00003231 prev = curr;
3232 }
3233 }
Mike Stump11289f42009-09-09 15:08:12 +00003234
John McCallaab3e412010-08-25 08:40:02 +00003235 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003236
Sebastian Redl9b244a82008-12-22 21:35:02 +00003237 // FIXME: We should detect handlers that cannot catch anything because an
3238 // earlier handler catches a superclass. Need to find a method that is not
3239 // quadratic for this.
3240 // Neither of these are explicitly forbidden, but every compiler detects them
3241 // and warns.
3242
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003243 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003244}
John Wiegley1c0675e2011-04-28 01:08:34 +00003245
3246StmtResult
3247Sema::ActOnSEHTryBlock(bool IsCXXTry,
3248 SourceLocation TryLoc,
3249 Stmt *TryBlock,
3250 Stmt *Handler) {
3251 assert(TryBlock && Handler);
3252
3253 getCurFunction()->setHasBranchProtectedScope();
3254
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003255 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003256}
3257
3258StmtResult
3259Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3260 Expr *FilterExpr,
3261 Stmt *Block) {
3262 assert(FilterExpr && Block);
3263
3264 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003265 return StmtError(Diag(FilterExpr->getExprLoc(),
3266 diag::err_filter_expression_integral)
3267 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003268 }
3269
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003270 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003271}
3272
3273StmtResult
3274Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3275 Stmt *Block) {
3276 assert(Block);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003277 return SEHFinallyStmt::Create(Context,Loc,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003278}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003279
Nico Weberc7d05962014-07-06 22:32:59 +00003280StmtResult
3281Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003282 Scope *SEHTryParent = CurScope;
3283 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3284 SEHTryParent = SEHTryParent->getParent();
3285 if (!SEHTryParent)
3286 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3287
Nico Weber9b982072014-07-07 00:12:30 +00003288 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003289}
3290
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003291StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3292 bool IsIfExists,
3293 NestedNameSpecifierLoc QualifierLoc,
3294 DeclarationNameInfo NameInfo,
3295 Stmt *Nested)
3296{
3297 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003298 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003299 cast<CompoundStmt>(Nested));
3300}
3301
3302
Chad Rosier02a84392012-08-10 17:56:09 +00003303StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003304 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003305 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003306 UnqualifiedId &Name,
3307 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003308 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003309 SS.getWithLocInContext(Context),
3310 GetNameFromUnqualifiedId(Name),
3311 Nested);
3312}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003313
3314RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003315Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3316 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003317 DeclContext *DC = CurContext;
3318 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3319 DC = DC->getParent();
3320
Craig Topperc3ec1492014-05-26 06:22:03 +00003321 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003322 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3324 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003325 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003326 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003327
3328 DC->addDecl(RD);
3329 RD->setImplicit();
3330 RD->startDefinition();
3331
Alexey Bataev9959db52014-05-06 10:08:46 +00003332 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003333 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003334 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003335 return RD;
3336}
3337
3338static void buildCapturedStmtCaptureList(
3339 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3340 SmallVectorImpl<Expr *> &CaptureInits,
3341 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3342
3343 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3344 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3345
3346 if (Cap->isThisCapture()) {
3347 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3348 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003349 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003350 continue;
3351 }
3352
3353 assert(Cap->isReferenceCapture() &&
3354 "non-reference capture not yet implemented");
3355
3356 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3357 CapturedStmt::VCK_ByRef,
3358 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003359 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003360 }
3361}
3362
3363void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003364 CapturedRegionKind Kind,
3365 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003366 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003367 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003368
Alexey Bataev9959db52014-05-06 10:08:46 +00003369 // Build the context parameter
3370 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3371 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3372 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3373 ImplicitParamDecl *Param
3374 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3375 DC->addDecl(Param);
3376
3377 CD->setContextParam(0, Param);
3378
3379 // Enter the capturing scope for this captured region.
3380 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3381
3382 if (CurScope)
3383 PushDeclContext(CurScope, CD);
3384 else
3385 CurContext = CD;
3386
3387 PushExpressionEvaluationContext(PotentiallyEvaluated);
3388}
3389
3390void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3391 CapturedRegionKind Kind,
3392 ArrayRef<CapturedParamNameType> Params) {
3393 CapturedDecl *CD = nullptr;
3394 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3395
3396 // Build the context parameter
3397 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3398 bool ContextIsFound = false;
3399 unsigned ParamNum = 0;
3400 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3401 E = Params.end();
3402 I != E; ++I, ++ParamNum) {
3403 if (I->second.isNull()) {
3404 assert(!ContextIsFound &&
3405 "null type has been found already for '__context' parameter");
3406 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3407 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3408 ImplicitParamDecl *Param
3409 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3410 DC->addDecl(Param);
3411 CD->setContextParam(ParamNum, Param);
3412 ContextIsFound = true;
3413 } else {
3414 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3415 ImplicitParamDecl *Param
3416 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3417 DC->addDecl(Param);
3418 CD->setParam(ParamNum, Param);
3419 }
3420 }
3421 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003422 if (!ContextIsFound) {
3423 // Add __context implicitly if it is not specified.
3424 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3425 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3426 ImplicitParamDecl *Param =
3427 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3428 DC->addDecl(Param);
3429 CD->setContextParam(ParamNum, Param);
3430 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003431 // Enter the capturing scope for this captured region.
3432 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3433
3434 if (CurScope)
3435 PushDeclContext(CurScope, CD);
3436 else
3437 CurContext = CD;
3438
3439 PushExpressionEvaluationContext(PotentiallyEvaluated);
3440}
3441
Wei Pan17fbf6e2013-05-04 03:59:06 +00003442void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003443 DiscardCleanupsInEvaluationContext();
3444 PopExpressionEvaluationContext();
3445
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003446 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3447 RecordDecl *Record = RSI->TheRecordDecl;
3448 Record->setInvalidDecl();
3449
Aaron Ballman62e47c42014-03-10 13:43:55 +00003450 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003451 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3452 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003453
Wei Pan17fbf6e2013-05-04 03:59:06 +00003454 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003455 PopFunctionScopeInfo();
3456}
3457
3458StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3459 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3460
3461 SmallVector<CapturedStmt::Capture, 4> Captures;
3462 SmallVector<Expr *, 4> CaptureInits;
3463 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3464
3465 CapturedDecl *CD = RSI->TheCapturedDecl;
3466 RecordDecl *RD = RSI->TheRecordDecl;
3467
Wei Pan17fbf6e2013-05-04 03:59:06 +00003468 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3469 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003470 CaptureInits, CD, RD);
3471
3472 CD->setBody(Res->getCapturedStmt());
3473 RD->completeDefinition();
3474
Wei Pan17fbf6e2013-05-04 03:59:06 +00003475 DiscardCleanupsInEvaluationContext();
3476 PopExpressionEvaluationContext();
3477
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003478 PopDeclContext();
3479 PopFunctionScopeInfo();
3480
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003481 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003482}