blob: 1ddb3694cbeba1bf8038f143e56ca822a5e8f998 [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();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000256 if (MD) {
257 if (MD->hasAttr<WarnUnusedResultAttr>()) {
258 Diag(Loc, diag::warn_unused_result) << R1 << R2;
259 return;
260 }
261 if (MD->isPropertyAccessor()) {
262 Diag(Loc, diag::warn_unused_property_expr);
263 return;
264 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000265 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000266 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
267 const Expr *Source = POE->getSyntacticForm();
268 if (isa<ObjCSubscriptRefExpr>(Source))
269 DiagID = diag::warn_unused_container_subscript_expr;
270 else
271 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000272 } else if (const CXXFunctionalCastExpr *FC
273 = dyn_cast<CXXFunctionalCastExpr>(E)) {
274 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
275 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
276 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000277 }
John McCall2351cb92010-04-06 22:24:14 +0000278 // Diagnose "(void*) blah" as a typo for "(void) blah".
279 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
280 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
281 QualType T = TI->getType();
282
283 // We really do want to use the non-canonical type here.
284 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000285 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000286
287 Diag(Loc, diag::warn_unused_voidptr)
288 << FixItHint::CreateRemoval(TL.getStarLoc());
289 return;
290 }
291 }
292
Eli Friedmanc11535c2012-05-24 00:47:05 +0000293 if (E->isGLValue() && E->getType().isVolatileQualified()) {
294 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
295 return;
296 }
297
Craig Topperc3ec1492014-05-26 06:22:03 +0000298 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000299}
300
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000301void Sema::ActOnStartOfCompoundStmt() {
302 PushCompoundScope();
303}
304
305void Sema::ActOnFinishOfCompoundStmt() {
306 PopCompoundScope();
307}
308
309sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
310 return getCurFunction()->CompoundScopes.back();
311}
312
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000313StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
314 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
315 const unsigned NumElts = Elts.size();
316
Chris Lattnerd864daf2007-08-27 04:29:41 +0000317 // If we're in C89 mode, check that we don't have any decls after stmts. If
318 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000319 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000320 // Note that __extension__ can be around a decl.
321 unsigned i = 0;
322 // Skip over all declarations.
323 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
324 /*empty*/;
325
326 // We found the end of the list or a statement. Scan for another declstmt.
327 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
328 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattnerd864daf2007-08-27 04:29:41 +0000330 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000331 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000332 Diag(D->getLocation(), diag::ext_mixed_decls_code);
333 }
334 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000335 // Warn about unused expressions in statements.
336 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000337 // Ignore statements that are last in a statement expression.
338 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000339 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000340
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000341 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000342 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000343
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000344 // Check for suspicious empty body (null statement) in `for' and `while'
345 // statements. Don't do anything for template instantiations, this just adds
346 // noise.
347 if (NumElts != 0 && !CurrentInstantiationScope &&
348 getCurCompoundScope().HasEmptyLoopBodies) {
349 for (unsigned i = 0; i != NumElts - 1; ++i)
350 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
351 }
352
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000353 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000354}
355
John McCalldadc5752010-08-24 06:29:42 +0000356StmtResult
John McCallb268a282010-08-23 23:25:46 +0000357Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
358 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000359 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000360 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000361
John McCallaab3e412010-08-25 08:40:02 +0000362 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000363 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000364 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000365 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000366
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000367 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000368 // C99 6.8.4.2p3: The expression shall be an integer constant.
369 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000370 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000371 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000372 if (!LHSVal)
373 return StmtError();
374 }
Richard Smithf8379a02012-01-18 23:55:52 +0000375
376 // GCC extension: The expression shall be an integer constant.
377
Richard Smithf4c51d92012-02-04 09:53:13 +0000378 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000379 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000380 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000381 }
382 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000383
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000384 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000385 getLangOpts().CPlusPlus11).get();
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000386 if (RHSVal)
387 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000388 getLangOpts().CPlusPlus11).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000389
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000390 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
391 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000392 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000393 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000394}
395
Chris Lattner34a22092009-03-04 04:23:07 +0000396/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000397void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000398 DiagnoseUnusedExprResult(SubStmt);
399
Chris Lattner34a22092009-03-04 04:23:07 +0000400 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000401 CS->setSubStmt(SubStmt);
402}
403
John McCalldadc5752010-08-24 06:29:42 +0000404StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000405Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000406 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000407 DiagnoseUnusedExprResult(SubStmt);
408
John McCallaab3e412010-08-25 08:40:02 +0000409 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000410 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000411 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000412 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000413
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000414 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000415 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000416 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000417}
418
John McCalldadc5752010-08-24 06:29:42 +0000419StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000420Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
421 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000422 // If the label was multiply defined, reject it now.
423 if (TheDecl->getStmt()) {
424 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
425 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000426 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000427 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000428
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000429 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000430 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
431 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000432 if (!TheDecl->isGnuLocal()) {
433 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000434 TheDecl->setLocation(IdentLoc);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000435 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000436 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000437}
438
Richard Smithc202b282012-04-14 00:33:13 +0000439StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000440 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000441 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000442 // Fill in the declaration and return it.
443 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000444 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000445}
446
John McCalldadc5752010-08-24 06:29:42 +0000447StmtResult
John McCall48871652010-08-21 09:40:31 +0000448Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000449 Stmt *thenStmt, SourceLocation ElseLoc,
450 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000451 // If the condition was invalid, discard the if statement. We could recover
452 // better by replacing it with a valid expr, but don't do that yet.
453 if (!CondVal.get() && !CondVar) {
454 getCurFunction()->setHasDroppedStmt();
455 return StmtError();
456 }
457
John McCalldadc5752010-08-24 06:29:42 +0000458 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000459
Craig Topperc3ec1492014-05-26 06:22:03 +0000460 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000461 if (CondVar) {
462 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000463 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000464 if (CondResult.isInvalid())
465 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000466 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000467 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000468 if (!ConditionExpr)
469 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000471 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000472
John McCallb268a282010-08-23 23:25:46 +0000473 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000474 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
475 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000476 }
477
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000478 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000479
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000480 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
481 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000482}
Steve Naroff86272ea2007-05-29 02:14:17 +0000483
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000484/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
485/// the specified width and sign. If an overflow occurs, detect it and emit
486/// the specified diagnostic.
487void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
488 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000489 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000490 unsigned DiagID) {
491 // Perform a conversion to the promoted condition type if needed.
492 if (NewWidth > Val.getBitWidth()) {
493 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000494 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000495 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000496
497 // If the input was signed and negative and the output is
498 // unsigned, don't bother to warn: this is implementation-defined
499 // behavior.
500 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000501 } else if (NewWidth < Val.getBitWidth()) {
502 // If this is a truncation, check for overflow.
503 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000504 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000505 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000506 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000507 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000508 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000509 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000511 // Regardless of whether a diagnostic was emitted, really do the
512 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000513 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000514 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000515 } else if (NewSign != Val.isSigned()) {
516 // Convert the sign to match the sign of the condition. This can cause
517 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000519 // behavior.
520 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000521 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000522 }
523}
524
Chris Lattner67998452007-08-23 18:29:20 +0000525namespace {
526 struct CaseCompareFunctor {
527 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
528 const llvm::APSInt &RHS) {
529 return LHS.first < RHS;
530 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000531 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
532 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
533 return LHS.first < RHS.first;
534 }
Chris Lattner67998452007-08-23 18:29:20 +0000535 bool operator()(const llvm::APSInt &LHS,
536 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
537 return LHS < RHS.first;
538 }
539 };
540}
541
Chris Lattner4b2ff022007-09-21 18:15:22 +0000542/// CmpCaseVals - Comparison predicate for sorting case values.
543///
544static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
545 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
546 if (lhs.first < rhs.first)
547 return true;
548
549 if (lhs.first == rhs.first &&
550 lhs.second->getCaseLoc().getRawEncoding()
551 < rhs.second->getCaseLoc().getRawEncoding())
552 return true;
553 return false;
554}
555
Douglas Gregorbd6839732010-02-08 22:24:16 +0000556/// CmpEnumVals - Comparison predicate for sorting enumeration values.
557///
558static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
559 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
560{
561 return lhs.first < rhs.first;
562}
563
564/// EqEnumVals - Comparison preficate for uniqing enumeration values.
565///
566static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
567 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
568{
569 return lhs.first == rhs.first;
570}
571
Chris Lattnera96d4272009-10-16 16:45:22 +0000572/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
573/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000574static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
575 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
576 expr = cleanups->getSubExpr();
577 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
578 if (impcast->getCastKind() != CK_IntegralCast) break;
579 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000580 }
581 return expr->getType();
582}
583
John McCalldadc5752010-08-24 06:29:42 +0000584StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000586 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000587 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000588
Craig Topperc3ec1492014-05-26 06:22:03 +0000589 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000590 if (CondVar) {
591 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000592 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
593 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000594 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000596 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
John McCallb268a282010-08-23 23:25:46 +0000599 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000600 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregore2b37442012-05-04 22:38:52 +0000602 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
603 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000604
Douglas Gregore2b37442012-05-04 22:38:52 +0000605 public:
606 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000607 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
608 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000609
Craig Toppere14c0f82014-03-12 04:55:44 +0000610 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
611 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000612 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
613 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000614
Craig Toppere14c0f82014-03-12 04:55:44 +0000615 SemaDiagnosticBuilder diagnoseIncomplete(
616 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000617 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
618 << T << Cond->getSourceRange();
619 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000620
Craig Toppere14c0f82014-03-12 04:55:44 +0000621 SemaDiagnosticBuilder diagnoseExplicitConv(
622 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000623 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
624 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000625
Craig Toppere14c0f82014-03-12 04:55:44 +0000626 SemaDiagnosticBuilder noteExplicitConv(
627 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000628 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
629 << ConvTy->isEnumeralType() << ConvTy;
630 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000631
Craig Toppere14c0f82014-03-12 04:55:44 +0000632 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
633 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000634 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
635 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000636
Craig Toppere14c0f82014-03-12 04:55:44 +0000637 SemaDiagnosticBuilder noteAmbiguous(
638 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000639 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
640 << ConvTy->isEnumeralType() << ConvTy;
641 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000642
Craig Toppere14c0f82014-03-12 04:55:44 +0000643 SemaDiagnosticBuilder diagnoseConversion(
644 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000645 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000646 }
647 } SwitchDiagnoser(Cond);
648
Richard Smithccc11812013-05-21 19:05:48 +0000649 CondResult =
650 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000651 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000652 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
John McCall5939b162011-08-06 07:30:58 +0000654 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
655 CondResult = UsualUnaryConversions(Cond);
656 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000657 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000658
John McCall48871652010-08-21 09:40:31 +0000659 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000660 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000661 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000662 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000663 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000664 }
John McCalla95172b2010-08-01 00:26:45 +0000665
John McCallaab3e412010-08-25 08:40:02 +0000666 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667
John McCallb268a282010-08-23 23:25:46 +0000668 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000669 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000670 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000671}
672
Gabor Greif16e02862010-10-01 22:05:14 +0000673static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
674 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000675 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000676 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000677 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000678 Val.setIsSigned(IsSigned);
679}
680
Dmitri Gribenko58683752013-12-05 22:52:07 +0000681/// Returns true if we should emit a diagnostic about this case expression not
682/// being a part of the enum used in the switch controlling expression.
683static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
684 const EnumDecl *ED,
685 const Expr *CaseExpr) {
686 // Don't warn if the 'case' expression refers to a static const variable of
687 // the enum type.
688 CaseExpr = CaseExpr->IgnoreParenImpCasts();
689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
690 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
691 if (!VD->hasGlobalStorage())
692 return true;
693 QualType VarType = VD->getType();
694 if (!VarType.isConstQualified())
695 return true;
696 QualType EnumType = Ctx.getTypeDeclType(ED);
697 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
698 return false;
699 }
700 }
701 return true;
702}
703
John McCalldadc5752010-08-24 06:29:42 +0000704StmtResult
John McCallb268a282010-08-23 23:25:46 +0000705Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
706 Stmt *BodyStmt) {
707 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000708 assert(SS == getCurFunction()->SwitchStack.back() &&
709 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000710
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000711 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000712 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000713 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000714
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000715 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000716 if (!CondExpr) return StmtError();
717
718 QualType CondType = CondExpr->getType();
719
John McCalld3dfbd62010-05-18 03:19:21 +0000720 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000721 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000722 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000723
Chris Lattnera96d4272009-10-16 16:45:22 +0000724 // C++ 6.4.2.p2:
725 // Integral promotions are performed (on the switch condition).
726 //
727 // A case value unrepresentable by the original switch condition
728 // type (before the promotion) doesn't make sense, even when it can
729 // be represented by the promoted type. Therefore we need to find
730 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000731 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000732 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000734 // appropriate type now, just return an error.
735 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000736 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000737
Chris Lattner4ebae652010-04-16 23:34:13 +0000738 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000739 // switch(bool_expr) {...} is often a programmer error, e.g.
740 // switch(n && mask) { ... } // Doh - should be "n & mask".
741 // One can always use an if statement instead of switch(bool_expr).
742 Diag(SwitchLoc, diag::warn_bool_switch_condition)
743 << CondExpr->getSourceRange();
744 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000745 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000746
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000747 // Get the bitwidth of the switched-on value before promotions. We must
748 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000749 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000750 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000751 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000752 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier02a84392012-08-10 17:56:09 +0000753 bool CondIsSigned
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000754 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000756 // Accumulate all of the case values in a vector so that we can sort them
757 // and detect duplicates. This vector contains the APInt for the case after
758 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000759 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000760 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000762 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000763 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
764 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000765
Craig Topperc3ec1492014-05-26 06:22:03 +0000766 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattner10cb5e52007-08-23 06:23:56 +0000768 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000769
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000770 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000771 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000772
Anders Carlsson51873c22007-07-22 07:07:56 +0000773 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000774 if (TheDefaultStmt) {
775 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000776 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000777
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000778 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000779 // we'll return a valid AST. This requires recursing down the AST and
780 // finding it, not something we are set up to do right now. For now,
781 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000782 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000783 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000784 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000786 } else {
787 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattnera65e1f32008-01-16 19:17:22 +0000789 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000790
791 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
792 HasDependentValue = true;
793 break;
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Richard Smithf8379a02012-01-18 23:55:52 +0000796 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000797
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000798 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000799 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
800 // constant expression of the promoted type of the switch condition.
801 ExprResult ConvLo =
802 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
803 if (ConvLo.isInvalid()) {
804 CaseListIsErroneous = true;
805 continue;
806 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000807 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000808 } else {
809 // We already verified that the expression has a i-c-e value (C99
810 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000811 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000812
813 // If the LHS is not the same type as the condition, insert an implicit
814 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000815 Lo = DefaultLvalueConversion(Lo).get();
816 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000817 }
818
819 // Convert the value to the same width/sign as the condition had prior to
820 // integral promotions.
821 //
822 // FIXME: This causes us to reject valid code:
823 // switch ((char)c) { case 256: case 0: return 0; }
824 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000825 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000826 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000827 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000828
Chris Lattnera65e1f32008-01-16 19:17:22 +0000829 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattner10cb5e52007-08-23 06:23:56 +0000831 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000832 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000833 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000834 CS->getRHS()->isValueDependent()) {
835 HasDependentValue = true;
836 break;
837 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000838 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000839 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000840 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000841 }
842 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000843
844 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000845 // If we don't have a default statement, check whether the
846 // condition is constant.
847 llvm::APSInt ConstantCondValue;
848 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000849 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000850 HasConstantCond
Richard Smith5fab0c92011-12-28 19:48:30 +0000851 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
852 Expr::SE_AllowSideEffects);
853 assert(!HasConstantCond ||
854 (ConstantCondValue.getBitWidth() == CondWidth &&
855 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000856 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000857 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000858
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000859 // Sort all the scalar case values so we can easily detect duplicates.
860 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
861
862 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000863 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
864 if (ShouldCheckConstantCond &&
865 CaseVals[i].first == ConstantCondValue)
866 ShouldCheckConstantCond = false;
867
868 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000869 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000870 // First, determine if either case value has a name
871 StringRef PrevString, CurrString;
872 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
873 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
874 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
875 PrevString = DeclRef->getDecl()->getName();
876 }
877 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
878 CurrString = DeclRef->getDecl()->getName();
879 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000880 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000881 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000882
883 if (PrevString == CurrString)
884 Diag(CaseVals[i].second->getLHS()->getLocStart(),
885 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000886 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000887 else
888 Diag(CaseVals[i].second->getLHS()->getLocStart(),
889 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000890 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
891 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000892 CaseValStr;
893
John McCalld3dfbd62010-05-18 03:19:21 +0000894 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000895 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000896 // FIXME: We really want to remove the bogus case stmt from the
897 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000898 CaseListIsErroneous = true;
899 }
900 }
901 }
Mike Stump11289f42009-09-09 15:08:12 +0000902
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000903 // Detect duplicate case ranges, which usually don't exist at all in
904 // the first place.
905 if (!CaseRanges.empty()) {
906 // Sort all the case ranges by their low value so we can easily detect
907 // overlaps between ranges.
908 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000909
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000910 // Scan the ranges, computing the high values and removing empty ranges.
911 std::vector<llvm::APSInt> HiVals;
912 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000913 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000914 CaseStmt *CR = CaseRanges[i].second;
915 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000916 llvm::APSInt HiVal;
917
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000918 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000919 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
920 // constant expression of the promoted type of the switch condition.
921 ExprResult ConvHi =
922 CheckConvertedConstantExpression(Hi, CondType, HiVal,
923 CCEK_CaseValue);
924 if (ConvHi.isInvalid()) {
925 CaseListIsErroneous = true;
926 continue;
927 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000928 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000929 } else {
930 HiVal = Hi->EvaluateKnownConstInt(Context);
931
932 // If the RHS is not the same type as the condition, insert an
933 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000934 Hi = DefaultLvalueConversion(Hi).get();
935 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000936 }
Mike Stump11289f42009-09-09 15:08:12 +0000937
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000938 // Convert the value to the same width/sign as the condition.
939 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000940 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000941 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000943 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000944
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000945 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000946 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000947 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
948 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000949 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000950 CaseRanges.erase(CaseRanges.begin()+i);
951 --i, --e;
952 continue;
953 }
John McCalld3dfbd62010-05-18 03:19:21 +0000954
955 if (ShouldCheckConstantCond &&
956 LoVal <= ConstantCondValue &&
957 ConstantCondValue <= HiVal)
958 ShouldCheckConstantCond = false;
959
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000960 HiVals.push_back(HiVal);
961 }
Mike Stump11289f42009-09-09 15:08:12 +0000962
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000963 // Rescan the ranges, looking for overlap with singleton values and other
964 // ranges. Since the range list is sorted, we only need to compare case
965 // ranges with their neighbors.
966 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
967 llvm::APSInt &CRLo = CaseRanges[i].first;
968 llvm::APSInt &CRHi = HiVals[i];
969 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000970
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000971 // Check to see whether the case range overlaps with any
972 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +0000973 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000974 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000976 // Find the smallest value >= the lower bound. If I is in the
977 // case range, then we have overlap.
978 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
979 CaseVals.end(), CRLo,
980 CaseCompareFunctor());
981 if (I != CaseVals.end() && I->first < CRHi) {
982 OverlapVal = I->first; // Found overlap with scalar.
983 OverlapStmt = I->second;
984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000986 // Find the smallest value bigger than the upper bound.
987 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
988 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
989 OverlapVal = (I-1)->first; // Found overlap with scalar.
990 OverlapStmt = (I-1)->second;
991 }
Mike Stump11289f42009-09-09 15:08:12 +0000992
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000993 // Check to see if this case stmt overlaps with the subsequent
994 // case range.
995 if (i && CRLo <= HiVals[i-1]) {
996 OverlapVal = HiVals[i-1]; // Found overlap with range.
997 OverlapStmt = CaseRanges[i-1].second;
998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001000 if (OverlapStmt) {
1001 // If we have a duplicate, report it.
1002 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1003 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001004 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001005 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001006 // FIXME: We really want to remove the bogus case stmt from the
1007 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001008 CaseListIsErroneous = true;
1009 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001010 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001011 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001012
John McCalld3dfbd62010-05-18 03:19:21 +00001013 // Complain if we have a constant condition and we didn't find a match.
1014 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1015 // TODO: it would be nice if we printed enums as enums, chars as
1016 // chars, etc.
1017 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1018 << ConstantCondValue.toString(10)
1019 << CondExpr->getSourceRange();
1020 }
1021
1022 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001023 // values. We only issue a warning if there is not 'default:', but
1024 // we still do the analysis to preserve this information in the AST
1025 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001026 //
Chris Lattner51679082010-09-16 17:09:42 +00001027 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001028
Douglas Gregorbd6839732010-02-08 22:24:16 +00001029 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001030 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001031 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001032 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +00001033 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001034 EnumValsTy EnumVals;
1035
John McCalld3dfbd62010-05-18 03:19:21 +00001036 // Gather all enum values, set their type and sort them,
1037 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001038 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001039 llvm::APSInt Val = EDI->getInitVal();
1040 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001041 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001042 }
1043 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +00001044 EnumValsTy::iterator EIend =
1045 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001046
1047 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001048 EnumValsTy::const_iterator EI = EnumVals.begin();
1049 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1050 CI != CaseVals.end(); CI++) {
1051 while (EI != EIend && EI->first < CI->first)
1052 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001053 if (EI == EIend || EI->first > CI->first) {
1054 Expr *CaseExpr = CI->second->getLHS();
1055 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1056 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1057 << CondTypeBeforePromotion;
1058 }
David Blaikiee476f972012-01-22 02:31:55 +00001059 }
1060 // See which of case ranges aren't in enum
1061 EI = EnumVals.begin();
1062 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1063 RI != CaseRanges.end() && EI != EIend; RI++) {
1064 while (EI != EIend && EI->first < RI->first)
1065 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
David Blaikiee476f972012-01-22 02:31:55 +00001067 if (EI == EIend || EI->first != RI->first) {
Dmitri Gribenko58683752013-12-05 22:52:07 +00001068 Expr *CaseExpr = RI->second->getLHS();
1069 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1070 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1071 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +00001072 }
David Blaikiee476f972012-01-22 02:31:55 +00001073
Chad Rosier02a84392012-08-10 17:56:09 +00001074 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001075 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1076 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1077 while (EI != EIend && EI->first < Hi)
1078 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001079 if (EI == EIend || EI->first != Hi) {
1080 Expr *CaseExpr = RI->second->getRHS();
1081 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1082 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1083 << CondTypeBeforePromotion;
1084 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
Ted Kremenekc42f3452010-09-09 00:05:53 +00001087 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +00001088 CaseValsTy::const_iterator CI = CaseVals.begin();
1089 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001090 bool hasCasesNotInSwitch = false;
1091
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001092 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093
David Blaikiee476f972012-01-22 02:31:55 +00001094 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001095 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001096 while (CI != CaseVals.end() && CI->first < EI->first)
1097 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
Douglas Gregorbd6839732010-02-08 22:24:16 +00001099 if (CI != CaseVals.end() && CI->first == EI->first)
1100 continue;
1101
Ted Kremenekc42f3452010-09-09 00:05:53 +00001102 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001103 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001104 llvm::APSInt Hi =
1105 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001106 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001107 if (EI->first <= Hi)
1108 break;
1109 }
1110
Ted Kremenekc42f3452010-09-09 00:05:53 +00001111 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001112 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001113 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001114 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116
David Blaikie60ac6382012-01-23 04:46:12 +00001117 if (TheDefaultStmt && UnhandledNames.empty())
1118 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001119
Chris Lattner51679082010-09-16 17:09:42 +00001120 // Produce a nice diagnostic if multiple values aren't handled.
1121 switch (UnhandledNames.size()) {
1122 case 0: break;
1123 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001124 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001125 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001126 << UnhandledNames[0];
1127 break;
1128 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001129 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001130 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001131 << UnhandledNames[0] << UnhandledNames[1];
1132 break;
1133 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001134 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1135 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001136 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1137 break;
1138 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001139 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1140 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001141 << (unsigned)UnhandledNames.size()
1142 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1143 break;
1144 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001145
1146 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001147 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001148 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001149 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001150
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001151 if (BodyStmt)
1152 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1153 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001154
Mike Stump87c57ac2009-05-16 07:39:55 +00001155 // FIXME: If the case list was broken is some way, we don't have a good system
1156 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001157 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001158 return StmtError();
1159
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001160 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001161}
1162
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001163void
1164Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1165 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001166 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001167 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001168
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001169 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001170 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001171 SrcType->isIntegerType()) {
1172 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1173 SrcExpr->isIntegerConstantExpr(Context)) {
1174 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001175 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001176 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1177
1178 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001179 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001180 const EnumDecl *ED = ET->getDecl();
Joey Gouly1ba27332013-06-06 13:48:00 +00001181 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1182 EnumValsTy;
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001183 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001184
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001185 // Gather all enum values, set their type and sort them,
1186 // allowing easier comparison with rhs constant.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001187 for (auto *EDI : ED->enumerators()) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001188 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly1ba27332013-06-06 13:48:00 +00001189 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001190 EnumVals.push_back(std::make_pair(Val, EDI));
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001191 }
1192 if (EnumVals.empty())
1193 return;
1194 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1195 EnumValsTy::iterator EIend =
Joey Gouly1ba27332013-06-06 13:48:00 +00001196 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001197
Joey Gouly1ba27332013-06-06 13:48:00 +00001198 // See which values aren't in the enum.
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001199 EnumValsTy::const_iterator EI = EnumVals.begin();
1200 while (EI != EIend && EI->first < RhsVal)
1201 EI++;
1202 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly1ba27332013-06-06 13:48:00 +00001203 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001204 << DstType.getUnqualifiedType();
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001205 }
1206 }
1207 }
1208}
1209
John McCalldadc5752010-08-24 06:29:42 +00001210StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001212 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001213 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214
Craig Topperc3ec1492014-05-26 06:22:03 +00001215 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001216 if (CondVar) {
1217 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001218 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001219 if (CondResult.isInvalid())
1220 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001221 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001222 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001223 if (!ConditionExpr)
1224 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001225 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001226
John McCallb268a282010-08-23 23:25:46 +00001227 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001228
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001229 if (isa<NullStmt>(Body))
1230 getCurCompoundScope().setHasEmptyLoopBodies();
1231
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001232 return new (Context)
1233 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001234}
1235
John McCalldadc5752010-08-24 06:29:42 +00001236StmtResult
John McCallb268a282010-08-23 23:25:46 +00001237Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001238 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001239 Expr *Cond, SourceLocation CondRParen) {
1240 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001241
Serge Pavlov09f99242014-01-23 15:05:00 +00001242 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001243 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001244 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001245 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001246 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001247
Richard Smith945f8d32013-01-14 22:39:08 +00001248 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001249 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001250 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001251 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001252
John McCallb268a282010-08-23 23:25:46 +00001253 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001254
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001255 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001256}
1257
Richard Trieu451a5db2012-04-30 18:01:30 +00001258namespace {
1259 // This visitor will traverse a conditional statement and store all
1260 // the evaluated decls into a vector. Simple is set to true if none
1261 // of the excluded constructs are used.
1262 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1263 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001264 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001265 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001266 public:
1267 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001268
Richard Trieu9d228802013-05-31 22:46:45 +00001269 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001270 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001271 Inherited(S.Context),
1272 Decls(Decls),
1273 Ranges(Ranges),
1274 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001275
Richard Trieu9d228802013-05-31 22:46:45 +00001276 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001277
Richard Trieu9d228802013-05-31 22:46:45 +00001278 // Replaces the method in EvaluatedExprVisitor.
1279 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001280 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001281 }
1282
1283 // Any Stmt not whitelisted will cause the condition to be marked complex.
1284 void VisitStmt(Stmt *S) {
1285 Simple = false;
1286 }
1287
1288 void VisitBinaryOperator(BinaryOperator *E) {
1289 Visit(E->getLHS());
1290 Visit(E->getRHS());
1291 }
1292
1293 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001294 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001295 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001296
Richard Trieu9d228802013-05-31 22:46:45 +00001297 void VisitUnaryOperator(UnaryOperator *E) {
1298 // Skip checking conditionals with derefernces.
1299 if (E->getOpcode() == UO_Deref)
1300 Simple = false;
1301 else
1302 Visit(E->getSubExpr());
1303 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001304
Richard Trieu9d228802013-05-31 22:46:45 +00001305 void VisitConditionalOperator(ConditionalOperator *E) {
1306 Visit(E->getCond());
1307 Visit(E->getTrueExpr());
1308 Visit(E->getFalseExpr());
1309 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001310
Richard Trieu9d228802013-05-31 22:46:45 +00001311 void VisitParenExpr(ParenExpr *E) {
1312 Visit(E->getSubExpr());
1313 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001314
Richard Trieu9d228802013-05-31 22:46:45 +00001315 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1316 Visit(E->getOpaqueValue()->getSourceExpr());
1317 Visit(E->getFalseExpr());
1318 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001319
Richard Trieu9d228802013-05-31 22:46:45 +00001320 void VisitIntegerLiteral(IntegerLiteral *E) { }
1321 void VisitFloatingLiteral(FloatingLiteral *E) { }
1322 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1323 void VisitCharacterLiteral(CharacterLiteral *E) { }
1324 void VisitGNUNullExpr(GNUNullExpr *E) { }
1325 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001326
Richard Trieu9d228802013-05-31 22:46:45 +00001327 void VisitDeclRefExpr(DeclRefExpr *E) {
1328 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1329 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001330
Richard Trieu9d228802013-05-31 22:46:45 +00001331 Ranges.push_back(E->getSourceRange());
1332
1333 Decls.insert(VD);
1334 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001335
1336 }; // end class DeclExtractor
1337
1338 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001339 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001340 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1341 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1342 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001343
Richard Trieu9d228802013-05-31 22:46:45 +00001344 public:
1345 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1348 Stmt *Statement) :
1349 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1350 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001351
Richard Trieu9d228802013-05-31 22:46:45 +00001352 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001353 }
1354
Richard Trieu9d228802013-05-31 22:46:45 +00001355 void VisitReturnStmt(ReturnStmt *S) {
1356 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001357 }
1358
Richard Trieu9d228802013-05-31 22:46:45 +00001359 void VisitBreakStmt(BreakStmt *S) {
1360 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001361 }
1362
Richard Trieu9d228802013-05-31 22:46:45 +00001363 void VisitGotoStmt(GotoStmt *S) {
1364 FoundDecl = true;
1365 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001366
Richard Trieu9d228802013-05-31 22:46:45 +00001367 void VisitCastExpr(CastExpr *E) {
1368 if (E->getCastKind() == CK_LValueToRValue)
1369 CheckLValueToRValueCast(E->getSubExpr());
1370 else
1371 Visit(E->getSubExpr());
1372 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001373
Richard Trieu9d228802013-05-31 22:46:45 +00001374 void CheckLValueToRValueCast(Expr *E) {
1375 E = E->IgnoreParenImpCasts();
1376
1377 if (isa<DeclRefExpr>(E)) {
1378 return;
1379 }
1380
1381 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1382 Visit(CO->getCond());
1383 CheckLValueToRValueCast(CO->getTrueExpr());
1384 CheckLValueToRValueCast(CO->getFalseExpr());
1385 return;
1386 }
1387
1388 if (BinaryConditionalOperator *BCO =
1389 dyn_cast<BinaryConditionalOperator>(E)) {
1390 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1391 CheckLValueToRValueCast(BCO->getFalseExpr());
1392 return;
1393 }
1394
1395 Visit(E);
1396 }
1397
1398 void VisitDeclRefExpr(DeclRefExpr *E) {
1399 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1400 if (Decls.count(VD))
1401 FoundDecl = true;
1402 }
1403
1404 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001405
1406 }; // end class DeclMatcher
1407
1408 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1409 Expr *Third, Stmt *Body) {
1410 // Condition is empty
1411 if (!Second) return;
1412
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001413 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1414 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001415 return;
1416
1417 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1418 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001419 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001420 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001421 DE.Visit(Second);
1422
1423 // Don't analyze complex conditionals.
1424 if (!DE.isSimple()) return;
1425
1426 // No decls found.
1427 if (Decls.size() == 0) return;
1428
Richard Trieu0030f1d2012-05-04 03:01:54 +00001429 // Don't warn on volatile, static, or global variables.
Richard Trieu451a5db2012-04-30 18:01:30 +00001430 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1431 E = Decls.end();
1432 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001433 if ((*I)->getType().isVolatileQualified() ||
1434 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001435
1436 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1437 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1438 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1439 return;
1440
1441 // Load decl names into diagnostic.
1442 if (Decls.size() > 4)
1443 PDiag << 0;
1444 else {
1445 PDiag << Decls.size();
1446 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1447 E = Decls.end();
1448 I != E; ++I)
1449 PDiag << (*I)->getDeclName();
1450 }
1451
1452 // Load SourceRanges into diagnostic if there is room.
1453 // Otherwise, load the SourceRange of the conditional expression.
1454 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001455 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001456 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001457 I != E; ++I)
1458 PDiag << *I;
1459 else
1460 PDiag << Second->getSourceRange();
1461
1462 S.Diag(Ranges.begin()->getBegin(), PDiag);
1463 }
1464
Richard Trieu4e7c9622013-08-06 21:31:54 +00001465 // If Statement is an incemement or decrement, return true and sets the
1466 // variables Increment and DRE.
1467 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1468 DeclRefExpr *&DRE) {
1469 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1470 switch (UO->getOpcode()) {
1471 default: return false;
1472 case UO_PostInc:
1473 case UO_PreInc:
1474 Increment = true;
1475 break;
1476 case UO_PostDec:
1477 case UO_PreDec:
1478 Increment = false;
1479 break;
1480 }
1481 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1482 return DRE;
1483 }
1484
1485 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1486 FunctionDecl *FD = Call->getDirectCallee();
1487 if (!FD || !FD->isOverloadedOperator()) return false;
1488 switch (FD->getOverloadedOperator()) {
1489 default: return false;
1490 case OO_PlusPlus:
1491 Increment = true;
1492 break;
1493 case OO_MinusMinus:
1494 Increment = false;
1495 break;
1496 }
1497 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1498 return DRE;
1499 }
1500
1501 return false;
1502 }
1503
Serge Pavlov09f99242014-01-23 15:05:00 +00001504 // A visitor to determine if a continue or break statement is a
1505 // subexpression.
1506 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1507 SourceLocation BreakLoc;
1508 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001509 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001510 BreakContinueFinder(Sema &S, Stmt* Body) :
1511 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001512 Visit(Body);
1513 }
1514
Serge Pavlov09f99242014-01-23 15:05:00 +00001515 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001516
1517 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001518 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001519 }
1520
Serge Pavlov09f99242014-01-23 15:05:00 +00001521 void VisitBreakStmt(BreakStmt* E) {
1522 BreakLoc = E->getBreakLoc();
1523 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001524
Serge Pavlov09f99242014-01-23 15:05:00 +00001525 bool ContinueFound() { return ContinueLoc.isValid(); }
1526 bool BreakFound() { return BreakLoc.isValid(); }
1527 SourceLocation GetContinueLoc() { return ContinueLoc; }
1528 SourceLocation GetBreakLoc() { return BreakLoc; }
1529
1530 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001531
1532 // Emit a warning when a loop increment/decrement appears twice per loop
1533 // iteration. The conditions which trigger this warning are:
1534 // 1) The last statement in the loop body and the third expression in the
1535 // for loop are both increment or both decrement of the same variable
1536 // 2) No continue statements in the loop body.
1537 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1538 // Return when there is nothing to check.
1539 if (!Body || !Third) return;
1540
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001541 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1542 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001543 return;
1544
1545 // Get the last statement from the loop body.
1546 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1547 if (!CS || CS->body_empty()) return;
1548 Stmt *LastStmt = CS->body_back();
1549 if (!LastStmt) return;
1550
1551 bool LoopIncrement, LastIncrement;
1552 DeclRefExpr *LoopDRE, *LastDRE;
1553
1554 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1555 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1556
1557 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001558 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001559 if (LoopIncrement != LastIncrement ||
1560 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1561
Serge Pavlov09f99242014-01-23 15:05:00 +00001562 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001563
1564 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1565 << LastDRE->getDecl() << LastIncrement;
1566 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1567 << LoopIncrement;
1568 }
1569
Richard Trieu451a5db2012-04-30 18:01:30 +00001570} // end namespace
1571
Serge Pavlov09f99242014-01-23 15:05:00 +00001572
1573void Sema::CheckBreakContinueBinding(Expr *E) {
1574 if (!E || getLangOpts().CPlusPlus)
1575 return;
1576 BreakContinueFinder BCFinder(*this, E);
1577 Scope *BreakParent = CurScope->getBreakParent();
1578 if (BCFinder.BreakFound() && BreakParent) {
1579 if (BreakParent->getFlags() & Scope::SwitchScope) {
1580 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1581 } else {
1582 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1583 << "break";
1584 }
1585 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1586 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1587 << "continue";
1588 }
1589}
1590
John McCalldadc5752010-08-24 06:29:42 +00001591StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001592Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001593 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001594 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001595 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001596 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001597 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001598 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1599 // declare identifiers for objects having storage class 'auto' or
1600 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001601 for (auto *DI : DS->decls()) {
1602 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001603 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001604 VD = nullptr;
1605 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001606 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1607 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001608 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001609 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001610 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001611 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001612
Serge Pavlov09f99242014-01-23 15:05:00 +00001613 CheckBreakContinueBinding(second.get());
1614 CheckBreakContinueBinding(third.get());
1615
Richard Trieu451a5db2012-04-30 18:01:30 +00001616 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001617 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001618
John McCalldadc5752010-08-24 06:29:42 +00001619 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001620 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001621 if (secondVar) {
1622 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001623 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001624 if (SecondResult.isInvalid())
1625 return StmtError();
1626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001627
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001628 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629
Anders Carlsson1682af52009-08-01 01:39:59 +00001630 DiagnoseUnusedExprResult(First);
1631 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001632 DiagnoseUnusedExprResult(Body);
1633
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001634 if (isa<NullStmt>(Body))
1635 getCurCompoundScope().setHasEmptyLoopBodies();
1636
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001637 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1638 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001639}
1640
John McCall34376a62010-12-04 03:47:34 +00001641/// In an Objective C collection iteration statement:
1642/// for (x in y)
1643/// x can be an arbitrary l-value expression. Bind it up as a
1644/// full-expression.
1645StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001646 // Reduce placeholder expressions here. Note that this rejects the
1647 // use of pseudo-object l-values in this position.
1648 ExprResult result = CheckPlaceholderExpr(E);
1649 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001650 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001651
Richard Smith945f8d32013-01-14 22:39:08 +00001652 ExprResult FullExpr = ActOnFinishFullExpr(E);
1653 if (FullExpr.isInvalid())
1654 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001655 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001656}
1657
John McCall53848232011-07-27 01:07:15 +00001658ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001659Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1660 if (!collection)
1661 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001662
John McCall53848232011-07-27 01:07:15 +00001663 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001664 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001665
1666 // Perform normal l-value conversion.
1667 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1668 if (result.isInvalid())
1669 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001670 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001671
1672 // The operand needs to have object-pointer type.
1673 // TODO: should we do a contextual conversion?
1674 const ObjCObjectPointerType *pointerType =
1675 collection->getType()->getAs<ObjCObjectPointerType>();
1676 if (!pointerType)
1677 return Diag(forLoc, diag::err_collection_expr_type)
1678 << collection->getType() << collection->getSourceRange();
1679
1680 // Check that the operand provides
1681 // - countByEnumeratingWithState:objects:count:
1682 const ObjCObjectType *objectType = pointerType->getObjectType();
1683 ObjCInterfaceDecl *iface = objectType->getInterface();
1684
1685 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001686 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001687 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001688 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001689 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001690 ? diag::err_arc_collection_forward
1691 : 0,
1692 collection)) {
John McCall53848232011-07-27 01:07:15 +00001693 // Otherwise, if we have any useful type information, check that
1694 // the type declares the appropriate method.
1695 } else if (iface || !objectType->qual_empty()) {
1696 IdentifierInfo *selectorIdents[] = {
1697 &Context.Idents.get("countByEnumeratingWithState"),
1698 &Context.Idents.get("objects"),
1699 &Context.Idents.get("count")
1700 };
1701 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1702
Craig Topperc3ec1492014-05-26 06:22:03 +00001703 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001704
1705 // If there's an interface, look in both the public and private APIs.
1706 if (iface) {
1707 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001708 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001709 }
1710
1711 // Also check protocol qualifiers.
1712 if (!method)
1713 method = LookupMethodInQualifiedType(selector, pointerType,
1714 /*instance*/ true);
1715
1716 // If we didn't find it anywhere, give up.
1717 if (!method) {
1718 Diag(forLoc, diag::warn_collection_expr_type)
1719 << collection->getType() << selector << collection->getSourceRange();
1720 }
1721
1722 // TODO: check for an incompatible signature?
1723 }
1724
1725 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001726 return collection;
John McCall53848232011-07-27 01:07:15 +00001727}
1728
John McCalldadc5752010-08-24 06:29:42 +00001729StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001730Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001731 Stmt *First, Expr *collection,
1732 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001733
1734 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001735 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001736
Fariborz Jahanian93977672008-01-10 20:33:58 +00001737 if (First) {
1738 QualType FirstType;
1739 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001740 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001741 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1742 diag::err_toomany_element_decls));
1743
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001744 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1745 if (!D || D->isInvalidDecl())
1746 return StmtError();
1747
John McCall31168b02011-06-15 23:02:42 +00001748 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001749 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1750 // declare identifiers for objects having storage class 'auto' or
1751 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001752 if (!D->hasLocalStorage())
1753 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001754 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001755
1756 // If the type contained 'auto', deduce the 'auto' to 'id'.
1757 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001758 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1759 VK_RValue);
1760 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001761 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1762 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001763 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001764 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001765 D->setInvalidDecl();
1766 return StmtError();
1767 }
1768
Richard Smith061f1e22013-04-30 21:23:01 +00001769 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001770
1771 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001772 SourceLocation Loc =
1773 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001774 Diag(Loc, diag::warn_auto_var_is_id)
1775 << D->getDeclName();
1776 }
1777 }
1778
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001779 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001780 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001781 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001782 return StmtError(Diag(First->getLocStart(),
1783 diag::err_selector_element_not_lvalue)
1784 << First->getSourceRange());
1785
Mike Stump11289f42009-09-09 15:08:12 +00001786 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001787 if (FirstType.isConstQualified())
1788 Diag(ForLoc, diag::err_selector_element_const_type)
1789 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001790 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001791 if (!FirstType->isDependentType() &&
1792 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001793 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001794 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1795 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001796 }
Chad Rosier02a84392012-08-10 17:56:09 +00001797
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001798 if (CollectionExprResult.isInvalid())
1799 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001800
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001801 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001802 if (CollectionExprResult.isInvalid())
1803 return StmtError();
1804
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001805 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1806 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001807}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001808
Richard Smith02e85f32011-04-14 22:09:26 +00001809/// Finish building a variable declaration for a for-range statement.
1810/// \return true if an error occurs.
1811static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001812 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001813 // Deduce the type for the iterator variable now rather than leaving it to
1814 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001815 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001816 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001817 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001818 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001819 SemaRef.Diag(Loc, DiagID) << Init->getType();
1820 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001821 Decl->setInvalidDecl();
1822 return true;
1823 }
Richard Smith061f1e22013-04-30 21:23:01 +00001824 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001825
John McCall31168b02011-06-15 23:02:42 +00001826 // In ARC, infer lifetime.
1827 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1828 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001829 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001830 SemaRef.inferObjCARCLifetime(Decl))
1831 Decl->setInvalidDecl();
1832
Richard Smith02e85f32011-04-14 22:09:26 +00001833 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1834 /*TypeMayContainAuto=*/false);
1835 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001836 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001837 return false;
1838}
1839
Sam Panzer0f384432012-08-21 00:52:01 +00001840namespace {
1841
Richard Smith02e85f32011-04-14 22:09:26 +00001842/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001843/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001844/// nor from the diagnostics produced when analysing the implicit expressions
1845/// required in a for-range statement.
1846void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001847 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001848 CallExpr *CE = dyn_cast<CallExpr>(E);
1849 if (!CE)
1850 return;
1851 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1852 if (!D)
1853 return;
1854 SourceLocation Loc = D->getLocation();
1855
1856 std::string Description;
1857 bool IsTemplate = false;
1858 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1859 Description = SemaRef.getTemplateArgumentBindingsText(
1860 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1861 IsTemplate = true;
1862 }
1863
1864 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1865 << BEF << IsTemplate << Description << E->getType();
1866}
1867
Sam Panzer0f384432012-08-21 00:52:01 +00001868/// Build a variable declaration for a for-range statement.
1869VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1870 QualType Type, const char *Name) {
1871 DeclContext *DC = SemaRef.CurContext;
1872 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1873 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1874 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001875 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001876 Decl->setImplicit();
1877 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001878}
1879
1880}
1881
Fariborz Jahanian00213472012-07-06 19:04:04 +00001882static bool ObjCEnumerationCollection(Expr *Collection) {
1883 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001884 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001885}
1886
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001887/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001888///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001889/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001890/// A range-based for statement is equivalent to
1891///
1892/// {
1893/// auto && __range = range-init;
1894/// for ( auto __begin = begin-expr,
1895/// __end = end-expr;
1896/// __begin != __end;
1897/// ++__begin ) {
1898/// for-range-declaration = *__begin;
1899/// statement
1900/// }
1901/// }
1902///
1903/// The body of the loop is not available yet, since it cannot be analysed until
1904/// we have determined the type of the for-range-declaration.
1905StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001906Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001907 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001908 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001909 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001910 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001911
Richard Smith3249fed2013-08-21 01:40:36 +00001912 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001913 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001914
1915 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1916 assert(DS && "first part of for range not a decl stmt");
1917
1918 if (!DS->isSingleDecl()) {
1919 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1920 return StmtError();
1921 }
Richard Smith02e85f32011-04-14 22:09:26 +00001922
Richard Smith3249fed2013-08-21 01:40:36 +00001923 Decl *LoopVar = DS->getSingleDecl();
1924 if (LoopVar->isInvalidDecl() || !Range ||
1925 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1926 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001927 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001928 }
Richard Smith02e85f32011-04-14 22:09:26 +00001929
1930 // Build auto && __range = range-init
1931 SourceLocation RangeLoc = Range->getLocStart();
1932 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1933 Context.getAutoRRefDeductType(),
1934 "__range");
1935 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001936 diag::err_for_range_deduction_failure)) {
1937 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001938 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001939 }
Richard Smith02e85f32011-04-14 22:09:26 +00001940
1941 // Claim the type doesn't contain auto: we've already done the checking.
1942 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001943 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001944 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001945 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001946 if (RangeDecl.isInvalid()) {
1947 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001948 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001949 }
Richard Smith02e85f32011-04-14 22:09:26 +00001950
1951 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1953 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001954}
1955
1956/// \brief Create the initialization, compare, and increment steps for
1957/// the range-based for loop expression.
1958/// This function does not handle array-based for loops,
1959/// which are created in Sema::BuildCXXForRangeStmt.
1960///
1961/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1962/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1963/// CandidateSet and BEF are set and some non-success value is returned on
1964/// failure.
1965static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1966 Expr *BeginRange, Expr *EndRange,
1967 QualType RangeType,
1968 VarDecl *BeginVar,
1969 VarDecl *EndVar,
1970 SourceLocation ColonLoc,
1971 OverloadCandidateSet *CandidateSet,
1972 ExprResult *BeginExpr,
1973 ExprResult *EndExpr,
1974 Sema::BeginEndFunction *BEF) {
1975 DeclarationNameInfo BeginNameInfo(
1976 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1977 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1978 ColonLoc);
1979
1980 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1981 Sema::LookupMemberName);
1982 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1983
1984 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1985 // - if _RangeT is a class type, the unqualified-ids begin and end are
1986 // looked up in the scope of class _RangeT as if by class member access
1987 // lookup (3.4.5), and if either (or both) finds at least one
1988 // declaration, begin-expr and end-expr are __range.begin() and
1989 // __range.end(), respectively;
1990 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1991 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1992
1993 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1994 SourceLocation RangeLoc = BeginVar->getLocation();
1995 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1996
1997 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1998 << RangeLoc << BeginRange->getType() << *BEF;
1999 return Sema::FRS_DiagnosticIssued;
2000 }
2001 } else {
2002 // - otherwise, begin-expr and end-expr are begin(__range) and
2003 // end(__range), respectively, where begin and end are looked up with
2004 // argument-dependent lookup (3.4.2). For the purposes of this name
2005 // lookup, namespace std is an associated namespace.
2006
2007 }
2008
2009 *BEF = Sema::BEF_begin;
2010 Sema::ForRangeStatus RangeStatus =
2011 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2012 Sema::BEF_begin, BeginNameInfo,
2013 BeginMemberLookup, CandidateSet,
2014 BeginRange, BeginExpr);
2015
2016 if (RangeStatus != Sema::FRS_Success)
2017 return RangeStatus;
2018 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2019 diag::err_for_range_iter_deduction_failure)) {
2020 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2021 return Sema::FRS_DiagnosticIssued;
2022 }
2023
2024 *BEF = Sema::BEF_end;
2025 RangeStatus =
2026 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2027 Sema::BEF_end, EndNameInfo,
2028 EndMemberLookup, CandidateSet,
2029 EndRange, EndExpr);
2030 if (RangeStatus != Sema::FRS_Success)
2031 return RangeStatus;
2032 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2033 diag::err_for_range_iter_deduction_failure)) {
2034 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2035 return Sema::FRS_DiagnosticIssued;
2036 }
2037 return Sema::FRS_Success;
2038}
2039
2040/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002041/// If the attempt fails, this function will return a valid, null StmtResult
2042/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002043static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2044 SourceLocation ForLoc,
2045 Stmt *LoopVarDecl,
2046 SourceLocation ColonLoc,
2047 Expr *Range,
2048 SourceLocation RangeLoc,
2049 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002050 // Determine whether we can rebuild the for-range statement with a
2051 // dereferenced range expression.
2052 ExprResult AdjustedRange;
2053 {
2054 Sema::SFINAETrap Trap(SemaRef);
2055
2056 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2057 if (AdjustedRange.isInvalid())
2058 return StmtResult();
2059
2060 StmtResult SR =
2061 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2062 AdjustedRange.get(), RParenLoc,
2063 Sema::BFRK_Check);
2064 if (SR.isInvalid())
2065 return StmtResult();
2066 }
2067
2068 // The attempt to dereference worked well enough that it could produce a valid
2069 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2070 // case there are any other (non-fatal) problems with it.
2071 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2072 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2073 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2074 AdjustedRange.get(), RParenLoc,
2075 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002076}
2077
Richard Smith3249fed2013-08-21 01:40:36 +00002078namespace {
2079/// RAII object to automatically invalidate a declaration if an error occurs.
2080struct InvalidateOnErrorScope {
2081 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2082 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2083 ~InvalidateOnErrorScope() {
2084 if (Enabled && Trap.hasErrorOccurred())
2085 D->setInvalidDecl();
2086 }
2087
2088 DiagnosticErrorTrap Trap;
2089 Decl *D;
2090 bool Enabled;
2091};
2092}
2093
Richard Smitha05b3b52012-09-20 21:52:32 +00002094/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002095StmtResult
2096Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2097 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2098 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002099 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002100 Scope *S = getCurScope();
2101
2102 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2103 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2104 QualType RangeVarType = RangeVar->getType();
2105
2106 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2107 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2108
Richard Smith3249fed2013-08-21 01:40:36 +00002109 // If we hit any errors, mark the loop variable as invalid if its type
2110 // contains 'auto'.
2111 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2112 LoopVar->getType()->isUndeducedType());
2113
Richard Smith02e85f32011-04-14 22:09:26 +00002114 StmtResult BeginEndDecl = BeginEnd;
2115 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2116
Richard Smith27d807c2013-04-30 13:56:41 +00002117 if (RangeVarType->isDependentType()) {
2118 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002119 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002120
2121 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2122 // them in properly when we instantiate the loop.
2123 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2124 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2125 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002126 SourceLocation RangeLoc = RangeVar->getLocation();
2127
Ted Kremenekbed648e2011-10-10 22:36:28 +00002128 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2129
2130 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2131 VK_LValue, ColonLoc);
2132 if (BeginRangeRef.isInvalid())
2133 return StmtError();
2134
2135 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2136 VK_LValue, ColonLoc);
2137 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002138 return StmtError();
2139
2140 QualType AutoType = Context.getAutoDeductType();
2141 Expr *Range = RangeVar->getInit();
2142 if (!Range)
2143 return StmtError();
2144 QualType RangeType = Range->getType();
2145
2146 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002147 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002148 return StmtError();
2149
2150 // Build auto __begin = begin-expr, __end = end-expr.
2151 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2152 "__begin");
2153 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2154 "__end");
2155
2156 // Build begin-expr and end-expr and attach to __begin and __end variables.
2157 ExprResult BeginExpr, EndExpr;
2158 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2159 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2160 // __range + __bound, respectively, where __bound is the array bound. If
2161 // _RangeT is an array of unknown size or an array of incomplete type,
2162 // the program is ill-formed;
2163
2164 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002165 BeginExpr = BeginRangeRef;
2166 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002167 diag::err_for_range_iter_deduction_failure)) {
2168 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2169 return StmtError();
2170 }
2171
2172 // Find the array bound.
2173 ExprResult BoundExpr;
2174 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002175 BoundExpr = IntegerLiteral::Create(
2176 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002177 else if (const VariableArrayType *VAT =
2178 dyn_cast<VariableArrayType>(UnqAT))
2179 BoundExpr = VAT->getSizeExpr();
2180 else {
2181 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2182 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002183 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002184 }
2185
2186 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002187 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002188 BoundExpr.get());
2189 if (EndExpr.isInvalid())
2190 return StmtError();
2191 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2192 diag::err_for_range_iter_deduction_failure)) {
2193 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2194 return StmtError();
2195 }
2196 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002197 OverloadCandidateSet CandidateSet(RangeLoc,
2198 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002199 Sema::BeginEndFunction BEFFailure;
2200 ForRangeStatus RangeStatus =
2201 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2202 EndRangeRef.get(), RangeType,
2203 BeginVar, EndVar, ColonLoc, &CandidateSet,
2204 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002205
Richard Smitha05b3b52012-09-20 21:52:32 +00002206 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002207 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002208 // If the range is being built from an array parameter, emit a
2209 // a diagnostic that it is being treated as a pointer.
2210 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2211 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2212 QualType ArrayTy = PVD->getOriginalType();
2213 QualType PointerTy = PVD->getType();
2214 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2215 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2216 << RangeLoc << PVD << ArrayTy << PointerTy;
2217 Diag(PVD->getLocation(), diag::note_declared_at);
2218 return StmtError();
2219 }
2220 }
2221 }
2222
2223 // If building the range failed, try dereferencing the range expression
2224 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002225 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2226 LoopVarDecl, ColonLoc,
2227 Range, RangeLoc,
2228 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002229 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002230 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002231 }
2232
Sam Panzer0f384432012-08-21 00:52:01 +00002233 // Otherwise, emit diagnostics if we haven't already.
2234 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002235 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002236 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2237 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002238 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002239 }
2240 // Return an error if no fix was discovered.
2241 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002242 return StmtError();
2243 }
2244
Sam Panzer0f384432012-08-21 00:52:01 +00002245 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2246 "invalid range expression in for loop");
2247
2248 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002249 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2250 if (!Context.hasSameType(BeginType, EndType)) {
2251 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2252 << BeginType << EndType;
2253 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2254 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2255 }
2256
2257 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2258 // Claim the type doesn't contain auto: we've already done the checking.
2259 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002260 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002261 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002262 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2263
Ted Kremenekbed648e2011-10-10 22:36:28 +00002264 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2265 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002266 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002267 if (BeginRef.isInvalid())
2268 return StmtError();
2269
Richard Smith02e85f32011-04-14 22:09:26 +00002270 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2271 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002272 if (EndRef.isInvalid())
2273 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002274
2275 // Build and check __begin != __end expression.
2276 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2277 BeginRef.get(), EndRef.get());
2278 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2279 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2280 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002281 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2282 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002283 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2284 if (!Context.hasSameType(BeginType, EndType))
2285 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2286 return StmtError();
2287 }
2288
2289 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002290 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2291 VK_LValue, ColonLoc);
2292 if (BeginRef.isInvalid())
2293 return StmtError();
2294
Richard Smith02e85f32011-04-14 22:09:26 +00002295 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2296 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2297 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002298 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2299 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002300 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2301 return StmtError();
2302 }
2303
2304 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002305 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2306 VK_LValue, ColonLoc);
2307 if (BeginRef.isInvalid())
2308 return StmtError();
2309
Richard Smith02e85f32011-04-14 22:09:26 +00002310 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2311 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002312 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2313 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002314 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2315 return StmtError();
2316 }
2317
Richard Smitha05b3b52012-09-20 21:52:32 +00002318 // Attach *__begin as initializer for VD. Don't touch it if we're just
2319 // trying to determine whether this would be a valid range.
2320 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002321 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2322 /*TypeMayContainAuto=*/true);
2323 if (LoopVar->isInvalidDecl())
2324 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2325 }
2326 }
2327
Richard Smitha05b3b52012-09-20 21:52:32 +00002328 // Don't bother to actually allocate the result if we're just trying to
2329 // determine whether it would be valid.
2330 if (Kind == BFRK_Check)
2331 return StmtResult();
2332
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002333 return new (Context) CXXForRangeStmt(
2334 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2335 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002336}
2337
Chad Rosier02a84392012-08-10 17:56:09 +00002338/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002339/// statement.
2340StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2341 if (!S || !B)
2342 return StmtError();
2343 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002344
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002345 ForStmt->setBody(B);
2346 return S;
2347}
2348
Richard Smith02e85f32011-04-14 22:09:26 +00002349/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2350/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2351/// body cannot be performed until after the type of the range variable is
2352/// determined.
2353StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2354 if (!S || !B)
2355 return StmtError();
2356
Fariborz Jahanian00213472012-07-06 19:04:04 +00002357 if (isa<ObjCForCollectionStmt>(S))
2358 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002359
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002360 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2361 ForStmt->setBody(B);
2362
2363 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2364 diag::warn_empty_range_based_for_body);
2365
Richard Smith02e85f32011-04-14 22:09:26 +00002366 return S;
2367}
2368
Chris Lattnercab02a62011-02-17 20:34:02 +00002369StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2370 SourceLocation LabelLoc,
2371 LabelDecl *TheDecl) {
2372 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002373 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002374 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002375}
Chris Lattner1c310502007-05-31 06:00:00 +00002376
John McCalldadc5752010-08-24 06:29:42 +00002377StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002378Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002379 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002380 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002381 if (!E->isTypeDependent()) {
2382 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002383 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002384 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002385 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002386 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2387 if (ExprRes.isInvalid())
2388 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002389 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002390 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002391 return StmtError();
2392 }
John McCalla95172b2010-08-01 00:26:45 +00002393
Richard Smith945f8d32013-01-14 22:39:08 +00002394 ExprResult ExprRes = ActOnFinishFullExpr(E);
2395 if (ExprRes.isInvalid())
2396 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002397 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002398
John McCallaab3e412010-08-25 08:40:02 +00002399 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002400
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002401 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002402}
2403
John McCalldadc5752010-08-24 06:29:42 +00002404StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002405Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002406 Scope *S = CurScope->getContinueParent();
2407 if (!S) {
2408 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002409 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002410 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002411
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002412 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002413}
2414
John McCalldadc5752010-08-24 06:29:42 +00002415StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002416Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002417 Scope *S = CurScope->getBreakParent();
2418 if (!S) {
2419 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002420 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002421 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002422 if (S->isOpenMPLoopScope())
2423 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2424 << "break");
Sebastian Redl573feed2009-01-18 13:19:59 +00002425
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002426 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002427}
2428
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002429/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002430/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002431///
Douglas Gregor5d369002011-01-21 18:05:27 +00002432/// \param ReturnType If we're determining the copy elision candidate for
2433/// a return statement, this is the return type of the function. If we're
2434/// determining the copy elision candidate for a throw expression, this will
2435/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002436///
Douglas Gregor5d369002011-01-21 18:05:27 +00002437/// \param E The expression being returned from the function or block, or
2438/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002439///
Douglas Gregor86394412011-05-20 15:00:53 +00002440/// \param AllowFunctionParameter Whether we allow function parameters to
2441/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2442/// we re-use this logic to determine whether we should try to move as part of
2443/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002444///
2445/// \returns The NRVO candidate variable, if the return statement may use the
2446/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002447VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2448 Expr *E,
2449 bool AllowFunctionParameter) {
2450 if (!getLangOpts().CPlusPlus)
2451 return nullptr;
2452
2453 // - in a return statement in a function [where] ...
2454 // ... the expression is the name of a non-volatile automatic object ...
2455 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2456 if (!DR || DR->refersToEnclosingLocal())
2457 return nullptr;
2458 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2459 if (!VD)
2460 return nullptr;
2461
2462 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2463 return VD;
2464 return nullptr;
2465}
2466
2467bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2468 bool AllowFunctionParameter) {
2469 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002470 // - in a return statement in a function with ...
2471 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002472 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002473 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002474 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002475 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002476 if (!VDType->isDependentType() &&
2477 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2478 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480
John McCall03318c12011-11-11 03:57:31 +00002481 // ...object (other than a function or catch-clause parameter)...
2482 if (VD->getKind() != Decl::Var &&
2483 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002484 return false;
2485 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486
John McCall03318c12011-11-11 03:57:31 +00002487 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002488 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002489
2490 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002491 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002492
2493 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002494 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002495
2496 // Variables with higher required alignment than their type's ABI
2497 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002498 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002499 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002500 return false;
John McCall03318c12011-11-11 03:57:31 +00002501
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002502 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002503}
2504
Douglas Gregor626fbed2011-01-21 21:08:57 +00002505/// \brief Perform the initialization of a potentially-movable value, which
2506/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002507///
2508/// This routine implements C++0x [class.copy]p33, which attempts to treat
2509/// returned lvalues as rvalues in certain cases (to prefer move construction),
2510/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002511ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002512Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2513 const VarDecl *NRVOCandidate,
2514 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002515 Expr *Value,
2516 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002517 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518 // When the criteria for elision of a copy operation are met or would
2519 // be met save for the fact that the source object is a function
2520 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002521 // overload resolution to select the constructor for the copy is first
2522 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002523 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002524 if (AllowNRVO &&
2525 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002526 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002527 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002528
Douglas Gregorf282a762011-01-21 19:38:21 +00002529 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002531 = InitializationKind::CreateCopy(Value->getLocStart(),
2532 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002533 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534
2535 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002536 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002537 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002538 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002539 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002540 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2541 StepEnd = Seq.step_end();
2542 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002543 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002544 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002545
2546 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002547 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548
Douglas Gregorf282a762011-01-21 19:38:21 +00002549 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002550 = Constructor->getParamDecl(0)->getType()
2551 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552
Douglas Gregorf282a762011-01-21 19:38:21 +00002553 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002554 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002555 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2556 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002558
Douglas Gregorf282a762011-01-21 19:38:21 +00002559 // Promote "AsRvalue" to the heap, since we now need this
2560 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002561 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002562 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563
Douglas Gregorf282a762011-01-21 19:38:21 +00002564 // Complete type-checking the initialization of the return type
2565 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002566 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002567 }
2568 }
2569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570
Douglas Gregorf282a762011-01-21 19:38:21 +00002571 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002572 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002573 // (again) now with the return value expression as written.
2574 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002575 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576
Douglas Gregorf282a762011-01-21 19:38:21 +00002577 return Res;
2578}
2579
Richard Smith4db51c22013-09-25 05:02:54 +00002580/// \brief Determine whether the declared return type of the specified function
2581/// contains 'auto'.
2582static bool hasDeducedReturnType(FunctionDecl *FD) {
2583 const FunctionProtoType *FPT =
2584 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002585 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002586}
2587
Eli Friedman34b49062012-01-26 03:00:14 +00002588/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2589/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002590///
John McCalldadc5752010-08-24 06:29:42 +00002591StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002592Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2593 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002594 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002595 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002596 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002597 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002598
Richard Smith4db51c22013-09-25 05:02:54 +00002599 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2600 // In C++1y, the return type may involve 'auto'.
2601 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2602 FunctionDecl *FD = CurLambda->CallOperator;
2603 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002604 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002605
2606 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2607 assert(AT && "lost auto type from lambda return type");
2608 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2609 FD->setInvalidDecl();
2610 return StmtError();
2611 }
Alp Toker314cc812014-01-25 16:55:45 +00002612 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002613 } else if (CurCap->HasImplicitReturnType) {
2614 // For blocks/lambdas with implicit return types, we check each return
2615 // statement individually, and deduce the common return type when the block
2616 // or lambda is completed.
2617 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002618 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002619 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2620 if (Result.isInvalid())
2621 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002622 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002623
Richard Smith4db51c22013-09-25 05:02:54 +00002624 if (!CurContext->isDependentContext())
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002625 FnRetType = RetValExp->getType();
Richard Smith4db51c22013-09-25 05:02:54 +00002626 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002627 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002628 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002629 if (RetValExp) {
2630 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2631 // initializer list, because it is not an expression (even
2632 // though we represent it as one). We still deduce 'void'.
2633 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2634 << RetValExp->getSourceRange();
2635 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002636
Jordan Rosed39e5f12012-07-02 21:19:23 +00002637 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002638 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002639
2640 // Although we'll properly infer the type of the block once it's completed,
2641 // make sure we provide a return type now for better error recovery.
2642 if (CurCap->ReturnType.isNull())
2643 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002644 }
Eli Friedman34b49062012-01-26 03:00:14 +00002645 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002646
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002647 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002648 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2649 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2650 return StmtError();
2651 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002652 } else if (CapturedRegionScopeInfo *CurRegion =
2653 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2654 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2655 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002656 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002657 assert(CurLambda && "unknown kind of captured scope");
2658 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2659 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002660 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2661 return StmtError();
2662 }
2663 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002664
Steve Naroffc540d662008-09-03 18:15:37 +00002665 // Otherwise, verify that this result type matches the previous one. We are
2666 // pickier with blocks than for normal functions because we don't have GCC
2667 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002668 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002669 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002670 // Delay processing for now. TODO: there are lots of dependent
2671 // types we can conclusively prove aren't void.
2672 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002673 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002674 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002675 (RetValExp->isTypeDependent() ||
2676 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002677 if (!getLangOpts().CPlusPlus &&
2678 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002679 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002680 else {
2681 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002682 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002683 }
Steve Naroffc540d662008-09-03 18:15:37 +00002684 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002685 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002686 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2687 } else if (!RetValExp->isTypeDependent()) {
2688 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002689
John McCall5500ef22011-08-17 22:09:46 +00002690 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2691 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2692 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002693
John McCall5500ef22011-08-17 22:09:46 +00002694 // In C++ the return statement is handled via a copy initialization.
2695 // the C version of which boils down to CheckSingleAssignmentConstraints.
2696 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2697 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2698 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002699 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002700 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2701 FnRetType, RetValExp);
2702 if (Res.isInvalid()) {
2703 // FIXME: Cleanup temporaries here, anyway?
2704 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002705 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002706 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002707 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002708 } else {
2709 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002710 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002711
John McCall75f92b52011-08-17 21:34:14 +00002712 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002713 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2714 if (ER.isInvalid())
2715 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002716 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002717 }
John McCall5500ef22011-08-17 22:09:46 +00002718 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2719 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002720
Jordan Rosed39e5f12012-07-02 21:19:23 +00002721 // If we need to check for the named return value optimization,
2722 // or if we need to infer the return type,
2723 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002724 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002725 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002727 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002728}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002729
Richard Smith2a7d4812013-05-04 07:00:32 +00002730/// Deduce the return type for a function from a returned expression, per
2731/// C++1y [dcl.spec.auto]p6.
2732bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2733 SourceLocation ReturnLoc,
2734 Expr *&RetExpr,
2735 AutoType *AT) {
2736 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00002737 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith2a7d4812013-05-04 07:00:32 +00002738 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002739
Richard Smithc58f38f2013-08-14 20:16:31 +00002740 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2741 // If the deduction is for a return statement and the initializer is
2742 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002743 Diag(RetExpr->getExprLoc(),
2744 getCurLambda() ? diag::err_lambda_return_init_list
2745 : diag::err_auto_fn_return_init_list)
2746 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002747 return true;
2748 }
2749
2750 if (FD->isDependentContext()) {
2751 // C++1y [dcl.spec.auto]p12:
2752 // Return type deduction [...] occurs when the definition is
2753 // instantiated even if the function body contains a return
2754 // statement with a non-type-dependent operand.
2755 assert(AT->isDeduced() && "should have deduced to dependent type");
2756 return false;
2757 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002758 // If the deduction is for a return statement and the initializer is
2759 // a braced-init-list, the program is ill-formed.
2760 if (isa<InitListExpr>(RetExpr)) {
2761 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2762 return true;
2763 }
2764
2765 // Otherwise, [...] deduce a value for U using the rules of template
2766 // argument deduction.
2767 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2768
2769 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2770 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2771 << OrigResultType.getType() << RetExpr->getType();
2772
2773 if (DAR != DAR_Succeeded)
2774 return true;
2775 } else {
2776 // In the case of a return with no operand, the initializer is considered
2777 // to be void().
2778 //
2779 // Deduction here can only succeed if the return type is exactly 'cv auto'
2780 // or 'decltype(auto)', so just check for that case directly.
2781 if (!OrigResultType.getType()->getAs<AutoType>()) {
2782 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2783 << OrigResultType.getType();
2784 return true;
2785 }
2786 // We always deduce U = void in this case.
2787 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2788 if (Deduced.isNull())
2789 return true;
2790 }
2791
2792 // If a function with a declared return type that contains a placeholder type
2793 // has multiple return statements, the return type is deduced for each return
2794 // statement. [...] if the type deduced is not the same in each deduction,
2795 // the program is ill-formed.
2796 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2797 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002798 if (!FD->isDependentContext() &&
2799 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002800 const LambdaScopeInfo *LambdaSI = getCurLambda();
2801 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2802 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2803 << NewAT->getDeducedType() << AT->getDeducedType()
2804 << true /*IsLambda*/;
2805 } else {
2806 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2807 << (AT->isDecltypeAuto() ? 1 : 0)
2808 << NewAT->getDeducedType() << AT->getDeducedType();
2809 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002810 return true;
2811 }
2812 } else if (!FD->isInvalidDecl()) {
2813 // Update all declarations of the function to have the deduced return type.
2814 Context.adjustDeducedFunctionResultType(FD, Deduced);
2815 }
2816
2817 return false;
2818}
2819
John McCalldadc5752010-08-24 06:29:42 +00002820StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002821Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2822 Scope *CurScope) {
2823 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2824 if (R.isInvalid()) {
2825 return R;
2826 }
2827
2828 if (VarDecl *VD =
2829 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2830 CurScope->addNRVOCandidate(VD);
2831 } else {
2832 CurScope->setNoNRVO();
2833 }
2834
2835 return R;
2836}
2837
2838StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002839 // Check for unexpanded parameter packs.
2840 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2841 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002842
Eli Friedman34b49062012-01-26 03:00:14 +00002843 if (isa<CapturingScopeInfo>(getCurFunction()))
2844 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002845
Chris Lattner79413952008-12-04 23:50:19 +00002846 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002847 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002848 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002849 bool isObjCMethod = false;
2850
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002851 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002852 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002853 if (FD->hasAttrs())
2854 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002855 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002856 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002857 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002858 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002859 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002860 isObjCMethod = true;
2861 if (MD->hasAttrs())
2862 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002863 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2864 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002865 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002866 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002867 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2868 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002869 }
2870 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002871 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002872
Richard Smith2a7d4812013-05-04 07:00:32 +00002873 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2874 // deduction.
Richard Smith2a7d4812013-05-04 07:00:32 +00002875 if (getLangOpts().CPlusPlus1y) {
2876 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2877 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002878 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002879 FD->setInvalidDecl();
2880 return StmtError();
2881 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002882 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002883 }
2884 }
2885 }
2886
Richard Smithc58f38f2013-08-14 20:16:31 +00002887 bool HasDependentReturnType = FnRetType->isDependentType();
2888
Craig Topperc3ec1492014-05-26 06:22:03 +00002889 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002890 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002891 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002892 if (isa<InitListExpr>(RetValExp)) {
2893 // We simply never allow init lists as the return value of void
2894 // functions. This is compatible because this was never allowed before,
2895 // so there's no legacy code to deal with.
2896 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2897 int FunctionKind = 0;
2898 if (isa<ObjCMethodDecl>(CurDecl))
2899 FunctionKind = 1;
2900 else if (isa<CXXConstructorDecl>(CurDecl))
2901 FunctionKind = 2;
2902 else if (isa<CXXDestructorDecl>(CurDecl))
2903 FunctionKind = 3;
2904
2905 Diag(ReturnLoc, diag::err_return_init_list)
2906 << CurDecl->getDeclName() << FunctionKind
2907 << RetValExp->getSourceRange();
2908
2909 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002910 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002911 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002912 // C99 6.8.6.4p1 (ext_ since GCC warns)
2913 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002914 if (RetValExp->getType()->isVoidType()) {
2915 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2916 if (isa<CXXConstructorDecl>(CurDecl) ||
2917 isa<CXXDestructorDecl>(CurDecl))
2918 D = diag::err_ctor_dtor_returns_void;
2919 else
2920 D = diag::ext_return_has_void_expr;
2921 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002922 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002923 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002924 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00002925 if (Result.isInvalid())
2926 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002927 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002928 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002929 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002930 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002931 // return of void in constructor/destructor is illegal in C++.
2932 if (D == diag::err_ctor_dtor_returns_void) {
2933 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2934 Diag(ReturnLoc, D)
2935 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
2936 << RetValExp->getSourceRange();
2937 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002938 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002939 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002940 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002941 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002942
2943 int FunctionKind = 0;
2944 if (isa<ObjCMethodDecl>(CurDecl))
2945 FunctionKind = 1;
2946 else if (isa<CXXConstructorDecl>(CurDecl))
2947 FunctionKind = 2;
2948 else if (isa<CXXDestructorDecl>(CurDecl))
2949 FunctionKind = 3;
2950
Nick Lewycky1be750a2011-06-01 07:44:31 +00002951 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002952 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002953 << RetValExp->getSourceRange();
2954 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002955 }
Mike Stump11289f42009-09-09 15:08:12 +00002956
Sebastian Redleef474c2012-02-22 10:50:08 +00002957 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002958 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2959 if (ER.isInvalid())
2960 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002961 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00002962 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964
Craig Topperc3ec1492014-05-26 06:22:03 +00002965 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00002966 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002967 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2968 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002969 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002970
2971 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002972 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002973 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002974 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002975 Result = new (Context) ReturnStmt(ReturnLoc);
2976 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00002977 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00002978 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002979
2980 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
2981
2982 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2983 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2984 // function return.
2985
2986 // In C++ the return statement is handled via a copy initialization,
2987 // the C version of which boils down to CheckSingleAssignmentConstraints.
2988 if (RetValExp)
2989 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00002990 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002991 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002992 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00002993 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002994 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002995 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00002996 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002997 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00002998 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002999 return StmtError();
3000 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003001 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003002
3003 // If we have a related result type, we need to implicitly
3004 // convert back to the formal result type. We can't pretend to
3005 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003006 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003007 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003008 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3009 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003010 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3011 if (Res.isInvalid()) {
3012 // FIXME: Clean up temporaries here anyway?
3013 return StmtError();
3014 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003015 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003016 }
3017
Artyom Skrobov9f213442014-01-24 11:10:39 +00003018 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3019 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
John McCallacf0ee52010-10-08 02:01:28 +00003022 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003023 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3024 if (ER.isInvalid())
3025 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003026 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003027 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003028 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030
3031 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003032 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003033 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003034 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003035
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003036 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003037}
3038
John McCalldadc5752010-08-24 06:29:42 +00003039StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003040Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003041 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003042 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003043 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003044 if (Var && Var->isInvalidDecl())
3045 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003046
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003047 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003048}
3049
John McCalldadc5752010-08-24 06:29:42 +00003050StmtResult
John McCallb268a282010-08-23 23:25:46 +00003051Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003052 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003053}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003054
John McCalldadc5752010-08-24 06:29:42 +00003055StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003056Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003057 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003058 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003059 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3060
John McCallaab3e412010-08-25 08:40:02 +00003061 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003062 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003063 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3064 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003065}
3066
John McCall0bd3e402012-05-08 21:41:25 +00003067StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003068 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003069 ExprResult Result = DefaultLvalueConversion(Throw);
3070 if (Result.isInvalid())
3071 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003072
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003073 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003074 if (Result.isInvalid())
3075 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003076 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003077
Douglas Gregor2900c162010-04-22 21:44:01 +00003078 QualType ThrowType = Throw->getType();
3079 // Make sure the expression type is an ObjC pointer or "void *".
3080 if (!ThrowType->isDependentType() &&
3081 !ThrowType->isObjCObjectPointerType()) {
3082 const PointerType *PT = ThrowType->getAs<PointerType>();
3083 if (!PT || !PT->getPointeeType()->isVoidType())
3084 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3085 << Throw->getType() << Throw->getSourceRange());
3086 }
3087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003088
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003089 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003090}
3091
John McCalldadc5752010-08-24 06:29:42 +00003092StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003093Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003094 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003095 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003096 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3097
John McCallb268a282010-08-23 23:25:46 +00003098 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003099 // @throw without an expression designates a rethrow (which much occur
3100 // in the context of an @catch clause).
3101 Scope *AtCatchParent = CurScope;
3102 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3103 AtCatchParent = AtCatchParent->getParent();
3104 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003105 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003106 }
John McCallb268a282010-08-23 23:25:46 +00003107 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003108}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003109
John McCalld9bb7432011-07-27 21:50:02 +00003110ExprResult
3111Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3112 ExprResult result = DefaultLvalueConversion(operand);
3113 if (result.isInvalid())
3114 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003115 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003116
3117 // Make sure the expression type is an ObjC pointer or "void *".
3118 QualType type = operand->getType();
3119 if (!type->isDependentType() &&
3120 !type->isObjCObjectPointerType()) {
3121 const PointerType *pointerType = type->getAs<PointerType>();
3122 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3123 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3124 << type << operand->getSourceRange();
3125 }
3126
3127 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003128 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003129}
3130
John McCalldadc5752010-08-24 06:29:42 +00003131StmtResult
John McCallb268a282010-08-23 23:25:46 +00003132Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3133 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003134 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003135 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003136 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003137}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003138
3139/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3140/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003141StmtResult
John McCall48871652010-08-21 09:40:31 +00003142Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003143 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003144 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003145 return new (Context)
3146 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003147}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003148
John McCall31168b02011-06-15 23:02:42 +00003149StmtResult
3150Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3151 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003152 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003153}
3154
Dan Gohman28ade552010-07-26 21:25:24 +00003155namespace {
3156
Sebastian Redl63c4da02009-07-29 17:15:45 +00003157class TypeWithHandler {
3158 QualType t;
3159 CXXCatchStmt *stmt;
3160public:
3161 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3162 : t(type), stmt(statement) {}
3163
John McCall8ccfcb52009-09-24 19:53:00 +00003164 // An arbitrary order is fine as long as it places identical
3165 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003166 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003167 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003168 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003169 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003170 return false;
3171 else
3172 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3173 }
Mike Stump11289f42009-09-09 15:08:12 +00003174
Sebastian Redl63c4da02009-07-29 17:15:45 +00003175 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003176 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003177 }
Mike Stump11289f42009-09-09 15:08:12 +00003178
Sebastian Redl63c4da02009-07-29 17:15:45 +00003179 CXXCatchStmt *getCatchStmt() const { return stmt; }
3180 SourceLocation getTypeSpecStartLoc() const {
3181 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3182 }
3183};
3184
Dan Gohman28ade552010-07-26 21:25:24 +00003185}
3186
Sebastian Redl9b244a82008-12-22 21:35:02 +00003187/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3188/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003189StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3190 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003191 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003192 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003193 !getSourceManager().isInSystemHeader(TryLoc))
3194 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003195
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003196 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3197 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3198
Robert Wilhelmcafda822013-08-22 09:20:03 +00003199 const unsigned NumHandlers = Handlers.size();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003200 assert(NumHandlers > 0 &&
3201 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003202
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003203 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003204
3205 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003206 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003207 if (!Handler->getExceptionDecl()) {
3208 if (i < NumHandlers - 1)
3209 return StmtError(Diag(Handler->getLocStart(),
3210 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003211
Sebastian Redl63c4da02009-07-29 17:15:45 +00003212 continue;
3213 }
Mike Stump11289f42009-09-09 15:08:12 +00003214
Sebastian Redl63c4da02009-07-29 17:15:45 +00003215 const QualType CaughtType = Handler->getCaughtType();
3216 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3217 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003218 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003219
3220 // Detect handlers for the same type as an earlier one.
3221 if (NumHandlers > 1) {
3222 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003223
Sebastian Redl63c4da02009-07-29 17:15:45 +00003224 TypeWithHandler prev = TypesWithHandlers[0];
3225 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3226 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003227
Sebastian Redl63c4da02009-07-29 17:15:45 +00003228 if (curr == prev) {
3229 Diag(curr.getTypeSpecStartLoc(),
3230 diag::warn_exception_caught_by_earlier_handler)
3231 << curr.getCatchStmt()->getCaughtType().getAsString();
3232 Diag(prev.getTypeSpecStartLoc(),
3233 diag::note_previous_exception_handler)
3234 << prev.getCatchStmt()->getCaughtType().getAsString();
3235 }
Mike Stump11289f42009-09-09 15:08:12 +00003236
Sebastian Redl63c4da02009-07-29 17:15:45 +00003237 prev = curr;
3238 }
3239 }
Mike Stump11289f42009-09-09 15:08:12 +00003240
John McCallaab3e412010-08-25 08:40:02 +00003241 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003242
Sebastian Redl9b244a82008-12-22 21:35:02 +00003243 // FIXME: We should detect handlers that cannot catch anything because an
3244 // earlier handler catches a superclass. Need to find a method that is not
3245 // quadratic for this.
3246 // Neither of these are explicitly forbidden, but every compiler detects them
3247 // and warns.
3248
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003249 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003250}
John Wiegley1c0675e2011-04-28 01:08:34 +00003251
Warren Huntf6be4cb2014-07-25 20:52:51 +00003252StmtResult
3253Sema::ActOnSEHTryBlock(bool IsCXXTry,
3254 SourceLocation TryLoc,
3255 Stmt *TryBlock,
3256 Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003257 assert(TryBlock && Handler);
3258
3259 getCurFunction()->setHasBranchProtectedScope();
3260
Warren Huntf6be4cb2014-07-25 20:52:51 +00003261 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003262}
3263
3264StmtResult
3265Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3266 Expr *FilterExpr,
3267 Stmt *Block) {
3268 assert(FilterExpr && Block);
3269
3270 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003271 return StmtError(Diag(FilterExpr->getExprLoc(),
3272 diag::err_filter_expression_integral)
3273 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003274 }
3275
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003276 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003277}
3278
3279StmtResult
3280Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3281 Stmt *Block) {
3282 assert(Block);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003283 return SEHFinallyStmt::Create(Context,Loc,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003284}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003285
Nico Weberc7d05962014-07-06 22:32:59 +00003286StmtResult
3287Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003288 Scope *SEHTryParent = CurScope;
3289 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3290 SEHTryParent = SEHTryParent->getParent();
3291 if (!SEHTryParent)
3292 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3293
Nico Weber9b982072014-07-07 00:12:30 +00003294 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003295}
3296
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003297StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3298 bool IsIfExists,
3299 NestedNameSpecifierLoc QualifierLoc,
3300 DeclarationNameInfo NameInfo,
3301 Stmt *Nested)
3302{
3303 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003304 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003305 cast<CompoundStmt>(Nested));
3306}
3307
3308
Chad Rosier02a84392012-08-10 17:56:09 +00003309StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003310 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003311 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003312 UnqualifiedId &Name,
3313 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003314 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003315 SS.getWithLocInContext(Context),
3316 GetNameFromUnqualifiedId(Name),
3317 Nested);
3318}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003319
3320RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003321Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3322 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003323 DeclContext *DC = CurContext;
3324 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3325 DC = DC->getParent();
3326
Craig Topperc3ec1492014-05-26 06:22:03 +00003327 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003328 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003329 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3330 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003331 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003332 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003333
3334 DC->addDecl(RD);
3335 RD->setImplicit();
3336 RD->startDefinition();
3337
Alexey Bataev9959db52014-05-06 10:08:46 +00003338 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003339 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003340 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003341 return RD;
3342}
3343
3344static void buildCapturedStmtCaptureList(
3345 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3346 SmallVectorImpl<Expr *> &CaptureInits,
3347 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3348
3349 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3350 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3351
3352 if (Cap->isThisCapture()) {
3353 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3354 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003355 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003356 continue;
3357 }
3358
3359 assert(Cap->isReferenceCapture() &&
3360 "non-reference capture not yet implemented");
3361
3362 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3363 CapturedStmt::VCK_ByRef,
3364 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003365 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003366 }
3367}
3368
3369void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003370 CapturedRegionKind Kind,
3371 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003372 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003373 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003374
Alexey Bataev9959db52014-05-06 10:08:46 +00003375 // Build the context parameter
3376 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3377 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3378 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3379 ImplicitParamDecl *Param
3380 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3381 DC->addDecl(Param);
3382
3383 CD->setContextParam(0, Param);
3384
3385 // Enter the capturing scope for this captured region.
3386 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3387
3388 if (CurScope)
3389 PushDeclContext(CurScope, CD);
3390 else
3391 CurContext = CD;
3392
3393 PushExpressionEvaluationContext(PotentiallyEvaluated);
3394}
3395
3396void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3397 CapturedRegionKind Kind,
3398 ArrayRef<CapturedParamNameType> Params) {
3399 CapturedDecl *CD = nullptr;
3400 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3401
3402 // Build the context parameter
3403 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3404 bool ContextIsFound = false;
3405 unsigned ParamNum = 0;
3406 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3407 E = Params.end();
3408 I != E; ++I, ++ParamNum) {
3409 if (I->second.isNull()) {
3410 assert(!ContextIsFound &&
3411 "null type has been found already for '__context' parameter");
3412 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3413 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3414 ImplicitParamDecl *Param
3415 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3416 DC->addDecl(Param);
3417 CD->setContextParam(ParamNum, Param);
3418 ContextIsFound = true;
3419 } else {
3420 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3421 ImplicitParamDecl *Param
3422 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3423 DC->addDecl(Param);
3424 CD->setParam(ParamNum, Param);
3425 }
3426 }
3427 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003428 if (!ContextIsFound) {
3429 // Add __context implicitly if it is not specified.
3430 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3431 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3432 ImplicitParamDecl *Param =
3433 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3434 DC->addDecl(Param);
3435 CD->setContextParam(ParamNum, Param);
3436 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003437 // Enter the capturing scope for this captured region.
3438 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3439
3440 if (CurScope)
3441 PushDeclContext(CurScope, CD);
3442 else
3443 CurContext = CD;
3444
3445 PushExpressionEvaluationContext(PotentiallyEvaluated);
3446}
3447
Wei Pan17fbf6e2013-05-04 03:59:06 +00003448void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003449 DiscardCleanupsInEvaluationContext();
3450 PopExpressionEvaluationContext();
3451
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003452 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3453 RecordDecl *Record = RSI->TheRecordDecl;
3454 Record->setInvalidDecl();
3455
Aaron Ballman62e47c42014-03-10 13:43:55 +00003456 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003457 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3458 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003459
Wei Pan17fbf6e2013-05-04 03:59:06 +00003460 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003461 PopFunctionScopeInfo();
3462}
3463
3464StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3465 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3466
3467 SmallVector<CapturedStmt::Capture, 4> Captures;
3468 SmallVector<Expr *, 4> CaptureInits;
3469 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3470
3471 CapturedDecl *CD = RSI->TheCapturedDecl;
3472 RecordDecl *RD = RSI->TheRecordDecl;
3473
Wei Pan17fbf6e2013-05-04 03:59:06 +00003474 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3475 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003476 CaptureInits, CD, RD);
3477
3478 CD->setBody(Res->getCapturedStmt());
3479 RD->completeDefinition();
3480
Wei Pan17fbf6e2013-05-04 03:59:06 +00003481 DiscardCleanupsInEvaluationContext();
3482 PopExpressionEvaluationContext();
3483
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003484 PopDeclContext();
3485 PopFunctionScopeInfo();
3486
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003487 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003488}