blob: 22ed93082065dfcca3b692435ca448317b6234d1 [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000022#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000023#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000025#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000031#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000036using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000037using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000038
Richard Smith945f8d32013-01-14 22:39:08 +000039StmtResult Sema::ActOnExprStmt(ExprResult FE) {
40 if (FE.isInvalid())
41 return StmtError();
42
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
45 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000046 return StmtError();
47
Chris Lattner903eb512008-07-25 23:18:17 +000048 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000051
Chris Lattner903eb512008-07-25 23:18:17 +000052 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000053 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000054}
55
56
John McCalleaef89b2013-03-22 02:10:40 +000057StmtResult Sema::ActOnExprStmtError() {
58 DiscardCleanupsInEvaluationContext();
59 return StmtError();
60}
61
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000062StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000063 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000065}
66
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000067StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
68 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000069 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000070
Chris Lattnercbafe8d2009-04-12 20:13:14 +000071 // If we have an invalid decl, just return an error.
72 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000073
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000074 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000075}
Chris Lattneraf8d5812006-11-10 05:07:45 +000076
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000077void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000078 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000079
Douglas Gregor2eb1c572013-04-08 20:52:24 +000080 // If we don't have a declaration, or we have an invalid declaration,
81 // just return.
82 if (DG.isNull() || !DG.isSingleDecl())
83 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 Decl *decl = DG.getSingleDecl();
86 if (!decl || decl->isInvalidDecl())
87 return;
88
89 // Only variable declarations are permitted.
90 VarDecl *var = dyn_cast<VarDecl>(decl);
91 if (!var) {
92 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
93 decl->setInvalidDecl();
94 return;
95 }
John McCall31168b02011-06-15 23:02:42 +000096
John McCalld4631322011-06-17 06:42:21 +000097 // foreach variables are never actually initialized in the way that
98 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +000099 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // In ARC, we don't need to retain the iteration variable of a fast
102 // enumeration loop. Rather than actually trying to catch that
103 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000104 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000105 QualType type = var->getType();
106
107 // Only do this if we inferred the lifetime. Inferred lifetime
108 // will show up as a local qualifier because explicit lifetime
109 // should have shown up as an AttributedType instead.
110 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
111 // Add 'const' and mark the variable as pseudo-strong.
112 var->setType(type.withConst());
113 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000114 }
115 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000116}
117
Richard Trieu99e1c952014-03-11 03:11:08 +0000118/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
119/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000120///
121/// Adding a cast to void (or other expression wrappers) will prevent the
122/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000123static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000125 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000126
127 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000128 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000129 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
Richard Trieu99e1c952014-03-11 03:11:08 +0000131 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 switch (Op->getOperator()) {
137 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000138 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000139 case OO_EqualEqual:
140 case OO_ExclaimEqual:
141 IsRelational = false;
142 break;
143 case OO_Less:
144 case OO_Greater:
145 case OO_GreaterEqual:
146 case OO_LessEqual:
147 IsRelational = true;
148 break;
149 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000150
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000151 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000152 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
153 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154 } else {
155 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000156 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000157 }
158
159 // Suppress warnings when the operator, suspicious as it may be, comes from
160 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000161 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000162 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000163
Chandler Carruthe2669392011-08-17 09:34:37 +0000164 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000165 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000166
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000167 // If the LHS is a plausible entity to assign to, provide a fixit hint to
168 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000170 if (IsNotEqual)
171 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
172 << FixItHint::CreateReplacement(Loc, "|=");
173 else
174 S.Diag(Loc, diag::note_equality_comparison_to_assign)
175 << FixItHint::CreateReplacement(Loc, "=");
176 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000177
178 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000179}
180
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000181void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000182 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
183 return DiagnoseUnusedExprResult(Label->getSubStmt());
184
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000185 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186 if (!E)
187 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000188
189 // If we are in an unevaluated expression context, then there can be no unused
190 // results because the results aren't expected to be used in the first place.
191 if (isUnevaluatedContext())
192 return;
193
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000194 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000195 // In most cases, we don't want to warn if the expression is written in a
196 // macro body, or if the macro comes from a system header. If the offending
197 // expression is a call to a function with the warn_unused_result attribute,
198 // we warn no matter the location. Because of the order in which the various
199 // checks need to happen, we factor out the macro-related test here.
200 bool ShouldSuppress =
201 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
202 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000203
Eli Friedmanc11535c2012-05-24 00:47:05 +0000204 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000205 SourceLocation Loc;
206 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000207 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208 return;
Mike Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattner6dc7e572012-08-31 22:39:21 +0000210 // If this is a GNU statement expression expanded from a macro, it is probably
211 // unused because it is a function-like macro that can be used as either an
212 // expression or statement. Don't warn, because it is almost certainly a
213 // false positive.
214 if (isa<StmtExpr>(E) && Loc.isMacroID())
215 return;
216
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000217 // Okay, we have an unused result. Depending on what the base expression is,
218 // we might want to make a more specific diagnostic. Check for one of these
219 // cases now.
220 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000221 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000222 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000223 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
224 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000225
Chandler Carruthe2669392011-08-17 09:34:37 +0000226 if (DiagnoseUnusedComparison(*this, E))
227 return;
228
Eli Friedmanc11535c2012-05-24 00:47:05 +0000229 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000230 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000231 if (E->getType()->isVoidType())
232 return;
233
Chris Lattner1a6babf2009-10-13 04:53:48 +0000234 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000235 // a more specific message to make it clear what is happening. If the call
236 // is written in a macro body, only warn if it has the warn_unused_result
237 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000238 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000239 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000240 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000241 return;
242 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000243 if (ShouldSuppress)
244 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000245 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000246 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
247 return;
248 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000249 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000250 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
251 return;
252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000253 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000254 } else if (ShouldSuppress)
255 return;
256
257 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000258 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000259 Diag(Loc, diag::err_arc_unused_init_message) << R1;
260 return;
261 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000262 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000263 if (MD) {
264 if (MD->hasAttr<WarnUnusedResultAttr>()) {
265 Diag(Loc, diag::warn_unused_result) << R1 << R2;
266 return;
267 }
268 if (MD->isPropertyAccessor()) {
269 Diag(Loc, diag::warn_unused_property_expr);
270 return;
271 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000272 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
274 const Expr *Source = POE->getSyntacticForm();
275 if (isa<ObjCSubscriptRefExpr>(Source))
276 DiagID = diag::warn_unused_container_subscript_expr;
277 else
278 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000279 } else if (const CXXFunctionalCastExpr *FC
280 = dyn_cast<CXXFunctionalCastExpr>(E)) {
281 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
282 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
283 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
John McCall2351cb92010-04-06 22:24:14 +0000285 // Diagnose "(void*) blah" as a typo for "(void) blah".
286 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
287 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
288 QualType T = TI->getType();
289
290 // We really do want to use the non-canonical type here.
291 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000292 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000293
294 Diag(Loc, diag::warn_unused_voidptr)
295 << FixItHint::CreateRemoval(TL.getStarLoc());
296 return;
297 }
298 }
299
Eli Friedmanc11535c2012-05-24 00:47:05 +0000300 if (E->isGLValue() && E->getType().isVolatileQualified()) {
301 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
302 return;
303 }
304
Craig Topperc3ec1492014-05-26 06:22:03 +0000305 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000306}
307
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000308void Sema::ActOnStartOfCompoundStmt() {
309 PushCompoundScope();
310}
311
312void Sema::ActOnFinishOfCompoundStmt() {
313 PopCompoundScope();
314}
315
316sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
317 return getCurFunction()->CompoundScopes.back();
318}
319
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000320StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
321 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
322 const unsigned NumElts = Elts.size();
323
Chris Lattnerd864daf2007-08-27 04:29:41 +0000324 // If we're in C89 mode, check that we don't have any decls after stmts. If
325 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000326 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000327 // Note that __extension__ can be around a decl.
328 unsigned i = 0;
329 // Skip over all declarations.
330 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
331 /*empty*/;
332
333 // We found the end of the list or a statement. Scan for another declstmt.
334 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
335 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000336
Chris Lattnerd864daf2007-08-27 04:29:41 +0000337 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000338 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000339 Diag(D->getLocation(), diag::ext_mixed_decls_code);
340 }
341 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000342 // Warn about unused expressions in statements.
343 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000344 // Ignore statements that are last in a statement expression.
345 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000346 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000347
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000348 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000349 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000350
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000351 // Check for suspicious empty body (null statement) in `for' and `while'
352 // statements. Don't do anything for template instantiations, this just adds
353 // noise.
354 if (NumElts != 0 && !CurrentInstantiationScope &&
355 getCurCompoundScope().HasEmptyLoopBodies) {
356 for (unsigned i = 0; i != NumElts - 1; ++i)
357 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
358 }
359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000360 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000361}
362
John McCalldadc5752010-08-24 06:29:42 +0000363StmtResult
John McCallb268a282010-08-23 23:25:46 +0000364Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
365 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000366 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000367 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000368
John McCallaab3e412010-08-25 08:40:02 +0000369 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000370 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000371 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000372 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000373
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000374 ExprResult LHS =
375 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
376 if (!getLangOpts().CPlusPlus11)
377 return VerifyIntegerConstantExpression(E);
378 if (Expr *CondExpr =
379 getCurFunction()->SwitchStack.back()->getCond()) {
380 QualType CondType = CondExpr->getType();
381 llvm::APSInt TempVal;
382 return CheckConvertedConstantExpression(E, CondType, TempVal,
383 CCEK_CaseValue);
384 }
385 return ExprError();
386 });
387 if (LHS.isInvalid())
388 return StmtError();
389 LHSVal = LHS.get();
390
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000391 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000392 // C99 6.8.4.2p3: The expression shall be an integer constant.
393 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000394 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000395 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000396 if (!LHSVal)
397 return StmtError();
398 }
Richard Smithf8379a02012-01-18 23:55:52 +0000399
400 // GCC extension: The expression shall be an integer constant.
401
Richard Smithf4c51d92012-02-04 09:53:13 +0000402 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000403 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000404 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000405 }
406 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000407
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000408 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000409 getLangOpts().CPlusPlus11);
410 if (LHS.isInvalid())
411 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000412
Richard Smith5b555da2014-11-20 01:24:12 +0000413 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
414 getLangOpts().CPlusPlus11)
415 : ExprResult();
416 if (RHS.isInvalid())
417 return StmtError();
418
419 CaseStmt *CS = new (Context)
420 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000421 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000422 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000423}
424
Chris Lattner34a22092009-03-04 04:23:07 +0000425/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000426void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000427 DiagnoseUnusedExprResult(SubStmt);
428
Chris Lattner34a22092009-03-04 04:23:07 +0000429 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000430 CS->setSubStmt(SubStmt);
431}
432
John McCalldadc5752010-08-24 06:29:42 +0000433StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000434Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000435 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000436 DiagnoseUnusedExprResult(SubStmt);
437
John McCallaab3e412010-08-25 08:40:02 +0000438 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000439 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000441 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000442
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000443 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000444 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000445 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000446}
447
John McCalldadc5752010-08-24 06:29:42 +0000448StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000449Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
450 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000451 // If the label was multiply defined, reject it now.
452 if (TheDecl->getStmt()) {
453 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
454 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000455 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000456 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000457
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000458 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000459 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
460 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000461 if (!TheDecl->isGnuLocal()) {
462 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000463 if (!TheDecl->isMSAsmLabel()) {
464 // Don't update the location of MS ASM labels. These will result in
465 // a diagnostic, and changing the location here will mess that up.
466 TheDecl->setLocation(IdentLoc);
467 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000468 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000469 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000470}
471
Richard Smithc202b282012-04-14 00:33:13 +0000472StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000473 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000474 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000475 // Fill in the declaration and return it.
476 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000477 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000478}
479
John McCalldadc5752010-08-24 06:29:42 +0000480StmtResult
John McCall48871652010-08-21 09:40:31 +0000481Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000482 Stmt *thenStmt, SourceLocation ElseLoc,
483 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000484 // If the condition was invalid, discard the if statement. We could recover
485 // better by replacing it with a valid expr, but don't do that yet.
486 if (!CondVal.get() && !CondVar) {
487 getCurFunction()->setHasDroppedStmt();
488 return StmtError();
489 }
490
John McCalldadc5752010-08-24 06:29:42 +0000491 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000492
Craig Topperc3ec1492014-05-26 06:22:03 +0000493 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000494 if (CondVar) {
495 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000496 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000497 if (CondResult.isInvalid())
498 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000499 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000500 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000501 if (!ConditionExpr)
502 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000504 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000505
John McCallb268a282010-08-23 23:25:46 +0000506 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000507 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
508 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000509 }
510
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000511 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000512
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000513 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
514 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000515}
Steve Naroff86272ea2007-05-29 02:14:17 +0000516
Chris Lattner67998452007-08-23 18:29:20 +0000517namespace {
518 struct CaseCompareFunctor {
519 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
520 const llvm::APSInt &RHS) {
521 return LHS.first < RHS;
522 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000523 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
524 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
525 return LHS.first < RHS.first;
526 }
Chris Lattner67998452007-08-23 18:29:20 +0000527 bool operator()(const llvm::APSInt &LHS,
528 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
529 return LHS < RHS.first;
530 }
531 };
532}
533
Chris Lattner4b2ff022007-09-21 18:15:22 +0000534/// CmpCaseVals - Comparison predicate for sorting case values.
535///
536static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
537 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
538 if (lhs.first < rhs.first)
539 return true;
540
541 if (lhs.first == rhs.first &&
542 lhs.second->getCaseLoc().getRawEncoding()
543 < rhs.second->getCaseLoc().getRawEncoding())
544 return true;
545 return false;
546}
547
Douglas Gregorbd6839732010-02-08 22:24:16 +0000548/// CmpEnumVals - Comparison predicate for sorting enumeration values.
549///
550static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
551 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
552{
553 return lhs.first < rhs.first;
554}
555
556/// EqEnumVals - Comparison preficate for uniqing enumeration values.
557///
558static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
559 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
560{
561 return lhs.first == rhs.first;
562}
563
Chris Lattnera96d4272009-10-16 16:45:22 +0000564/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
565/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000566static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
567 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
568 expr = cleanups->getSubExpr();
569 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
570 if (impcast->getCastKind() != CK_IntegralCast) break;
571 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000572 }
573 return expr->getType();
574}
575
John McCalldadc5752010-08-24 06:29:42 +0000576StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000578 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000579 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000580
Craig Topperc3ec1492014-05-26 06:22:03 +0000581 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000582 if (CondVar) {
583 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000584 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
585 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000586 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000588 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
John McCallb268a282010-08-23 23:25:46 +0000591 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000592 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregore2b37442012-05-04 22:38:52 +0000594 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
595 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000596
Douglas Gregore2b37442012-05-04 22:38:52 +0000597 public:
598 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000599 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
600 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000601
Craig Toppere14c0f82014-03-12 04:55:44 +0000602 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
603 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000604 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
605 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000606
Craig Toppere14c0f82014-03-12 04:55:44 +0000607 SemaDiagnosticBuilder diagnoseIncomplete(
608 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000609 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
610 << T << Cond->getSourceRange();
611 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000612
Craig Toppere14c0f82014-03-12 04:55:44 +0000613 SemaDiagnosticBuilder diagnoseExplicitConv(
614 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000615 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
616 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000617
Craig Toppere14c0f82014-03-12 04:55:44 +0000618 SemaDiagnosticBuilder noteExplicitConv(
619 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000620 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
621 << ConvTy->isEnumeralType() << ConvTy;
622 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000623
Craig Toppere14c0f82014-03-12 04:55:44 +0000624 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
625 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000626 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
627 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000628
Craig Toppere14c0f82014-03-12 04:55:44 +0000629 SemaDiagnosticBuilder noteAmbiguous(
630 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000631 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
632 << ConvTy->isEnumeralType() << ConvTy;
633 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000634
Craig Toppere14c0f82014-03-12 04:55:44 +0000635 SemaDiagnosticBuilder diagnoseConversion(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000637 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000638 }
639 } SwitchDiagnoser(Cond);
640
Richard Smithccc11812013-05-21 19:05:48 +0000641 CondResult =
642 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000643 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000644 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
John McCall5939b162011-08-06 07:30:58 +0000646 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
647 CondResult = UsualUnaryConversions(Cond);
648 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000649 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000650
John McCall48871652010-08-21 09:40:31 +0000651 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000652 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000653 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000654 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000655 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000656 }
John McCalla95172b2010-08-01 00:26:45 +0000657
John McCallaab3e412010-08-25 08:40:02 +0000658 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
John McCallb268a282010-08-23 23:25:46 +0000660 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000661 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000662 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000663}
664
Gabor Greif16e02862010-10-01 22:05:14 +0000665static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000666 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000667 Val.setIsSigned(IsSigned);
668}
669
Richard Smith077d0832014-08-04 00:40:48 +0000670/// Check the specified case value is in range for the given unpromoted switch
671/// type.
672static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
673 unsigned UnpromotedWidth, bool UnpromotedSign) {
674 // If the case value was signed and negative and the switch expression is
675 // unsigned, don't bother to warn: this is implementation-defined behavior.
676 // FIXME: Introduce a second, default-ignored warning for this case?
677 if (UnpromotedWidth < Val.getBitWidth()) {
678 llvm::APSInt ConvVal(Val);
679 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
680 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
681 // FIXME: Use different diagnostics for overflow in conversion to promoted
682 // type versus "switch expression cannot have this value". Use proper
683 // IntRange checking rather than just looking at the unpromoted type here.
684 if (ConvVal != Val)
685 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
686 << ConvVal.toString(10);
687 }
688}
689
Alexis Hunt724f14e2014-11-28 00:53:20 +0000690typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
691
Dmitri Gribenko58683752013-12-05 22:52:07 +0000692/// Returns true if we should emit a diagnostic about this case expression not
693/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000694static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000695 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000696 const Expr *CaseExpr,
697 EnumValsTy::iterator &EI,
698 EnumValsTy::iterator &EIEnd,
699 const llvm::APSInt &Val) {
700 bool FlagType = ED->hasAttr<FlagEnumAttr>();
701
702 if (const DeclRefExpr *DRE =
703 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000704 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000705 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000706 QualType EnumType = S.Context.getTypeDeclType(ED);
707 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
708 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000709 return false;
710 }
711 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000712
713 if (FlagType) {
714 return !S.IsValueInFlagEnum(ED, Val, false);
715 } else {
716 while (EI != EIEnd && EI->first < Val)
717 EI++;
718
719 if (EI != EIEnd && EI->first == Val)
720 return false;
721 }
722
Dmitri Gribenko58683752013-12-05 22:52:07 +0000723 return true;
724}
725
John McCalldadc5752010-08-24 06:29:42 +0000726StmtResult
John McCallb268a282010-08-23 23:25:46 +0000727Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
728 Stmt *BodyStmt) {
729 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000730 assert(SS == getCurFunction()->SwitchStack.back() &&
731 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000732
David Majnemer418ad3f2014-12-15 07:46:12 +0000733 getCurFunction()->SwitchStack.pop_back();
734
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000735 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000736 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000737
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000738 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000739 if (!CondExpr) return StmtError();
740
741 QualType CondType = CondExpr->getType();
742
John McCalld3dfbd62010-05-18 03:19:21 +0000743 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000744 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000745 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000746
Chris Lattnera96d4272009-10-16 16:45:22 +0000747 // C++ 6.4.2.p2:
748 // Integral promotions are performed (on the switch condition).
749 //
750 // A case value unrepresentable by the original switch condition
751 // type (before the promotion) doesn't make sense, even when it can
752 // be represented by the promoted type. Therefore we need to find
753 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000754 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000755 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000756 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000757 // appropriate type now, just return an error.
758 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000759 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000760
Chris Lattner4ebae652010-04-16 23:34:13 +0000761 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000762 // switch(bool_expr) {...} is often a programmer error, e.g.
763 // switch(n && mask) { ... } // Doh - should be "n & mask".
764 // One can always use an if statement instead of switch(bool_expr).
765 Diag(SwitchLoc, diag::warn_bool_switch_condition)
766 << CondExpr->getSourceRange();
767 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000768 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000769
Richard Smith077d0832014-08-04 00:40:48 +0000770 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000771 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000772 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000773 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000774 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
775 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
776
777 // Get the width and signedness that the condition might actually have, for
778 // warning purposes.
779 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
780 // type.
781 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000782 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000783 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000784 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000786 // Accumulate all of the case values in a vector so that we can sort them
787 // and detect duplicates. This vector contains the APInt for the case after
788 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000789 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000790 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000791
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000792 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000793 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
794 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000795
Craig Topperc3ec1492014-05-26 06:22:03 +0000796 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattner10cb5e52007-08-23 06:23:56 +0000798 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000799
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000800 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000801 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000802
Anders Carlsson51873c22007-07-22 07:07:56 +0000803 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000804 if (TheDefaultStmt) {
805 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000806 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000807
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000808 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000809 // we'll return a valid AST. This requires recursing down the AST and
810 // finding it, not something we are set up to do right now. For now,
811 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000812 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000813 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000814 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000816 } else {
817 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000818
Chris Lattnera65e1f32008-01-16 19:17:22 +0000819 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000820
821 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
822 HasDependentValue = true;
823 break;
824 }
Mike Stump11289f42009-09-09 15:08:12 +0000825
Richard Smithf8379a02012-01-18 23:55:52 +0000826 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000827
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000828 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000829 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
830 // constant expression of the promoted type of the switch condition.
831 ExprResult ConvLo =
832 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
833 if (ConvLo.isInvalid()) {
834 CaseListIsErroneous = true;
835 continue;
836 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000837 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000838 } else {
839 // We already verified that the expression has a i-c-e value (C99
840 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000841 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000842
843 // If the LHS is not the same type as the condition, insert an implicit
844 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000845 Lo = DefaultLvalueConversion(Lo).get();
846 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000847 }
848
Richard Smith077d0832014-08-04 00:40:48 +0000849 // Check the unconverted value is within the range of possible values of
850 // the switch expression.
851 checkCaseValue(*this, Lo->getLocStart(), LoVal,
852 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
853
854 // Convert the value to the same width/sign as the condition.
855 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000856
Chris Lattnera65e1f32008-01-16 19:17:22 +0000857 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000858
Chris Lattner10cb5e52007-08-23 06:23:56 +0000859 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000860 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000861 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000862 CS->getRHS()->isValueDependent()) {
863 HasDependentValue = true;
864 break;
865 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000866 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000867 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000868 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000869 }
870 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000871
872 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000873 // If we don't have a default statement, check whether the
874 // condition is constant.
875 llvm::APSInt ConstantCondValue;
876 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000877 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000878 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
879 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000880 assert(!HasConstantCond ||
881 (ConstantCondValue.getBitWidth() == CondWidth &&
882 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000883 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000884 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000885
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000886 // Sort all the scalar case values so we can easily detect duplicates.
887 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
888
889 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000890 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
891 if (ShouldCheckConstantCond &&
892 CaseVals[i].first == ConstantCondValue)
893 ShouldCheckConstantCond = false;
894
895 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000896 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000897 // First, determine if either case value has a name
898 StringRef PrevString, CurrString;
899 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
900 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
901 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
902 PrevString = DeclRef->getDecl()->getName();
903 }
904 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
905 CurrString = DeclRef->getDecl()->getName();
906 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000907 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000908 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000909
910 if (PrevString == CurrString)
911 Diag(CaseVals[i].second->getLHS()->getLocStart(),
912 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000913 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000914 else
915 Diag(CaseVals[i].second->getLHS()->getLocStart(),
916 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000917 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
918 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000919 CaseValStr;
920
John McCalld3dfbd62010-05-18 03:19:21 +0000921 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000922 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000923 // FIXME: We really want to remove the bogus case stmt from the
924 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000925 CaseListIsErroneous = true;
926 }
927 }
928 }
Mike Stump11289f42009-09-09 15:08:12 +0000929
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000930 // Detect duplicate case ranges, which usually don't exist at all in
931 // the first place.
932 if (!CaseRanges.empty()) {
933 // Sort all the case ranges by their low value so we can easily detect
934 // overlaps between ranges.
935 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000936
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000937 // Scan the ranges, computing the high values and removing empty ranges.
938 std::vector<llvm::APSInt> HiVals;
939 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000940 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000941 CaseStmt *CR = CaseRanges[i].second;
942 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000943 llvm::APSInt HiVal;
944
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000945 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000946 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
947 // constant expression of the promoted type of the switch condition.
948 ExprResult ConvHi =
949 CheckConvertedConstantExpression(Hi, CondType, HiVal,
950 CCEK_CaseValue);
951 if (ConvHi.isInvalid()) {
952 CaseListIsErroneous = true;
953 continue;
954 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000955 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000956 } else {
957 HiVal = Hi->EvaluateKnownConstInt(Context);
958
959 // If the RHS is not the same type as the condition, insert an
960 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000961 Hi = DefaultLvalueConversion(Hi).get();
962 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000963 }
Mike Stump11289f42009-09-09 15:08:12 +0000964
Richard Smith077d0832014-08-04 00:40:48 +0000965 // Check the unconverted value is within the range of possible values of
966 // the switch expression.
967 checkCaseValue(*this, Hi->getLocStart(), HiVal,
968 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
969
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000970 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000971 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000972
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000973 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000975 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000976 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000977 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
978 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000979 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000980 CaseRanges.erase(CaseRanges.begin()+i);
981 --i, --e;
982 continue;
983 }
John McCalld3dfbd62010-05-18 03:19:21 +0000984
985 if (ShouldCheckConstantCond &&
986 LoVal <= ConstantCondValue &&
987 ConstantCondValue <= HiVal)
988 ShouldCheckConstantCond = false;
989
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000990 HiVals.push_back(HiVal);
991 }
Mike Stump11289f42009-09-09 15:08:12 +0000992
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000993 // Rescan the ranges, looking for overlap with singleton values and other
994 // ranges. Since the range list is sorted, we only need to compare case
995 // ranges with their neighbors.
996 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
997 llvm::APSInt &CRLo = CaseRanges[i].first;
998 llvm::APSInt &CRHi = HiVals[i];
999 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001000
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001001 // Check to see whether the case range overlaps with any
1002 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001003 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001004 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001005
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001006 // Find the smallest value >= the lower bound. If I is in the
1007 // case range, then we have overlap.
1008 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1009 CaseVals.end(), CRLo,
1010 CaseCompareFunctor());
1011 if (I != CaseVals.end() && I->first < CRHi) {
1012 OverlapVal = I->first; // Found overlap with scalar.
1013 OverlapStmt = I->second;
1014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001016 // Find the smallest value bigger than the upper bound.
1017 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1018 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1019 OverlapVal = (I-1)->first; // Found overlap with scalar.
1020 OverlapStmt = (I-1)->second;
1021 }
Mike Stump11289f42009-09-09 15:08:12 +00001022
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001023 // Check to see if this case stmt overlaps with the subsequent
1024 // case range.
1025 if (i && CRLo <= HiVals[i-1]) {
1026 OverlapVal = HiVals[i-1]; // Found overlap with range.
1027 OverlapStmt = CaseRanges[i-1].second;
1028 }
Mike Stump11289f42009-09-09 15:08:12 +00001029
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001030 if (OverlapStmt) {
1031 // If we have a duplicate, report it.
1032 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1033 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001034 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001035 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001036 // FIXME: We really want to remove the bogus case stmt from the
1037 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001038 CaseListIsErroneous = true;
1039 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001040 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001041 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001042
John McCalld3dfbd62010-05-18 03:19:21 +00001043 // Complain if we have a constant condition and we didn't find a match.
1044 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1045 // TODO: it would be nice if we printed enums as enums, chars as
1046 // chars, etc.
1047 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1048 << ConstantCondValue.toString(10)
1049 << CondExpr->getSourceRange();
1050 }
1051
1052 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001053 // values. We only issue a warning if there is not 'default:', but
1054 // we still do the analysis to preserve this information in the AST
1055 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001056 //
Chris Lattner51679082010-09-16 17:09:42 +00001057 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001058
Douglas Gregorbd6839732010-02-08 22:24:16 +00001059 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001060 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001061 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001062 EnumValsTy EnumVals;
1063
John McCalld3dfbd62010-05-18 03:19:21 +00001064 // Gather all enum values, set their type and sort them,
1065 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001066 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001067 llvm::APSInt Val = EDI->getInitVal();
1068 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001069 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001070 }
1071 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001072 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001073 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001074
1075 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001076 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001077 CI != CaseVals.end(); CI++) {
1078 Expr *CaseExpr = CI->second->getLHS();
1079 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1080 CI->first))
1081 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1082 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001083 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001084
David Blaikiee476f972012-01-22 02:31:55 +00001085 // See which of case ranges aren't in enum
1086 EI = EnumVals.begin();
1087 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001088 RI != CaseRanges.end(); RI++) {
1089 Expr *CaseExpr = RI->second->getLHS();
1090 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1091 RI->first))
1092 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1093 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001094
Chad Rosier02a84392012-08-10 17:56:09 +00001095 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001096 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1097 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001098
1099 CaseExpr = RI->second->getRHS();
1100 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1101 Hi))
1102 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1103 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Ted Kremenekc42f3452010-09-09 00:05:53 +00001106 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001107 auto CI = CaseVals.begin();
1108 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001109 bool hasCasesNotInSwitch = false;
1110
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001111 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Alexis Hunt724f14e2014-11-28 00:53:20 +00001113 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001114 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001115 while (CI != CaseVals.end() && CI->first < EI->first)
1116 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001117
Douglas Gregorbd6839732010-02-08 22:24:16 +00001118 if (CI != CaseVals.end() && CI->first == EI->first)
1119 continue;
1120
Ted Kremenekc42f3452010-09-09 00:05:53 +00001121 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001122 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001123 llvm::APSInt Hi =
1124 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001125 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001126 if (EI->first <= Hi)
1127 break;
1128 }
1129
Ted Kremenekc42f3452010-09-09 00:05:53 +00001130 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001131 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001132 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001133 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135
David Blaikie60ac6382012-01-23 04:46:12 +00001136 if (TheDefaultStmt && UnhandledNames.empty())
1137 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001138
Chris Lattner51679082010-09-16 17:09:42 +00001139 // Produce a nice diagnostic if multiple values aren't handled.
1140 switch (UnhandledNames.size()) {
1141 case 0: break;
1142 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001143 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001144 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001145 << UnhandledNames[0];
1146 break;
1147 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001148 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001149 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001150 << UnhandledNames[0] << UnhandledNames[1];
1151 break;
1152 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001153 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1154 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001155 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1156 break;
1157 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001158 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1159 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001160 << (unsigned)UnhandledNames.size()
1161 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1162 break;
1163 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001164
1165 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001166 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001167 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001168 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001169
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001170 if (BodyStmt)
1171 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1172 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001173
Mike Stump87c57ac2009-05-16 07:39:55 +00001174 // FIXME: If the case list was broken is some way, we don't have a good system
1175 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001176 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001177 return StmtError();
1178
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001179 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001180}
1181
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001182void
1183Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1184 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001185 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001186 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001187
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001188 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001189 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001190 SrcType->isIntegerType()) {
1191 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1192 SrcExpr->isIntegerConstantExpr(Context)) {
1193 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001194 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001195 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1196
1197 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001198 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001199 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001200
Alexis Hunt724f14e2014-11-28 00:53:20 +00001201 if (ED->hasAttr<FlagEnumAttr>()) {
1202 if (!IsValueInFlagEnum(ED, RhsVal, true))
1203 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001204 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001205 } else {
1206 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1207 EnumValsTy;
1208 EnumValsTy EnumVals;
1209
1210 // Gather all enum values, set their type and sort them,
1211 // allowing easier comparison with rhs constant.
1212 for (auto *EDI : ED->enumerators()) {
1213 llvm::APSInt Val = EDI->getInitVal();
1214 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1215 EnumVals.push_back(std::make_pair(Val, EDI));
1216 }
1217 if (EnumVals.empty())
1218 return;
1219 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1220 EnumValsTy::iterator EIend =
1221 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1222
1223 // See which values aren't in the enum.
1224 EnumValsTy::const_iterator EI = EnumVals.begin();
1225 while (EI != EIend && EI->first < RhsVal)
1226 EI++;
1227 if (EI == EIend || EI->first != RhsVal) {
1228 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1229 << DstType.getUnqualifiedType();
1230 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001231 }
1232 }
1233 }
1234}
1235
John McCalldadc5752010-08-24 06:29:42 +00001236StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001237Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001238 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001239 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240
Craig Topperc3ec1492014-05-26 06:22:03 +00001241 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001242 if (CondVar) {
1243 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001244 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001245 if (CondResult.isInvalid())
1246 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001247 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001248 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001249 if (!ConditionExpr)
1250 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001251 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001252
John McCallb268a282010-08-23 23:25:46 +00001253 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001254
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001255 if (isa<NullStmt>(Body))
1256 getCurCompoundScope().setHasEmptyLoopBodies();
1257
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001258 return new (Context)
1259 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001260}
1261
John McCalldadc5752010-08-24 06:29:42 +00001262StmtResult
John McCallb268a282010-08-23 23:25:46 +00001263Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001264 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001265 Expr *Cond, SourceLocation CondRParen) {
1266 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001267
Serge Pavlov09f99242014-01-23 15:05:00 +00001268 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001269 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001270 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001271 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001272 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001273
Richard Smith945f8d32013-01-14 22:39:08 +00001274 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001275 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001276 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001277 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
John McCallb268a282010-08-23 23:25:46 +00001279 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001280
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001281 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001282}
1283
Richard Trieu451a5db2012-04-30 18:01:30 +00001284namespace {
1285 // This visitor will traverse a conditional statement and store all
1286 // the evaluated decls into a vector. Simple is set to true if none
1287 // of the excluded constructs are used.
1288 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001289 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001290 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001291 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001292 public:
1293 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001294
Craig Topper4dd9b432014-08-17 23:49:53 +00001295 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001296 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001297 Inherited(S.Context),
1298 Decls(Decls),
1299 Ranges(Ranges),
1300 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001301
Richard Trieu9d228802013-05-31 22:46:45 +00001302 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001303
Richard Trieu9d228802013-05-31 22:46:45 +00001304 // Replaces the method in EvaluatedExprVisitor.
1305 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001306 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001307 }
1308
1309 // Any Stmt not whitelisted will cause the condition to be marked complex.
1310 void VisitStmt(Stmt *S) {
1311 Simple = false;
1312 }
1313
1314 void VisitBinaryOperator(BinaryOperator *E) {
1315 Visit(E->getLHS());
1316 Visit(E->getRHS());
1317 }
1318
1319 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001320 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001321 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001322
Richard Trieu9d228802013-05-31 22:46:45 +00001323 void VisitUnaryOperator(UnaryOperator *E) {
1324 // Skip checking conditionals with derefernces.
1325 if (E->getOpcode() == UO_Deref)
1326 Simple = false;
1327 else
1328 Visit(E->getSubExpr());
1329 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001330
Richard Trieu9d228802013-05-31 22:46:45 +00001331 void VisitConditionalOperator(ConditionalOperator *E) {
1332 Visit(E->getCond());
1333 Visit(E->getTrueExpr());
1334 Visit(E->getFalseExpr());
1335 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001336
Richard Trieu9d228802013-05-31 22:46:45 +00001337 void VisitParenExpr(ParenExpr *E) {
1338 Visit(E->getSubExpr());
1339 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001340
Richard Trieu9d228802013-05-31 22:46:45 +00001341 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1342 Visit(E->getOpaqueValue()->getSourceExpr());
1343 Visit(E->getFalseExpr());
1344 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001345
Richard Trieu9d228802013-05-31 22:46:45 +00001346 void VisitIntegerLiteral(IntegerLiteral *E) { }
1347 void VisitFloatingLiteral(FloatingLiteral *E) { }
1348 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1349 void VisitCharacterLiteral(CharacterLiteral *E) { }
1350 void VisitGNUNullExpr(GNUNullExpr *E) { }
1351 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001352
Richard Trieu9d228802013-05-31 22:46:45 +00001353 void VisitDeclRefExpr(DeclRefExpr *E) {
1354 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1355 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001356
Richard Trieu9d228802013-05-31 22:46:45 +00001357 Ranges.push_back(E->getSourceRange());
1358
1359 Decls.insert(VD);
1360 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001361
1362 }; // end class DeclExtractor
1363
1364 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001365 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001366 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001367 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001368 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001369
Richard Trieu9d228802013-05-31 22:46:45 +00001370 public:
1371 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001372
Craig Topper4dd9b432014-08-17 23:49:53 +00001373 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001374 Stmt *Statement) :
1375 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1376 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001379 }
1380
Richard Trieu9d228802013-05-31 22:46:45 +00001381 void VisitReturnStmt(ReturnStmt *S) {
1382 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001383 }
1384
Richard Trieu9d228802013-05-31 22:46:45 +00001385 void VisitBreakStmt(BreakStmt *S) {
1386 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001387 }
1388
Richard Trieu9d228802013-05-31 22:46:45 +00001389 void VisitGotoStmt(GotoStmt *S) {
1390 FoundDecl = true;
1391 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001392
Richard Trieu9d228802013-05-31 22:46:45 +00001393 void VisitCastExpr(CastExpr *E) {
1394 if (E->getCastKind() == CK_LValueToRValue)
1395 CheckLValueToRValueCast(E->getSubExpr());
1396 else
1397 Visit(E->getSubExpr());
1398 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001399
Richard Trieu9d228802013-05-31 22:46:45 +00001400 void CheckLValueToRValueCast(Expr *E) {
1401 E = E->IgnoreParenImpCasts();
1402
1403 if (isa<DeclRefExpr>(E)) {
1404 return;
1405 }
1406
1407 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1408 Visit(CO->getCond());
1409 CheckLValueToRValueCast(CO->getTrueExpr());
1410 CheckLValueToRValueCast(CO->getFalseExpr());
1411 return;
1412 }
1413
1414 if (BinaryConditionalOperator *BCO =
1415 dyn_cast<BinaryConditionalOperator>(E)) {
1416 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1417 CheckLValueToRValueCast(BCO->getFalseExpr());
1418 return;
1419 }
1420
1421 Visit(E);
1422 }
1423
1424 void VisitDeclRefExpr(DeclRefExpr *E) {
1425 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1426 if (Decls.count(VD))
1427 FoundDecl = true;
1428 }
1429
1430 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001431
1432 }; // end class DeclMatcher
1433
1434 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1435 Expr *Third, Stmt *Body) {
1436 // Condition is empty
1437 if (!Second) return;
1438
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001439 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1440 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001441 return;
1442
1443 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1444 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001445 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001446 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001447 DE.Visit(Second);
1448
1449 // Don't analyze complex conditionals.
1450 if (!DE.isSimple()) return;
1451
1452 // No decls found.
1453 if (Decls.size() == 0) return;
1454
Richard Trieu0030f1d2012-05-04 03:01:54 +00001455 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001456 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1457 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001458 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001459 if ((*I)->getType().isVolatileQualified() ||
1460 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001461
1462 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1463 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1464 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1465 return;
1466
1467 // Load decl names into diagnostic.
1468 if (Decls.size() > 4)
1469 PDiag << 0;
1470 else {
1471 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001472 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1473 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001474 I != E; ++I)
1475 PDiag << (*I)->getDeclName();
1476 }
1477
1478 // Load SourceRanges into diagnostic if there is room.
1479 // Otherwise, load the SourceRange of the conditional expression.
1480 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001481 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001482 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001483 I != E; ++I)
1484 PDiag << *I;
1485 else
1486 PDiag << Second->getSourceRange();
1487
1488 S.Diag(Ranges.begin()->getBegin(), PDiag);
1489 }
1490
Richard Trieu4e7c9622013-08-06 21:31:54 +00001491 // If Statement is an incemement or decrement, return true and sets the
1492 // variables Increment and DRE.
1493 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1494 DeclRefExpr *&DRE) {
1495 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1496 switch (UO->getOpcode()) {
1497 default: return false;
1498 case UO_PostInc:
1499 case UO_PreInc:
1500 Increment = true;
1501 break;
1502 case UO_PostDec:
1503 case UO_PreDec:
1504 Increment = false;
1505 break;
1506 }
1507 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1508 return DRE;
1509 }
1510
1511 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1512 FunctionDecl *FD = Call->getDirectCallee();
1513 if (!FD || !FD->isOverloadedOperator()) return false;
1514 switch (FD->getOverloadedOperator()) {
1515 default: return false;
1516 case OO_PlusPlus:
1517 Increment = true;
1518 break;
1519 case OO_MinusMinus:
1520 Increment = false;
1521 break;
1522 }
1523 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1524 return DRE;
1525 }
1526
1527 return false;
1528 }
1529
Serge Pavlov09f99242014-01-23 15:05:00 +00001530 // A visitor to determine if a continue or break statement is a
1531 // subexpression.
1532 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1533 SourceLocation BreakLoc;
1534 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001535 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001536 BreakContinueFinder(Sema &S, Stmt* Body) :
1537 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001538 Visit(Body);
1539 }
1540
Serge Pavlov09f99242014-01-23 15:05:00 +00001541 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001542
1543 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001544 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001545 }
1546
Serge Pavlov09f99242014-01-23 15:05:00 +00001547 void VisitBreakStmt(BreakStmt* E) {
1548 BreakLoc = E->getBreakLoc();
1549 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001550
Serge Pavlov09f99242014-01-23 15:05:00 +00001551 bool ContinueFound() { return ContinueLoc.isValid(); }
1552 bool BreakFound() { return BreakLoc.isValid(); }
1553 SourceLocation GetContinueLoc() { return ContinueLoc; }
1554 SourceLocation GetBreakLoc() { return BreakLoc; }
1555
1556 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001557
1558 // Emit a warning when a loop increment/decrement appears twice per loop
1559 // iteration. The conditions which trigger this warning are:
1560 // 1) The last statement in the loop body and the third expression in the
1561 // for loop are both increment or both decrement of the same variable
1562 // 2) No continue statements in the loop body.
1563 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1564 // Return when there is nothing to check.
1565 if (!Body || !Third) return;
1566
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001567 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1568 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001569 return;
1570
1571 // Get the last statement from the loop body.
1572 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1573 if (!CS || CS->body_empty()) return;
1574 Stmt *LastStmt = CS->body_back();
1575 if (!LastStmt) return;
1576
1577 bool LoopIncrement, LastIncrement;
1578 DeclRefExpr *LoopDRE, *LastDRE;
1579
1580 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1581 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1582
1583 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001584 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001585 if (LoopIncrement != LastIncrement ||
1586 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1587
Serge Pavlov09f99242014-01-23 15:05:00 +00001588 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001589
1590 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1591 << LastDRE->getDecl() << LastIncrement;
1592 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1593 << LoopIncrement;
1594 }
1595
Richard Trieu451a5db2012-04-30 18:01:30 +00001596} // end namespace
1597
Serge Pavlov09f99242014-01-23 15:05:00 +00001598
1599void Sema::CheckBreakContinueBinding(Expr *E) {
1600 if (!E || getLangOpts().CPlusPlus)
1601 return;
1602 BreakContinueFinder BCFinder(*this, E);
1603 Scope *BreakParent = CurScope->getBreakParent();
1604 if (BCFinder.BreakFound() && BreakParent) {
1605 if (BreakParent->getFlags() & Scope::SwitchScope) {
1606 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1607 } else {
1608 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1609 << "break";
1610 }
1611 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1612 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1613 << "continue";
1614 }
1615}
1616
John McCalldadc5752010-08-24 06:29:42 +00001617StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001618Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001619 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001620 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001621 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001622 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001623 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001624 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1625 // declare identifiers for objects having storage class 'auto' or
1626 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001627 for (auto *DI : DS->decls()) {
1628 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001629 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001630 VD = nullptr;
1631 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001632 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1633 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001634 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001635 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001636 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001637 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001638
Serge Pavlov09f99242014-01-23 15:05:00 +00001639 CheckBreakContinueBinding(second.get());
1640 CheckBreakContinueBinding(third.get());
1641
Richard Trieu451a5db2012-04-30 18:01:30 +00001642 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001643 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001644
John McCalldadc5752010-08-24 06:29:42 +00001645 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001646 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001647 if (secondVar) {
1648 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001649 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001650 if (SecondResult.isInvalid())
1651 return StmtError();
1652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001653
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001654 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
Anders Carlsson1682af52009-08-01 01:39:59 +00001656 DiagnoseUnusedExprResult(First);
1657 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001658 DiagnoseUnusedExprResult(Body);
1659
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001660 if (isa<NullStmt>(Body))
1661 getCurCompoundScope().setHasEmptyLoopBodies();
1662
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001663 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1664 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001665}
1666
John McCall34376a62010-12-04 03:47:34 +00001667/// In an Objective C collection iteration statement:
1668/// for (x in y)
1669/// x can be an arbitrary l-value expression. Bind it up as a
1670/// full-expression.
1671StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001672 // Reduce placeholder expressions here. Note that this rejects the
1673 // use of pseudo-object l-values in this position.
1674 ExprResult result = CheckPlaceholderExpr(E);
1675 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001676 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001677
Richard Smith945f8d32013-01-14 22:39:08 +00001678 ExprResult FullExpr = ActOnFinishFullExpr(E);
1679 if (FullExpr.isInvalid())
1680 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001681 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001682}
1683
John McCall53848232011-07-27 01:07:15 +00001684ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001685Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1686 if (!collection)
1687 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001688
Kaelyn Takata15867822014-11-21 18:48:04 +00001689 ExprResult result = CorrectDelayedTyposInExpr(collection);
1690 if (!result.isUsable())
1691 return ExprError();
1692 collection = result.get();
1693
John McCall53848232011-07-27 01:07:15 +00001694 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001695 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001696
1697 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001698 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001699 if (result.isInvalid())
1700 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001701 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001702
1703 // The operand needs to have object-pointer type.
1704 // TODO: should we do a contextual conversion?
1705 const ObjCObjectPointerType *pointerType =
1706 collection->getType()->getAs<ObjCObjectPointerType>();
1707 if (!pointerType)
1708 return Diag(forLoc, diag::err_collection_expr_type)
1709 << collection->getType() << collection->getSourceRange();
1710
1711 // Check that the operand provides
1712 // - countByEnumeratingWithState:objects:count:
1713 const ObjCObjectType *objectType = pointerType->getObjectType();
1714 ObjCInterfaceDecl *iface = objectType->getInterface();
1715
1716 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001717 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001718 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001719 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001720 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001721 ? diag::err_arc_collection_forward
1722 : 0,
1723 collection)) {
John McCall53848232011-07-27 01:07:15 +00001724 // Otherwise, if we have any useful type information, check that
1725 // the type declares the appropriate method.
1726 } else if (iface || !objectType->qual_empty()) {
1727 IdentifierInfo *selectorIdents[] = {
1728 &Context.Idents.get("countByEnumeratingWithState"),
1729 &Context.Idents.get("objects"),
1730 &Context.Idents.get("count")
1731 };
1732 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1733
Craig Topperc3ec1492014-05-26 06:22:03 +00001734 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001735
1736 // If there's an interface, look in both the public and private APIs.
1737 if (iface) {
1738 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001739 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001740 }
1741
1742 // Also check protocol qualifiers.
1743 if (!method)
1744 method = LookupMethodInQualifiedType(selector, pointerType,
1745 /*instance*/ true);
1746
1747 // If we didn't find it anywhere, give up.
1748 if (!method) {
1749 Diag(forLoc, diag::warn_collection_expr_type)
1750 << collection->getType() << selector << collection->getSourceRange();
1751 }
1752
1753 // TODO: check for an incompatible signature?
1754 }
1755
1756 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001757 return collection;
John McCall53848232011-07-27 01:07:15 +00001758}
1759
John McCalldadc5752010-08-24 06:29:42 +00001760StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001761Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001762 Stmt *First, Expr *collection,
1763 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001764
1765 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001766 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001767
Fariborz Jahanian93977672008-01-10 20:33:58 +00001768 if (First) {
1769 QualType FirstType;
1770 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001771 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001772 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1773 diag::err_toomany_element_decls));
1774
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001775 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1776 if (!D || D->isInvalidDecl())
1777 return StmtError();
1778
John McCall31168b02011-06-15 23:02:42 +00001779 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001780 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1781 // declare identifiers for objects having storage class 'auto' or
1782 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001783 if (!D->hasLocalStorage())
1784 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001785 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001786
1787 // If the type contained 'auto', deduce the 'auto' to 'id'.
1788 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001789 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1790 VK_RValue);
1791 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001792 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1793 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001794 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001795 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001796 D->setInvalidDecl();
1797 return StmtError();
1798 }
1799
Richard Smith061f1e22013-04-30 21:23:01 +00001800 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001801
1802 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001803 SourceLocation Loc =
1804 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001805 Diag(Loc, diag::warn_auto_var_is_id)
1806 << D->getDeclName();
1807 }
1808 }
1809
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001810 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001811 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001812 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001813 return StmtError(Diag(First->getLocStart(),
1814 diag::err_selector_element_not_lvalue)
1815 << First->getSourceRange());
1816
Mike Stump11289f42009-09-09 15:08:12 +00001817 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001818 if (FirstType.isConstQualified())
1819 Diag(ForLoc, diag::err_selector_element_const_type)
1820 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001821 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001822 if (!FirstType->isDependentType() &&
1823 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001824 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001825 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1826 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001827 }
Chad Rosier02a84392012-08-10 17:56:09 +00001828
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001829 if (CollectionExprResult.isInvalid())
1830 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001831
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001832 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001833 if (CollectionExprResult.isInvalid())
1834 return StmtError();
1835
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001836 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1837 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001838}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001839
Richard Smith02e85f32011-04-14 22:09:26 +00001840/// Finish building a variable declaration for a for-range statement.
1841/// \return true if an error occurs.
1842static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001843 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001844 // Deduce the type for the iterator variable now rather than leaving it to
1845 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001846 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001847 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001848 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001849 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001850 SemaRef.Diag(Loc, DiagID) << Init->getType();
1851 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001852 Decl->setInvalidDecl();
1853 return true;
1854 }
Richard Smith061f1e22013-04-30 21:23:01 +00001855 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001856
John McCall31168b02011-06-15 23:02:42 +00001857 // In ARC, infer lifetime.
1858 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1859 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001860 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001861 SemaRef.inferObjCARCLifetime(Decl))
1862 Decl->setInvalidDecl();
1863
Richard Smith02e85f32011-04-14 22:09:26 +00001864 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1865 /*TypeMayContainAuto=*/false);
1866 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001867 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001868 return false;
1869}
1870
Sam Panzer0f384432012-08-21 00:52:01 +00001871namespace {
1872
Richard Smith02e85f32011-04-14 22:09:26 +00001873/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001874/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001875/// nor from the diagnostics produced when analysing the implicit expressions
1876/// required in a for-range statement.
1877void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001878 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001879 CallExpr *CE = dyn_cast<CallExpr>(E);
1880 if (!CE)
1881 return;
1882 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1883 if (!D)
1884 return;
1885 SourceLocation Loc = D->getLocation();
1886
1887 std::string Description;
1888 bool IsTemplate = false;
1889 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1890 Description = SemaRef.getTemplateArgumentBindingsText(
1891 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1892 IsTemplate = true;
1893 }
1894
1895 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1896 << BEF << IsTemplate << Description << E->getType();
1897}
1898
Sam Panzer0f384432012-08-21 00:52:01 +00001899/// Build a variable declaration for a for-range statement.
1900VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1901 QualType Type, const char *Name) {
1902 DeclContext *DC = SemaRef.CurContext;
1903 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1904 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1905 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001906 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001907 Decl->setImplicit();
1908 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001909}
1910
1911}
1912
Fariborz Jahanian00213472012-07-06 19:04:04 +00001913static bool ObjCEnumerationCollection(Expr *Collection) {
1914 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001915 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001916}
1917
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001918/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001919///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001920/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001921/// A range-based for statement is equivalent to
1922///
1923/// {
1924/// auto && __range = range-init;
1925/// for ( auto __begin = begin-expr,
1926/// __end = end-expr;
1927/// __begin != __end;
1928/// ++__begin ) {
1929/// for-range-declaration = *__begin;
1930/// statement
1931/// }
1932/// }
1933///
1934/// The body of the loop is not available yet, since it cannot be analysed until
1935/// we have determined the type of the for-range-declaration.
1936StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001937Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001938 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001939 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001940 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001941 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001942
Richard Smith3249fed2013-08-21 01:40:36 +00001943 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001944 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001945
1946 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1947 assert(DS && "first part of for range not a decl stmt");
1948
1949 if (!DS->isSingleDecl()) {
1950 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1951 return StmtError();
1952 }
Richard Smith02e85f32011-04-14 22:09:26 +00001953
Richard Smith3249fed2013-08-21 01:40:36 +00001954 Decl *LoopVar = DS->getSingleDecl();
1955 if (LoopVar->isInvalidDecl() || !Range ||
1956 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1957 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001958 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001959 }
Richard Smith02e85f32011-04-14 22:09:26 +00001960
1961 // Build auto && __range = range-init
1962 SourceLocation RangeLoc = Range->getLocStart();
1963 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1964 Context.getAutoRRefDeductType(),
1965 "__range");
1966 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001967 diag::err_for_range_deduction_failure)) {
1968 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001969 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001970 }
Richard Smith02e85f32011-04-14 22:09:26 +00001971
1972 // Claim the type doesn't contain auto: we've already done the checking.
1973 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001974 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001975 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001976 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001977 if (RangeDecl.isInvalid()) {
1978 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001979 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001980 }
Richard Smith02e85f32011-04-14 22:09:26 +00001981
1982 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001983 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1984 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001985}
1986
1987/// \brief Create the initialization, compare, and increment steps for
1988/// the range-based for loop expression.
1989/// This function does not handle array-based for loops,
1990/// which are created in Sema::BuildCXXForRangeStmt.
1991///
1992/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1993/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1994/// CandidateSet and BEF are set and some non-success value is returned on
1995/// failure.
1996static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1997 Expr *BeginRange, Expr *EndRange,
1998 QualType RangeType,
1999 VarDecl *BeginVar,
2000 VarDecl *EndVar,
2001 SourceLocation ColonLoc,
2002 OverloadCandidateSet *CandidateSet,
2003 ExprResult *BeginExpr,
2004 ExprResult *EndExpr,
2005 Sema::BeginEndFunction *BEF) {
2006 DeclarationNameInfo BeginNameInfo(
2007 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2008 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2009 ColonLoc);
2010
2011 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2012 Sema::LookupMemberName);
2013 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2014
2015 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2016 // - if _RangeT is a class type, the unqualified-ids begin and end are
2017 // looked up in the scope of class _RangeT as if by class member access
2018 // lookup (3.4.5), and if either (or both) finds at least one
2019 // declaration, begin-expr and end-expr are __range.begin() and
2020 // __range.end(), respectively;
2021 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2022 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2023
2024 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2025 SourceLocation RangeLoc = BeginVar->getLocation();
2026 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2027
2028 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2029 << RangeLoc << BeginRange->getType() << *BEF;
2030 return Sema::FRS_DiagnosticIssued;
2031 }
2032 } else {
2033 // - otherwise, begin-expr and end-expr are begin(__range) and
2034 // end(__range), respectively, where begin and end are looked up with
2035 // argument-dependent lookup (3.4.2). For the purposes of this name
2036 // lookup, namespace std is an associated namespace.
2037
2038 }
2039
2040 *BEF = Sema::BEF_begin;
2041 Sema::ForRangeStatus RangeStatus =
2042 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2043 Sema::BEF_begin, BeginNameInfo,
2044 BeginMemberLookup, CandidateSet,
2045 BeginRange, BeginExpr);
2046
2047 if (RangeStatus != Sema::FRS_Success)
2048 return RangeStatus;
2049 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2050 diag::err_for_range_iter_deduction_failure)) {
2051 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2052 return Sema::FRS_DiagnosticIssued;
2053 }
2054
2055 *BEF = Sema::BEF_end;
2056 RangeStatus =
2057 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2058 Sema::BEF_end, EndNameInfo,
2059 EndMemberLookup, CandidateSet,
2060 EndRange, EndExpr);
2061 if (RangeStatus != Sema::FRS_Success)
2062 return RangeStatus;
2063 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2064 diag::err_for_range_iter_deduction_failure)) {
2065 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2066 return Sema::FRS_DiagnosticIssued;
2067 }
2068 return Sema::FRS_Success;
2069}
2070
2071/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002072/// If the attempt fails, this function will return a valid, null StmtResult
2073/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002074static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2075 SourceLocation ForLoc,
2076 Stmt *LoopVarDecl,
2077 SourceLocation ColonLoc,
2078 Expr *Range,
2079 SourceLocation RangeLoc,
2080 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002081 // Determine whether we can rebuild the for-range statement with a
2082 // dereferenced range expression.
2083 ExprResult AdjustedRange;
2084 {
2085 Sema::SFINAETrap Trap(SemaRef);
2086
2087 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2088 if (AdjustedRange.isInvalid())
2089 return StmtResult();
2090
2091 StmtResult SR =
2092 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2093 AdjustedRange.get(), RParenLoc,
2094 Sema::BFRK_Check);
2095 if (SR.isInvalid())
2096 return StmtResult();
2097 }
2098
2099 // The attempt to dereference worked well enough that it could produce a valid
2100 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2101 // case there are any other (non-fatal) problems with it.
2102 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2103 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2104 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2105 AdjustedRange.get(), RParenLoc,
2106 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002107}
2108
Richard Smith3249fed2013-08-21 01:40:36 +00002109namespace {
2110/// RAII object to automatically invalidate a declaration if an error occurs.
2111struct InvalidateOnErrorScope {
2112 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2113 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2114 ~InvalidateOnErrorScope() {
2115 if (Enabled && Trap.hasErrorOccurred())
2116 D->setInvalidDecl();
2117 }
2118
2119 DiagnosticErrorTrap Trap;
2120 Decl *D;
2121 bool Enabled;
2122};
2123}
2124
Richard Smitha05b3b52012-09-20 21:52:32 +00002125/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002126StmtResult
2127Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2128 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2129 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002130 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002131 Scope *S = getCurScope();
2132
2133 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2134 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2135 QualType RangeVarType = RangeVar->getType();
2136
2137 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2138 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2139
Richard Smith3249fed2013-08-21 01:40:36 +00002140 // If we hit any errors, mark the loop variable as invalid if its type
2141 // contains 'auto'.
2142 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2143 LoopVar->getType()->isUndeducedType());
2144
Richard Smith02e85f32011-04-14 22:09:26 +00002145 StmtResult BeginEndDecl = BeginEnd;
2146 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2147
Richard Smith27d807c2013-04-30 13:56:41 +00002148 if (RangeVarType->isDependentType()) {
2149 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002150 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002151
2152 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2153 // them in properly when we instantiate the loop.
2154 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2155 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2156 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002157 SourceLocation RangeLoc = RangeVar->getLocation();
2158
Ted Kremenekbed648e2011-10-10 22:36:28 +00002159 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2160
2161 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2162 VK_LValue, ColonLoc);
2163 if (BeginRangeRef.isInvalid())
2164 return StmtError();
2165
2166 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2167 VK_LValue, ColonLoc);
2168 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002169 return StmtError();
2170
2171 QualType AutoType = Context.getAutoDeductType();
2172 Expr *Range = RangeVar->getInit();
2173 if (!Range)
2174 return StmtError();
2175 QualType RangeType = Range->getType();
2176
2177 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002178 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002179 return StmtError();
2180
2181 // Build auto __begin = begin-expr, __end = end-expr.
2182 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2183 "__begin");
2184 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2185 "__end");
2186
2187 // Build begin-expr and end-expr and attach to __begin and __end variables.
2188 ExprResult BeginExpr, EndExpr;
2189 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2190 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2191 // __range + __bound, respectively, where __bound is the array bound. If
2192 // _RangeT is an array of unknown size or an array of incomplete type,
2193 // the program is ill-formed;
2194
2195 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002196 BeginExpr = BeginRangeRef;
2197 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002198 diag::err_for_range_iter_deduction_failure)) {
2199 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2200 return StmtError();
2201 }
2202
2203 // Find the array bound.
2204 ExprResult BoundExpr;
2205 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002206 BoundExpr = IntegerLiteral::Create(
2207 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002208 else if (const VariableArrayType *VAT =
2209 dyn_cast<VariableArrayType>(UnqAT))
2210 BoundExpr = VAT->getSizeExpr();
2211 else {
2212 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2213 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002214 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002215 }
2216
2217 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002218 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002219 BoundExpr.get());
2220 if (EndExpr.isInvalid())
2221 return StmtError();
2222 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2223 diag::err_for_range_iter_deduction_failure)) {
2224 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2225 return StmtError();
2226 }
2227 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002228 OverloadCandidateSet CandidateSet(RangeLoc,
2229 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002230 Sema::BeginEndFunction BEFFailure;
2231 ForRangeStatus RangeStatus =
2232 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2233 EndRangeRef.get(), RangeType,
2234 BeginVar, EndVar, ColonLoc, &CandidateSet,
2235 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002236
Richard Smitha05b3b52012-09-20 21:52:32 +00002237 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002238 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002239 // If the range is being built from an array parameter, emit a
2240 // a diagnostic that it is being treated as a pointer.
2241 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2242 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2243 QualType ArrayTy = PVD->getOriginalType();
2244 QualType PointerTy = PVD->getType();
2245 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2246 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2247 << RangeLoc << PVD << ArrayTy << PointerTy;
2248 Diag(PVD->getLocation(), diag::note_declared_at);
2249 return StmtError();
2250 }
2251 }
2252 }
2253
2254 // If building the range failed, try dereferencing the range expression
2255 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002256 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2257 LoopVarDecl, ColonLoc,
2258 Range, RangeLoc,
2259 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002260 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002261 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002262 }
2263
Sam Panzer0f384432012-08-21 00:52:01 +00002264 // Otherwise, emit diagnostics if we haven't already.
2265 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002266 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002267 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2268 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002269 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002270 }
2271 // Return an error if no fix was discovered.
2272 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002273 return StmtError();
2274 }
2275
Sam Panzer0f384432012-08-21 00:52:01 +00002276 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2277 "invalid range expression in for loop");
2278
2279 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002280 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2281 if (!Context.hasSameType(BeginType, EndType)) {
2282 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2283 << BeginType << EndType;
2284 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2285 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2286 }
2287
2288 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2289 // Claim the type doesn't contain auto: we've already done the checking.
2290 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002291 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002292 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002293 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2294
Ted Kremenekbed648e2011-10-10 22:36:28 +00002295 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2296 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002297 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002298 if (BeginRef.isInvalid())
2299 return StmtError();
2300
Richard Smith02e85f32011-04-14 22:09:26 +00002301 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2302 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002303 if (EndRef.isInvalid())
2304 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002305
2306 // Build and check __begin != __end expression.
2307 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2308 BeginRef.get(), EndRef.get());
2309 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2310 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2311 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002312 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2313 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002314 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2315 if (!Context.hasSameType(BeginType, EndType))
2316 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2317 return StmtError();
2318 }
2319
2320 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002321 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2322 VK_LValue, ColonLoc);
2323 if (BeginRef.isInvalid())
2324 return StmtError();
2325
Richard Smith02e85f32011-04-14 22:09:26 +00002326 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2327 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2328 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002329 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2330 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002331 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2332 return StmtError();
2333 }
2334
2335 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002336 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2337 VK_LValue, ColonLoc);
2338 if (BeginRef.isInvalid())
2339 return StmtError();
2340
Richard Smith02e85f32011-04-14 22:09:26 +00002341 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2342 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002343 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2344 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002345 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2346 return StmtError();
2347 }
2348
Richard Smitha05b3b52012-09-20 21:52:32 +00002349 // Attach *__begin as initializer for VD. Don't touch it if we're just
2350 // trying to determine whether this would be a valid range.
2351 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002352 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2353 /*TypeMayContainAuto=*/true);
2354 if (LoopVar->isInvalidDecl())
2355 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2356 }
2357 }
2358
Richard Smitha05b3b52012-09-20 21:52:32 +00002359 // Don't bother to actually allocate the result if we're just trying to
2360 // determine whether it would be valid.
2361 if (Kind == BFRK_Check)
2362 return StmtResult();
2363
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002364 return new (Context) CXXForRangeStmt(
2365 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2366 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002367}
2368
Chad Rosier02a84392012-08-10 17:56:09 +00002369/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002370/// statement.
2371StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2372 if (!S || !B)
2373 return StmtError();
2374 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002375
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002376 ForStmt->setBody(B);
2377 return S;
2378}
2379
Richard Smith02e85f32011-04-14 22:09:26 +00002380/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2381/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2382/// body cannot be performed until after the type of the range variable is
2383/// determined.
2384StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2385 if (!S || !B)
2386 return StmtError();
2387
Fariborz Jahanian00213472012-07-06 19:04:04 +00002388 if (isa<ObjCForCollectionStmt>(S))
2389 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002390
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002391 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2392 ForStmt->setBody(B);
2393
2394 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2395 diag::warn_empty_range_based_for_body);
2396
Richard Smith02e85f32011-04-14 22:09:26 +00002397 return S;
2398}
2399
Chris Lattnercab02a62011-02-17 20:34:02 +00002400StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2401 SourceLocation LabelLoc,
2402 LabelDecl *TheDecl) {
2403 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002404 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002405 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002406}
Chris Lattner1c310502007-05-31 06:00:00 +00002407
John McCalldadc5752010-08-24 06:29:42 +00002408StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002409Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002410 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002411 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002412 if (!E->isTypeDependent()) {
2413 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002414 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002415 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002416 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002417 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2418 if (ExprRes.isInvalid())
2419 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002420 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002421 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002422 return StmtError();
2423 }
John McCalla95172b2010-08-01 00:26:45 +00002424
Richard Smith945f8d32013-01-14 22:39:08 +00002425 ExprResult ExprRes = ActOnFinishFullExpr(E);
2426 if (ExprRes.isInvalid())
2427 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002428 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002429
John McCallaab3e412010-08-25 08:40:02 +00002430 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002431
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002432 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002433}
2434
John McCalldadc5752010-08-24 06:29:42 +00002435StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002436Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002437 Scope *S = CurScope->getContinueParent();
2438 if (!S) {
2439 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002440 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002441 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002442
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002443 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002444}
2445
John McCalldadc5752010-08-24 06:29:42 +00002446StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002447Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002448 Scope *S = CurScope->getBreakParent();
2449 if (!S) {
2450 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002451 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002452 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002453 if (S->isOpenMPLoopScope())
2454 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2455 << "break");
Sebastian Redl573feed2009-01-18 13:19:59 +00002456
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002457 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002458}
2459
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002461/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002462///
Douglas Gregor5d369002011-01-21 18:05:27 +00002463/// \param ReturnType If we're determining the copy elision candidate for
2464/// a return statement, this is the return type of the function. If we're
2465/// determining the copy elision candidate for a throw expression, this will
2466/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002467///
Douglas Gregor5d369002011-01-21 18:05:27 +00002468/// \param E The expression being returned from the function or block, or
2469/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002470///
Douglas Gregor86394412011-05-20 15:00:53 +00002471/// \param AllowFunctionParameter Whether we allow function parameters to
2472/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2473/// we re-use this logic to determine whether we should try to move as part of
2474/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002475///
2476/// \returns The NRVO candidate variable, if the return statement may use the
2477/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002478VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2479 Expr *E,
2480 bool AllowFunctionParameter) {
2481 if (!getLangOpts().CPlusPlus)
2482 return nullptr;
2483
2484 // - in a return statement in a function [where] ...
2485 // ... the expression is the name of a non-volatile automatic object ...
2486 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002487 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002488 return nullptr;
2489 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2490 if (!VD)
2491 return nullptr;
2492
2493 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2494 return VD;
2495 return nullptr;
2496}
2497
2498bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2499 bool AllowFunctionParameter) {
2500 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002501 // - in a return statement in a function with ...
2502 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002503 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002504 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002505 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002506 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002507 if (!VDType->isDependentType() &&
2508 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2509 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002511
John McCall03318c12011-11-11 03:57:31 +00002512 // ...object (other than a function or catch-clause parameter)...
2513 if (VD->getKind() != Decl::Var &&
2514 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002515 return false;
2516 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002517
John McCall03318c12011-11-11 03:57:31 +00002518 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002519 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002520
2521 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002522 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002523
2524 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002525 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002526
2527 // Variables with higher required alignment than their type's ABI
2528 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002529 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002530 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002531 return false;
John McCall03318c12011-11-11 03:57:31 +00002532
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002533 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002534}
2535
Douglas Gregor626fbed2011-01-21 21:08:57 +00002536/// \brief Perform the initialization of a potentially-movable value, which
2537/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002538///
2539/// This routine implements C++0x [class.copy]p33, which attempts to treat
2540/// returned lvalues as rvalues in certain cases (to prefer move construction),
2541/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002543Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2544 const VarDecl *NRVOCandidate,
2545 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002546 Expr *Value,
2547 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002548 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002549 // When the criteria for elision of a copy operation are met or would
2550 // be met save for the fact that the source object is a function
2551 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002552 // overload resolution to select the constructor for the copy is first
2553 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002554 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002555 if (AllowNRVO &&
2556 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002558 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002559
Douglas Gregorf282a762011-01-21 19:38:21 +00002560 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002561 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002562 = InitializationKind::CreateCopy(Value->getLocStart(),
2563 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002564 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
2566 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002567 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002568 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002569 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002570 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002571 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2572 StepEnd = Seq.step_end();
2573 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002574 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002575 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576
2577 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002578 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579
Douglas Gregorf282a762011-01-21 19:38:21 +00002580 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002581 = Constructor->getParamDecl(0)->getType()
2582 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002583
Douglas Gregorf282a762011-01-21 19:38:21 +00002584 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002585 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002586 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2587 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002589
Douglas Gregorf282a762011-01-21 19:38:21 +00002590 // Promote "AsRvalue" to the heap, since we now need this
2591 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002592 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002593 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002594
Douglas Gregorf282a762011-01-21 19:38:21 +00002595 // Complete type-checking the initialization of the return type
2596 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002597 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002598 }
2599 }
2600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002601
Douglas Gregorf282a762011-01-21 19:38:21 +00002602 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002603 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002604 // (again) now with the return value expression as written.
2605 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002606 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002607
Douglas Gregorf282a762011-01-21 19:38:21 +00002608 return Res;
2609}
2610
Richard Smith4db51c22013-09-25 05:02:54 +00002611/// \brief Determine whether the declared return type of the specified function
2612/// contains 'auto'.
2613static bool hasDeducedReturnType(FunctionDecl *FD) {
2614 const FunctionProtoType *FPT =
2615 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002616 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002617}
2618
Eli Friedman34b49062012-01-26 03:00:14 +00002619/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2620/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002621///
John McCalldadc5752010-08-24 06:29:42 +00002622StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002623Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2624 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002625 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002626 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002627 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002628 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002629
Richard Smith4db51c22013-09-25 05:02:54 +00002630 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2631 // In C++1y, the return type may involve 'auto'.
2632 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2633 FunctionDecl *FD = CurLambda->CallOperator;
2634 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002635 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002636
2637 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2638 assert(AT && "lost auto type from lambda return type");
2639 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2640 FD->setInvalidDecl();
2641 return StmtError();
2642 }
Alp Toker314cc812014-01-25 16:55:45 +00002643 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002644 } else if (CurCap->HasImplicitReturnType) {
2645 // For blocks/lambdas with implicit return types, we check each return
2646 // statement individually, and deduce the common return type when the block
2647 // or lambda is completed.
2648 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002649 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002650 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2651 if (Result.isInvalid())
2652 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002653 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002654
Richard Smith5a0e50c2014-12-19 22:10:51 +00002655 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2656 // when deducing a return type for a lambda-expression (or by extension
2657 // for a block). These rules differ from the stated C++11 rules only in
2658 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002659 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002660 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002661 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002662 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002663 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002664 if (RetValExp) {
2665 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2666 // initializer list, because it is not an expression (even
2667 // though we represent it as one). We still deduce 'void'.
2668 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2669 << RetValExp->getSourceRange();
2670 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002671
Jordan Rosed39e5f12012-07-02 21:19:23 +00002672 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002673 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002674
2675 // Although we'll properly infer the type of the block once it's completed,
2676 // make sure we provide a return type now for better error recovery.
2677 if (CurCap->ReturnType.isNull())
2678 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002679 }
Eli Friedman34b49062012-01-26 03:00:14 +00002680 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002681
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002682 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002683 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2684 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2685 return StmtError();
2686 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002687 } else if (CapturedRegionScopeInfo *CurRegion =
2688 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2689 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2690 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002691 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002692 assert(CurLambda && "unknown kind of captured scope");
2693 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2694 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002695 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2696 return StmtError();
2697 }
2698 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002699
Steve Naroffc540d662008-09-03 18:15:37 +00002700 // Otherwise, verify that this result type matches the previous one. We are
2701 // pickier with blocks than for normal functions because we don't have GCC
2702 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002703 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002704 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002705 // Delay processing for now. TODO: there are lots of dependent
2706 // types we can conclusively prove aren't void.
2707 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002708 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002709 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002710 (RetValExp->isTypeDependent() ||
2711 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002712 if (!getLangOpts().CPlusPlus &&
2713 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002714 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002715 else {
2716 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002717 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002718 }
Steve Naroffc540d662008-09-03 18:15:37 +00002719 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002720 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002721 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2722 } else if (!RetValExp->isTypeDependent()) {
2723 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002724
John McCall5500ef22011-08-17 22:09:46 +00002725 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2726 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2727 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002728
John McCall5500ef22011-08-17 22:09:46 +00002729 // In C++ the return statement is handled via a copy initialization.
2730 // the C version of which boils down to CheckSingleAssignmentConstraints.
2731 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2732 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2733 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002734 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002735 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2736 FnRetType, RetValExp);
2737 if (Res.isInvalid()) {
2738 // FIXME: Cleanup temporaries here, anyway?
2739 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002740 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002741 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002742 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002743 } else {
2744 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002745 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002746
John McCall75f92b52011-08-17 21:34:14 +00002747 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002748 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2749 if (ER.isInvalid())
2750 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002751 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002752 }
John McCall5500ef22011-08-17 22:09:46 +00002753 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2754 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002755
Jordan Rosed39e5f12012-07-02 21:19:23 +00002756 // If we need to check for the named return value optimization,
2757 // or if we need to infer the return type,
2758 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002759 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002760 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002761
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002762 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002763}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002764
Nico Weber72889432014-09-06 01:25:55 +00002765namespace {
2766/// \brief Marks all typedefs in all local classes in a type referenced.
2767///
2768/// In a function like
2769/// auto f() {
2770/// struct S { typedef int a; };
2771/// return S();
2772/// }
2773///
2774/// the local type escapes and could be referenced in some TUs but not in
2775/// others. Pretend that all local typedefs are always referenced, to not warn
2776/// on this. This isn't necessary if f has internal linkage, or the typedef
2777/// is private.
2778class LocalTypedefNameReferencer
2779 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2780public:
2781 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2782 bool VisitRecordType(const RecordType *RT);
2783private:
2784 Sema &S;
2785};
2786bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2787 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2788 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2789 R->isDependentType())
2790 return true;
2791 for (auto *TmpD : R->decls())
2792 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2793 if (T->getAccess() != AS_private || R->hasFriends())
2794 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2795 return true;
2796}
2797}
2798
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002799TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002800 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002801 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2802 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002803 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002804}
2805
Richard Smith2a7d4812013-05-04 07:00:32 +00002806/// Deduce the return type for a function from a returned expression, per
2807/// C++1y [dcl.spec.auto]p6.
2808bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2809 SourceLocation ReturnLoc,
2810 Expr *&RetExpr,
2811 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002812 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00002813 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002814
Richard Smithc58f38f2013-08-14 20:16:31 +00002815 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2816 // If the deduction is for a return statement and the initializer is
2817 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002818 Diag(RetExpr->getExprLoc(),
2819 getCurLambda() ? diag::err_lambda_return_init_list
2820 : diag::err_auto_fn_return_init_list)
2821 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002822 return true;
2823 }
2824
2825 if (FD->isDependentContext()) {
2826 // C++1y [dcl.spec.auto]p12:
2827 // Return type deduction [...] occurs when the definition is
2828 // instantiated even if the function body contains a return
2829 // statement with a non-type-dependent operand.
2830 assert(AT->isDeduced() && "should have deduced to dependent type");
2831 return false;
2832 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002833 // If the deduction is for a return statement and the initializer is
2834 // a braced-init-list, the program is ill-formed.
2835 if (isa<InitListExpr>(RetExpr)) {
2836 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2837 return true;
2838 }
2839
2840 // Otherwise, [...] deduce a value for U using the rules of template
2841 // argument deduction.
2842 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2843
2844 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2845 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2846 << OrigResultType.getType() << RetExpr->getType();
2847
2848 if (DAR != DAR_Succeeded)
2849 return true;
Nico Weber72889432014-09-06 01:25:55 +00002850
2851 // If a local type is part of the returned type, mark its fields as
2852 // referenced.
2853 LocalTypedefNameReferencer Referencer(*this);
2854 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00002855 } else {
2856 // In the case of a return with no operand, the initializer is considered
2857 // to be void().
2858 //
2859 // Deduction here can only succeed if the return type is exactly 'cv auto'
2860 // or 'decltype(auto)', so just check for that case directly.
2861 if (!OrigResultType.getType()->getAs<AutoType>()) {
2862 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2863 << OrigResultType.getType();
2864 return true;
2865 }
2866 // We always deduce U = void in this case.
2867 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2868 if (Deduced.isNull())
2869 return true;
2870 }
2871
2872 // If a function with a declared return type that contains a placeholder type
2873 // has multiple return statements, the return type is deduced for each return
2874 // statement. [...] if the type deduced is not the same in each deduction,
2875 // the program is ill-formed.
2876 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2877 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002878 if (!FD->isDependentContext() &&
2879 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002880 const LambdaScopeInfo *LambdaSI = getCurLambda();
2881 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2882 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2883 << NewAT->getDeducedType() << AT->getDeducedType()
2884 << true /*IsLambda*/;
2885 } else {
2886 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2887 << (AT->isDecltypeAuto() ? 1 : 0)
2888 << NewAT->getDeducedType() << AT->getDeducedType();
2889 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002890 return true;
2891 }
2892 } else if (!FD->isInvalidDecl()) {
2893 // Update all declarations of the function to have the deduced return type.
2894 Context.adjustDeducedFunctionResultType(FD, Deduced);
2895 }
2896
2897 return false;
2898}
2899
John McCalldadc5752010-08-24 06:29:42 +00002900StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002901Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2902 Scope *CurScope) {
2903 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2904 if (R.isInvalid()) {
2905 return R;
2906 }
2907
2908 if (VarDecl *VD =
2909 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2910 CurScope->addNRVOCandidate(VD);
2911 } else {
2912 CurScope->setNoNRVO();
2913 }
2914
2915 return R;
2916}
2917
2918StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002919 // Check for unexpanded parameter packs.
2920 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2921 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002922
Eli Friedman34b49062012-01-26 03:00:14 +00002923 if (isa<CapturingScopeInfo>(getCurFunction()))
2924 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002925
Chris Lattner79413952008-12-04 23:50:19 +00002926 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002927 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002928 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002929 bool isObjCMethod = false;
2930
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002931 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002932 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002933 if (FD->hasAttrs())
2934 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002935 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002936 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002937 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002938 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002939 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002940 isObjCMethod = true;
2941 if (MD->hasAttrs())
2942 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002943 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2944 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002945 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002946 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002947 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2948 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002949 }
2950 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002951 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002952
Richard Smith2a7d4812013-05-04 07:00:32 +00002953 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2954 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002955 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002956 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2957 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002958 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002959 FD->setInvalidDecl();
2960 return StmtError();
2961 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002962 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002963 }
2964 }
2965 }
2966
Richard Smithc58f38f2013-08-14 20:16:31 +00002967 bool HasDependentReturnType = FnRetType->isDependentType();
2968
Craig Topperc3ec1492014-05-26 06:22:03 +00002969 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002970 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002971 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002972 if (isa<InitListExpr>(RetValExp)) {
2973 // We simply never allow init lists as the return value of void
2974 // functions. This is compatible because this was never allowed before,
2975 // so there's no legacy code to deal with.
2976 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2977 int FunctionKind = 0;
2978 if (isa<ObjCMethodDecl>(CurDecl))
2979 FunctionKind = 1;
2980 else if (isa<CXXConstructorDecl>(CurDecl))
2981 FunctionKind = 2;
2982 else if (isa<CXXDestructorDecl>(CurDecl))
2983 FunctionKind = 3;
2984
2985 Diag(ReturnLoc, diag::err_return_init_list)
2986 << CurDecl->getDeclName() << FunctionKind
2987 << RetValExp->getSourceRange();
2988
2989 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002990 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002991 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002992 // C99 6.8.6.4p1 (ext_ since GCC warns)
2993 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002994 if (RetValExp->getType()->isVoidType()) {
2995 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2996 if (isa<CXXConstructorDecl>(CurDecl) ||
2997 isa<CXXDestructorDecl>(CurDecl))
2998 D = diag::err_ctor_dtor_returns_void;
2999 else
3000 D = diag::ext_return_has_void_expr;
3001 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003002 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003003 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003004 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003005 if (Result.isInvalid())
3006 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003007 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003008 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003009 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003010 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003011 // return of void in constructor/destructor is illegal in C++.
3012 if (D == diag::err_ctor_dtor_returns_void) {
3013 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3014 Diag(ReturnLoc, D)
3015 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3016 << RetValExp->getSourceRange();
3017 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003018 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003019 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003020 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003021 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003022
3023 int FunctionKind = 0;
3024 if (isa<ObjCMethodDecl>(CurDecl))
3025 FunctionKind = 1;
3026 else if (isa<CXXConstructorDecl>(CurDecl))
3027 FunctionKind = 2;
3028 else if (isa<CXXDestructorDecl>(CurDecl))
3029 FunctionKind = 3;
3030
Nick Lewycky1be750a2011-06-01 07:44:31 +00003031 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003032 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003033 << RetValExp->getSourceRange();
3034 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036
Sebastian Redleef474c2012-02-22 10:50:08 +00003037 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003038 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3039 if (ER.isInvalid())
3040 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003041 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003042 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
Craig Topperc3ec1492014-05-26 06:22:03 +00003045 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003046 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003047 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003048
David Majnemer2887ad32014-12-13 08:12:56 +00003049 unsigned DiagID;
3050 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3051 // C++11 [stmt.return]p2
3052 DiagID = diag::err_constexpr_return_missing_expr;
3053 FD->setInvalidDecl();
3054 } else if (getLangOpts().C99) {
3055 // C99 6.8.6.4p1 (ext_ since GCC warns)
3056 DiagID = diag::ext_return_missing_expr;
3057 } else {
3058 // C90 6.6.6.4p4
3059 DiagID = diag::warn_return_missing_expr;
3060 }
3061
3062 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003063 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003064 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003065 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003066
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003067 Result = new (Context) ReturnStmt(ReturnLoc);
3068 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003069 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003070 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003071
3072 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3073
3074 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3075 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3076 // function return.
3077
3078 // In C++ the return statement is handled via a copy initialization,
3079 // the C version of which boils down to CheckSingleAssignmentConstraints.
3080 if (RetValExp)
3081 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003082 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003083 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003085 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003086 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003088 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003089 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003090 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003091 return StmtError();
3092 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003093 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003094
3095 // If we have a related result type, we need to implicitly
3096 // convert back to the formal result type. We can't pretend to
3097 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003098 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003099 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003100 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3101 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003102 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3103 if (Res.isInvalid()) {
3104 // FIXME: Clean up temporaries here anyway?
3105 return StmtError();
3106 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003107 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003108 }
3109
Artyom Skrobov9f213442014-01-24 11:10:39 +00003110 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3111 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003113
John McCallacf0ee52010-10-08 02:01:28 +00003114 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003115 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3116 if (ER.isInvalid())
3117 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003118 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003119 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003120 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122
3123 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003124 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003125 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003126 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003127
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003128 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003129}
3130
John McCalldadc5752010-08-24 06:29:42 +00003131StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003132Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003133 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003134 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003135 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003136 if (Var && Var->isInvalidDecl())
3137 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003138
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003139 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003140}
3141
John McCalldadc5752010-08-24 06:29:42 +00003142StmtResult
John McCallb268a282010-08-23 23:25:46 +00003143Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003144 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003145}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003146
John McCalldadc5752010-08-24 06:29:42 +00003147StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003149 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003150 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003151 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3152
John McCallaab3e412010-08-25 08:40:02 +00003153 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003154 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003155 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3156 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003157}
3158
John McCall0bd3e402012-05-08 21:41:25 +00003159StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003160 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003161 ExprResult Result = DefaultLvalueConversion(Throw);
3162 if (Result.isInvalid())
3163 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003164
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003165 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003166 if (Result.isInvalid())
3167 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003168 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003169
Douglas Gregor2900c162010-04-22 21:44:01 +00003170 QualType ThrowType = Throw->getType();
3171 // Make sure the expression type is an ObjC pointer or "void *".
3172 if (!ThrowType->isDependentType() &&
3173 !ThrowType->isObjCObjectPointerType()) {
3174 const PointerType *PT = ThrowType->getAs<PointerType>();
3175 if (!PT || !PT->getPointeeType()->isVoidType())
3176 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3177 << Throw->getType() << Throw->getSourceRange());
3178 }
3179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003181 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003182}
3183
John McCalldadc5752010-08-24 06:29:42 +00003184StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003186 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003187 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003188 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3189
John McCallb268a282010-08-23 23:25:46 +00003190 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003191 // @throw without an expression designates a rethrow (which much occur
3192 // in the context of an @catch clause).
3193 Scope *AtCatchParent = CurScope;
3194 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3195 AtCatchParent = AtCatchParent->getParent();
3196 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003197 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198 }
John McCallb268a282010-08-23 23:25:46 +00003199 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003200}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003201
John McCalld9bb7432011-07-27 21:50:02 +00003202ExprResult
3203Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3204 ExprResult result = DefaultLvalueConversion(operand);
3205 if (result.isInvalid())
3206 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003207 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003208
3209 // Make sure the expression type is an ObjC pointer or "void *".
3210 QualType type = operand->getType();
3211 if (!type->isDependentType() &&
3212 !type->isObjCObjectPointerType()) {
3213 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003214 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3215 if (getLangOpts().CPlusPlus) {
3216 if (RequireCompleteType(atLoc, type,
3217 diag::err_incomplete_receiver_type))
3218 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3219 << type << operand->getSourceRange();
3220
3221 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3222 if (!result.isUsable())
3223 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3224 << type << operand->getSourceRange();
3225
3226 operand = result.get();
3227 } else {
3228 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3229 << type << operand->getSourceRange();
3230 }
3231 }
John McCalld9bb7432011-07-27 21:50:02 +00003232 }
3233
3234 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003235 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003236}
3237
John McCalldadc5752010-08-24 06:29:42 +00003238StmtResult
John McCallb268a282010-08-23 23:25:46 +00003239Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3240 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003241 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003242 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003243 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003244}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003245
3246/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3247/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003248StmtResult
John McCall48871652010-08-21 09:40:31 +00003249Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003250 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003251 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003252 return new (Context)
3253 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003254}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003255
John McCall31168b02011-06-15 23:02:42 +00003256StmtResult
3257Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3258 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003259 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003260}
3261
Dan Gohman28ade552010-07-26 21:25:24 +00003262namespace {
3263
Sebastian Redl63c4da02009-07-29 17:15:45 +00003264class TypeWithHandler {
3265 QualType t;
3266 CXXCatchStmt *stmt;
3267public:
3268 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3269 : t(type), stmt(statement) {}
3270
John McCall8ccfcb52009-09-24 19:53:00 +00003271 // An arbitrary order is fine as long as it places identical
3272 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003273 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003274 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003275 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003276 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003277 return false;
3278 else
3279 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3280 }
Mike Stump11289f42009-09-09 15:08:12 +00003281
Sebastian Redl63c4da02009-07-29 17:15:45 +00003282 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003283 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003284 }
Mike Stump11289f42009-09-09 15:08:12 +00003285
Sebastian Redl63c4da02009-07-29 17:15:45 +00003286 CXXCatchStmt *getCatchStmt() const { return stmt; }
3287 SourceLocation getTypeSpecStartLoc() const {
3288 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3289 }
3290};
3291
Dan Gohman28ade552010-07-26 21:25:24 +00003292}
3293
Sebastian Redl9b244a82008-12-22 21:35:02 +00003294/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3295/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003296StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3297 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003298 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003299 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003300 !getSourceManager().isInSystemHeader(TryLoc))
3301 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003302
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003303 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3304 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3305
Robert Wilhelmcafda822013-08-22 09:20:03 +00003306 const unsigned NumHandlers = Handlers.size();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003307 assert(NumHandlers > 0 &&
3308 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003309
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003310 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003311
3312 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003313 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003314 if (!Handler->getExceptionDecl()) {
3315 if (i < NumHandlers - 1)
3316 return StmtError(Diag(Handler->getLocStart(),
3317 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003318
Sebastian Redl63c4da02009-07-29 17:15:45 +00003319 continue;
3320 }
Mike Stump11289f42009-09-09 15:08:12 +00003321
Sebastian Redl63c4da02009-07-29 17:15:45 +00003322 const QualType CaughtType = Handler->getCaughtType();
3323 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3324 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003325 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003326
3327 // Detect handlers for the same type as an earlier one.
3328 if (NumHandlers > 1) {
3329 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003330
Sebastian Redl63c4da02009-07-29 17:15:45 +00003331 TypeWithHandler prev = TypesWithHandlers[0];
3332 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3333 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003334
Sebastian Redl63c4da02009-07-29 17:15:45 +00003335 if (curr == prev) {
3336 Diag(curr.getTypeSpecStartLoc(),
3337 diag::warn_exception_caught_by_earlier_handler)
3338 << curr.getCatchStmt()->getCaughtType().getAsString();
3339 Diag(prev.getTypeSpecStartLoc(),
3340 diag::note_previous_exception_handler)
3341 << prev.getCatchStmt()->getCaughtType().getAsString();
3342 }
Mike Stump11289f42009-09-09 15:08:12 +00003343
Sebastian Redl63c4da02009-07-29 17:15:45 +00003344 prev = curr;
3345 }
3346 }
Mike Stump11289f42009-09-09 15:08:12 +00003347
John McCallaab3e412010-08-25 08:40:02 +00003348 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003349
Sebastian Redl9b244a82008-12-22 21:35:02 +00003350 // FIXME: We should detect handlers that cannot catch anything because an
3351 // earlier handler catches a superclass. Need to find a method that is not
3352 // quadratic for this.
3353 // Neither of these are explicitly forbidden, but every compiler detects them
3354 // and warns.
3355
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003356 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003357}
John Wiegley1c0675e2011-04-28 01:08:34 +00003358
Warren Huntf6be4cb2014-07-25 20:52:51 +00003359StmtResult
3360Sema::ActOnSEHTryBlock(bool IsCXXTry,
3361 SourceLocation TryLoc,
3362 Stmt *TryBlock,
3363 Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003364 assert(TryBlock && Handler);
3365
3366 getCurFunction()->setHasBranchProtectedScope();
3367
Warren Huntf6be4cb2014-07-25 20:52:51 +00003368 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003369}
3370
3371StmtResult
3372Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3373 Expr *FilterExpr,
3374 Stmt *Block) {
3375 assert(FilterExpr && Block);
3376
3377 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003378 return StmtError(Diag(FilterExpr->getExprLoc(),
3379 diag::err_filter_expression_integral)
3380 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003381 }
3382
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003383 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003384}
3385
3386StmtResult
3387Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3388 Stmt *Block) {
3389 assert(Block);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003390 return SEHFinallyStmt::Create(Context,Loc,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003391}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003392
Nico Weberc7d05962014-07-06 22:32:59 +00003393StmtResult
3394Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003395 Scope *SEHTryParent = CurScope;
3396 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3397 SEHTryParent = SEHTryParent->getParent();
3398 if (!SEHTryParent)
3399 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3400
Nico Weber9b982072014-07-07 00:12:30 +00003401 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003402}
3403
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003404StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3405 bool IsIfExists,
3406 NestedNameSpecifierLoc QualifierLoc,
3407 DeclarationNameInfo NameInfo,
3408 Stmt *Nested)
3409{
3410 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003411 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003412 cast<CompoundStmt>(Nested));
3413}
3414
3415
Chad Rosier02a84392012-08-10 17:56:09 +00003416StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003417 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003418 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003419 UnqualifiedId &Name,
3420 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003421 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003422 SS.getWithLocInContext(Context),
3423 GetNameFromUnqualifiedId(Name),
3424 Nested);
3425}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003426
3427RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003428Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3429 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003430 DeclContext *DC = CurContext;
3431 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3432 DC = DC->getParent();
3433
Craig Topperc3ec1492014-05-26 06:22:03 +00003434 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003435 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003436 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3437 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003438 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003439 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003440
Alexey Bataev330de032014-10-29 12:21:55 +00003441 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003442 DC->addDecl(RD);
3443 RD->setImplicit();
3444 RD->startDefinition();
3445
Alexey Bataev9959db52014-05-06 10:08:46 +00003446 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003447 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003448 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003449 return RD;
3450}
3451
3452static void buildCapturedStmtCaptureList(
3453 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3454 SmallVectorImpl<Expr *> &CaptureInits,
3455 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3456
3457 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3458 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3459
3460 if (Cap->isThisCapture()) {
3461 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3462 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003463 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003464 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003465 } else if (Cap->isVLATypeCapture()) {
3466 Captures.push_back(
3467 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3468 CaptureInits.push_back(nullptr);
3469 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003470 }
3471
3472 assert(Cap->isReferenceCapture() &&
3473 "non-reference capture not yet implemented");
3474
3475 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3476 CapturedStmt::VCK_ByRef,
3477 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003478 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003479 }
3480}
3481
3482void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003483 CapturedRegionKind Kind,
3484 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003485 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003486 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003487
Alexey Bataev9959db52014-05-06 10:08:46 +00003488 // Build the context parameter
3489 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3490 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3491 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3492 ImplicitParamDecl *Param
3493 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3494 DC->addDecl(Param);
3495
3496 CD->setContextParam(0, Param);
3497
3498 // Enter the capturing scope for this captured region.
3499 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3500
3501 if (CurScope)
3502 PushDeclContext(CurScope, CD);
3503 else
3504 CurContext = CD;
3505
3506 PushExpressionEvaluationContext(PotentiallyEvaluated);
3507}
3508
3509void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3510 CapturedRegionKind Kind,
3511 ArrayRef<CapturedParamNameType> Params) {
3512 CapturedDecl *CD = nullptr;
3513 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3514
3515 // Build the context parameter
3516 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3517 bool ContextIsFound = false;
3518 unsigned ParamNum = 0;
3519 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3520 E = Params.end();
3521 I != E; ++I, ++ParamNum) {
3522 if (I->second.isNull()) {
3523 assert(!ContextIsFound &&
3524 "null type has been found already for '__context' parameter");
3525 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3526 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3527 ImplicitParamDecl *Param
3528 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3529 DC->addDecl(Param);
3530 CD->setContextParam(ParamNum, Param);
3531 ContextIsFound = true;
3532 } else {
3533 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3534 ImplicitParamDecl *Param
3535 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3536 DC->addDecl(Param);
3537 CD->setParam(ParamNum, Param);
3538 }
3539 }
3540 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003541 if (!ContextIsFound) {
3542 // Add __context implicitly if it is not specified.
3543 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3544 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3545 ImplicitParamDecl *Param =
3546 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3547 DC->addDecl(Param);
3548 CD->setContextParam(ParamNum, Param);
3549 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003550 // Enter the capturing scope for this captured region.
3551 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3552
3553 if (CurScope)
3554 PushDeclContext(CurScope, CD);
3555 else
3556 CurContext = CD;
3557
3558 PushExpressionEvaluationContext(PotentiallyEvaluated);
3559}
3560
Wei Pan17fbf6e2013-05-04 03:59:06 +00003561void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003562 DiscardCleanupsInEvaluationContext();
3563 PopExpressionEvaluationContext();
3564
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003565 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3566 RecordDecl *Record = RSI->TheRecordDecl;
3567 Record->setInvalidDecl();
3568
Aaron Ballman62e47c42014-03-10 13:43:55 +00003569 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003570 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3571 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003572
Wei Pan17fbf6e2013-05-04 03:59:06 +00003573 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003574 PopFunctionScopeInfo();
3575}
3576
3577StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3578 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3579
3580 SmallVector<CapturedStmt::Capture, 4> Captures;
3581 SmallVector<Expr *, 4> CaptureInits;
3582 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3583
3584 CapturedDecl *CD = RSI->TheCapturedDecl;
3585 RecordDecl *RD = RSI->TheRecordDecl;
3586
Wei Pan17fbf6e2013-05-04 03:59:06 +00003587 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3588 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003589 CaptureInits, CD, RD);
3590
3591 CD->setBody(Res->getCapturedStmt());
3592 RD->completeDefinition();
3593
Wei Pan17fbf6e2013-05-04 03:59:06 +00003594 DiscardCleanupsInEvaluationContext();
3595 PopExpressionEvaluationContext();
3596
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003597 PopDeclContext();
3598 PopFunctionScopeInfo();
3599
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003600 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003601}