blob: 8d2a3258b10b41a1a8f8d0e720d112300b1b676e [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;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000188 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000189 // In most cases, we don't want to warn if the expression is written in a
190 // macro body, or if the macro comes from a system header. If the offending
191 // expression is a call to a function with the warn_unused_result attribute,
192 // we warn no matter the location. Because of the order in which the various
193 // checks need to happen, we factor out the macro-related test here.
194 bool ShouldSuppress =
195 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
196 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000197
Eli Friedmanc11535c2012-05-24 00:47:05 +0000198 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000199 SourceLocation Loc;
200 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000201 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000202 return;
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattner6dc7e572012-08-31 22:39:21 +0000204 // If this is a GNU statement expression expanded from a macro, it is probably
205 // unused because it is a function-like macro that can be used as either an
206 // expression or statement. Don't warn, because it is almost certainly a
207 // false positive.
208 if (isa<StmtExpr>(E) && Loc.isMacroID())
209 return;
210
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000211 // Okay, we have an unused result. Depending on what the base expression is,
212 // we might want to make a more specific diagnostic. Check for one of these
213 // cases now.
214 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000215 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000216 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000217 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
218 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000219
Chandler Carruthe2669392011-08-17 09:34:37 +0000220 if (DiagnoseUnusedComparison(*this, E))
221 return;
222
Eli Friedmanc11535c2012-05-24 00:47:05 +0000223 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000224 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000225 if (E->getType()->isVoidType())
226 return;
227
Chris Lattner1a6babf2009-10-13 04:53:48 +0000228 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000229 // a more specific message to make it clear what is happening. If the call
230 // is written in a macro body, only warn if it has the warn_unused_result
231 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000232 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000233 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000234 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000235 return;
236 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000237 if (ShouldSuppress)
238 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000239 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000240 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
241 return;
242 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000243 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
245 return;
246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000247 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000248 } else if (ShouldSuppress)
249 return;
250
251 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000252 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000253 Diag(Loc, diag::err_arc_unused_init_message) << R1;
254 return;
255 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000256 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000257 if (MD) {
258 if (MD->hasAttr<WarnUnusedResultAttr>()) {
259 Diag(Loc, diag::warn_unused_result) << R1 << R2;
260 return;
261 }
262 if (MD->isPropertyAccessor()) {
263 Diag(Loc, diag::warn_unused_property_expr);
264 return;
265 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000266 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000267 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
268 const Expr *Source = POE->getSyntacticForm();
269 if (isa<ObjCSubscriptRefExpr>(Source))
270 DiagID = diag::warn_unused_container_subscript_expr;
271 else
272 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000273 } else if (const CXXFunctionalCastExpr *FC
274 = dyn_cast<CXXFunctionalCastExpr>(E)) {
275 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
276 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
277 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 }
John McCall2351cb92010-04-06 22:24:14 +0000279 // Diagnose "(void*) blah" as a typo for "(void) blah".
280 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
281 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
282 QualType T = TI->getType();
283
284 // We really do want to use the non-canonical type here.
285 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000286 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000287
288 Diag(Loc, diag::warn_unused_voidptr)
289 << FixItHint::CreateRemoval(TL.getStarLoc());
290 return;
291 }
292 }
293
Eli Friedmanc11535c2012-05-24 00:47:05 +0000294 if (E->isGLValue() && E->getType().isVolatileQualified()) {
295 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
296 return;
297 }
298
Craig Topperc3ec1492014-05-26 06:22:03 +0000299 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000300}
301
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000302void Sema::ActOnStartOfCompoundStmt() {
303 PushCompoundScope();
304}
305
306void Sema::ActOnFinishOfCompoundStmt() {
307 PopCompoundScope();
308}
309
310sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
311 return getCurFunction()->CompoundScopes.back();
312}
313
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000314StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
315 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
316 const unsigned NumElts = Elts.size();
317
Chris Lattnerd864daf2007-08-27 04:29:41 +0000318 // If we're in C89 mode, check that we don't have any decls after stmts. If
319 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000320 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000321 // Note that __extension__ can be around a decl.
322 unsigned i = 0;
323 // Skip over all declarations.
324 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
325 /*empty*/;
326
327 // We found the end of the list or a statement. Scan for another declstmt.
328 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
329 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000330
Chris Lattnerd864daf2007-08-27 04:29:41 +0000331 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000332 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000333 Diag(D->getLocation(), diag::ext_mixed_decls_code);
334 }
335 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000336 // Warn about unused expressions in statements.
337 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000338 // Ignore statements that are last in a statement expression.
339 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000340 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000341
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000342 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000343 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000344
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000345 // Check for suspicious empty body (null statement) in `for' and `while'
346 // statements. Don't do anything for template instantiations, this just adds
347 // noise.
348 if (NumElts != 0 && !CurrentInstantiationScope &&
349 getCurCompoundScope().HasEmptyLoopBodies) {
350 for (unsigned i = 0; i != NumElts - 1; ++i)
351 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
352 }
353
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000354 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000355}
356
John McCalldadc5752010-08-24 06:29:42 +0000357StmtResult
John McCallb268a282010-08-23 23:25:46 +0000358Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
359 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000360 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000361 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000362
John McCallaab3e412010-08-25 08:40:02 +0000363 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000364 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000365 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000366 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000367
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000368 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000369 // C99 6.8.4.2p3: The expression shall be an integer constant.
370 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000371 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000372 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000373 if (!LHSVal)
374 return StmtError();
375 }
Richard Smithf8379a02012-01-18 23:55:52 +0000376
377 // GCC extension: The expression shall be an integer constant.
378
Richard Smithf4c51d92012-02-04 09:53:13 +0000379 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000380 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000381 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000382 }
383 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000384
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000385 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000386 getLangOpts().CPlusPlus11).get();
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000387 if (RHSVal)
388 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000389 getLangOpts().CPlusPlus11).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000390
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000391 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
392 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000393 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000394 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000395}
396
Chris Lattner34a22092009-03-04 04:23:07 +0000397/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000398void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000399 DiagnoseUnusedExprResult(SubStmt);
400
Chris Lattner34a22092009-03-04 04:23:07 +0000401 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000402 CS->setSubStmt(SubStmt);
403}
404
John McCalldadc5752010-08-24 06:29:42 +0000405StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000406Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000407 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000408 DiagnoseUnusedExprResult(SubStmt);
409
John McCallaab3e412010-08-25 08:40:02 +0000410 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000411 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000412 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000413 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000414
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000415 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000416 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000417 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000418}
419
John McCalldadc5752010-08-24 06:29:42 +0000420StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000421Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
422 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000423 // If the label was multiply defined, reject it now.
424 if (TheDecl->getStmt()) {
425 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
426 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000427 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000428 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000429
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000430 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000431 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
432 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000433 if (!TheDecl->isGnuLocal()) {
434 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000435 TheDecl->setLocation(IdentLoc);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000436 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000437 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000438}
439
Richard Smithc202b282012-04-14 00:33:13 +0000440StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000441 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000442 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000443 // Fill in the declaration and return it.
444 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000445 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000446}
447
John McCalldadc5752010-08-24 06:29:42 +0000448StmtResult
John McCall48871652010-08-21 09:40:31 +0000449Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000450 Stmt *thenStmt, SourceLocation ElseLoc,
451 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000452 // If the condition was invalid, discard the if statement. We could recover
453 // better by replacing it with a valid expr, but don't do that yet.
454 if (!CondVal.get() && !CondVar) {
455 getCurFunction()->setHasDroppedStmt();
456 return StmtError();
457 }
458
John McCalldadc5752010-08-24 06:29:42 +0000459 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000460
Craig Topperc3ec1492014-05-26 06:22:03 +0000461 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000462 if (CondVar) {
463 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000464 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000465 if (CondResult.isInvalid())
466 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000467 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000468 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000469 if (!ConditionExpr)
470 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000471
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000472 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000473
John McCallb268a282010-08-23 23:25:46 +0000474 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000475 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
476 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000477 }
478
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000479 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000480
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000481 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
482 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000483}
Steve Naroff86272ea2007-05-29 02:14:17 +0000484
Chris Lattner67998452007-08-23 18:29:20 +0000485namespace {
486 struct CaseCompareFunctor {
487 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
488 const llvm::APSInt &RHS) {
489 return LHS.first < RHS;
490 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000491 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
492 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
493 return LHS.first < RHS.first;
494 }
Chris Lattner67998452007-08-23 18:29:20 +0000495 bool operator()(const llvm::APSInt &LHS,
496 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
497 return LHS < RHS.first;
498 }
499 };
500}
501
Chris Lattner4b2ff022007-09-21 18:15:22 +0000502/// CmpCaseVals - Comparison predicate for sorting case values.
503///
504static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
505 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
506 if (lhs.first < rhs.first)
507 return true;
508
509 if (lhs.first == rhs.first &&
510 lhs.second->getCaseLoc().getRawEncoding()
511 < rhs.second->getCaseLoc().getRawEncoding())
512 return true;
513 return false;
514}
515
Douglas Gregorbd6839732010-02-08 22:24:16 +0000516/// CmpEnumVals - Comparison predicate for sorting enumeration values.
517///
518static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
519 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
520{
521 return lhs.first < rhs.first;
522}
523
524/// EqEnumVals - Comparison preficate for uniqing enumeration values.
525///
526static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
527 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
528{
529 return lhs.first == rhs.first;
530}
531
Chris Lattnera96d4272009-10-16 16:45:22 +0000532/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
533/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000534static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
535 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
536 expr = cleanups->getSubExpr();
537 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
538 if (impcast->getCastKind() != CK_IntegralCast) break;
539 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000540 }
541 return expr->getType();
542}
543
John McCalldadc5752010-08-24 06:29:42 +0000544StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000546 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000547 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000548
Craig Topperc3ec1492014-05-26 06:22:03 +0000549 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000550 if (CondVar) {
551 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000552 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
553 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000554 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000556 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
John McCallb268a282010-08-23 23:25:46 +0000559 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000560 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561
Douglas Gregore2b37442012-05-04 22:38:52 +0000562 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
563 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000564
Douglas Gregore2b37442012-05-04 22:38:52 +0000565 public:
566 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000567 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
568 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000569
Craig Toppere14c0f82014-03-12 04:55:44 +0000570 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
571 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000572 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
573 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000574
Craig Toppere14c0f82014-03-12 04:55:44 +0000575 SemaDiagnosticBuilder diagnoseIncomplete(
576 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000577 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
578 << T << Cond->getSourceRange();
579 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000580
Craig Toppere14c0f82014-03-12 04:55:44 +0000581 SemaDiagnosticBuilder diagnoseExplicitConv(
582 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000583 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
584 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000585
Craig Toppere14c0f82014-03-12 04:55:44 +0000586 SemaDiagnosticBuilder noteExplicitConv(
587 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000588 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
589 << ConvTy->isEnumeralType() << ConvTy;
590 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000591
Craig Toppere14c0f82014-03-12 04:55:44 +0000592 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
593 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000594 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
595 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000596
Craig Toppere14c0f82014-03-12 04:55:44 +0000597 SemaDiagnosticBuilder noteAmbiguous(
598 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000599 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
600 << ConvTy->isEnumeralType() << ConvTy;
601 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000602
Craig Toppere14c0f82014-03-12 04:55:44 +0000603 SemaDiagnosticBuilder diagnoseConversion(
604 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000605 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000606 }
607 } SwitchDiagnoser(Cond);
608
Richard Smithccc11812013-05-21 19:05:48 +0000609 CondResult =
610 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000611 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000612 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613
John McCall5939b162011-08-06 07:30:58 +0000614 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
615 CondResult = UsualUnaryConversions(Cond);
616 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000617 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000618
John McCall48871652010-08-21 09:40:31 +0000619 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000620 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000621 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000622 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000623 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000624 }
John McCalla95172b2010-08-01 00:26:45 +0000625
John McCallaab3e412010-08-25 08:40:02 +0000626 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
John McCallb268a282010-08-23 23:25:46 +0000628 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000629 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000630 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000631}
632
Gabor Greif16e02862010-10-01 22:05:14 +0000633static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000634 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000635 Val.setIsSigned(IsSigned);
636}
637
Richard Smith077d0832014-08-04 00:40:48 +0000638/// Check the specified case value is in range for the given unpromoted switch
639/// type.
640static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
641 unsigned UnpromotedWidth, bool UnpromotedSign) {
642 // If the case value was signed and negative and the switch expression is
643 // unsigned, don't bother to warn: this is implementation-defined behavior.
644 // FIXME: Introduce a second, default-ignored warning for this case?
645 if (UnpromotedWidth < Val.getBitWidth()) {
646 llvm::APSInt ConvVal(Val);
647 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
648 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
649 // FIXME: Use different diagnostics for overflow in conversion to promoted
650 // type versus "switch expression cannot have this value". Use proper
651 // IntRange checking rather than just looking at the unpromoted type here.
652 if (ConvVal != Val)
653 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
654 << ConvVal.toString(10);
655 }
656}
657
Dmitri Gribenko58683752013-12-05 22:52:07 +0000658/// Returns true if we should emit a diagnostic about this case expression not
659/// being a part of the enum used in the switch controlling expression.
660static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
661 const EnumDecl *ED,
662 const Expr *CaseExpr) {
663 // Don't warn if the 'case' expression refers to a static const variable of
664 // the enum type.
665 CaseExpr = CaseExpr->IgnoreParenImpCasts();
666 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
667 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
668 if (!VD->hasGlobalStorage())
669 return true;
670 QualType VarType = VD->getType();
671 if (!VarType.isConstQualified())
672 return true;
673 QualType EnumType = Ctx.getTypeDeclType(ED);
674 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
675 return false;
676 }
677 }
678 return true;
679}
680
John McCalldadc5752010-08-24 06:29:42 +0000681StmtResult
John McCallb268a282010-08-23 23:25:46 +0000682Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
683 Stmt *BodyStmt) {
684 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000685 assert(SS == getCurFunction()->SwitchStack.back() &&
686 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000687
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000688 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000689 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000690 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000691
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000692 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000693 if (!CondExpr) return StmtError();
694
695 QualType CondType = CondExpr->getType();
696
John McCalld3dfbd62010-05-18 03:19:21 +0000697 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000698 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000699 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000700
Chris Lattnera96d4272009-10-16 16:45:22 +0000701 // C++ 6.4.2.p2:
702 // Integral promotions are performed (on the switch condition).
703 //
704 // A case value unrepresentable by the original switch condition
705 // type (before the promotion) doesn't make sense, even when it can
706 // be represented by the promoted type. Therefore we need to find
707 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000708 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000709 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000711 // appropriate type now, just return an error.
712 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000713 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000714
Chris Lattner4ebae652010-04-16 23:34:13 +0000715 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000716 // switch(bool_expr) {...} is often a programmer error, e.g.
717 // switch(n && mask) { ... } // Doh - should be "n & mask".
718 // One can always use an if statement instead of switch(bool_expr).
719 Diag(SwitchLoc, diag::warn_bool_switch_condition)
720 << CondExpr->getSourceRange();
721 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000722 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000723
Richard Smith077d0832014-08-04 00:40:48 +0000724 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000725 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000726 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000727 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000728 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
729 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
730
731 // Get the width and signedness that the condition might actually have, for
732 // warning purposes.
733 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
734 // type.
735 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000736 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000737 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000738 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000739
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000740 // Accumulate all of the case values in a vector so that we can sort them
741 // and detect duplicates. This vector contains the APInt for the case after
742 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000743 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000744 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000746 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000747 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
748 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000749
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000751
Chris Lattner10cb5e52007-08-23 06:23:56 +0000752 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000754 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000755 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000756
Anders Carlsson51873c22007-07-22 07:07:56 +0000757 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000758 if (TheDefaultStmt) {
759 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000760 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000761
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000762 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000763 // we'll return a valid AST. This requires recursing down the AST and
764 // finding it, not something we are set up to do right now. For now,
765 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000766 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000767 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000768 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000769
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000770 } else {
771 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000772
Chris Lattnera65e1f32008-01-16 19:17:22 +0000773 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000774
775 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
776 HasDependentValue = true;
777 break;
778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
Richard Smithf8379a02012-01-18 23:55:52 +0000780 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000781
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000782 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000783 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
784 // constant expression of the promoted type of the switch condition.
785 ExprResult ConvLo =
786 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
787 if (ConvLo.isInvalid()) {
788 CaseListIsErroneous = true;
789 continue;
790 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000791 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000792 } else {
793 // We already verified that the expression has a i-c-e value (C99
794 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000795 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000796
797 // If the LHS is not the same type as the condition, insert an implicit
798 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000799 Lo = DefaultLvalueConversion(Lo).get();
800 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000801 }
802
Richard Smith077d0832014-08-04 00:40:48 +0000803 // Check the unconverted value is within the range of possible values of
804 // the switch expression.
805 checkCaseValue(*this, Lo->getLocStart(), LoVal,
806 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
807
808 // Convert the value to the same width/sign as the condition.
809 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000810
Chris Lattnera65e1f32008-01-16 19:17:22 +0000811 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000812
Chris Lattner10cb5e52007-08-23 06:23:56 +0000813 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000814 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000815 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000816 CS->getRHS()->isValueDependent()) {
817 HasDependentValue = true;
818 break;
819 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000820 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000821 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000822 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000823 }
824 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000825
826 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000827 // If we don't have a default statement, check whether the
828 // condition is constant.
829 llvm::APSInt ConstantCondValue;
830 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000831 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000832 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
833 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000834 assert(!HasConstantCond ||
835 (ConstantCondValue.getBitWidth() == CondWidth &&
836 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000837 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000838 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000839
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000840 // Sort all the scalar case values so we can easily detect duplicates.
841 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
842
843 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000844 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
845 if (ShouldCheckConstantCond &&
846 CaseVals[i].first == ConstantCondValue)
847 ShouldCheckConstantCond = false;
848
849 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000850 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000851 // First, determine if either case value has a name
852 StringRef PrevString, CurrString;
853 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
854 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
855 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
856 PrevString = DeclRef->getDecl()->getName();
857 }
858 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
859 CurrString = DeclRef->getDecl()->getName();
860 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000861 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000862 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000863
864 if (PrevString == CurrString)
865 Diag(CaseVals[i].second->getLHS()->getLocStart(),
866 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000867 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000868 else
869 Diag(CaseVals[i].second->getLHS()->getLocStart(),
870 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000871 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
872 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000873 CaseValStr;
874
John McCalld3dfbd62010-05-18 03:19:21 +0000875 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000876 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000877 // FIXME: We really want to remove the bogus case stmt from the
878 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000879 CaseListIsErroneous = true;
880 }
881 }
882 }
Mike Stump11289f42009-09-09 15:08:12 +0000883
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000884 // Detect duplicate case ranges, which usually don't exist at all in
885 // the first place.
886 if (!CaseRanges.empty()) {
887 // Sort all the case ranges by their low value so we can easily detect
888 // overlaps between ranges.
889 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000890
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000891 // Scan the ranges, computing the high values and removing empty ranges.
892 std::vector<llvm::APSInt> HiVals;
893 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000894 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000895 CaseStmt *CR = CaseRanges[i].second;
896 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000897 llvm::APSInt HiVal;
898
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000899 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000900 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
901 // constant expression of the promoted type of the switch condition.
902 ExprResult ConvHi =
903 CheckConvertedConstantExpression(Hi, CondType, HiVal,
904 CCEK_CaseValue);
905 if (ConvHi.isInvalid()) {
906 CaseListIsErroneous = true;
907 continue;
908 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000909 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000910 } else {
911 HiVal = Hi->EvaluateKnownConstInt(Context);
912
913 // If the RHS is not the same type as the condition, insert an
914 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000915 Hi = DefaultLvalueConversion(Hi).get();
916 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000917 }
Mike Stump11289f42009-09-09 15:08:12 +0000918
Richard Smith077d0832014-08-04 00:40:48 +0000919 // Check the unconverted value is within the range of possible values of
920 // the switch expression.
921 checkCaseValue(*this, Hi->getLocStart(), HiVal,
922 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
923
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000924 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000925 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000926
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000927 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000928
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000929 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000930 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000931 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
932 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000933 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000934 CaseRanges.erase(CaseRanges.begin()+i);
935 --i, --e;
936 continue;
937 }
John McCalld3dfbd62010-05-18 03:19:21 +0000938
939 if (ShouldCheckConstantCond &&
940 LoVal <= ConstantCondValue &&
941 ConstantCondValue <= HiVal)
942 ShouldCheckConstantCond = false;
943
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000944 HiVals.push_back(HiVal);
945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000947 // Rescan the ranges, looking for overlap with singleton values and other
948 // ranges. Since the range list is sorted, we only need to compare case
949 // ranges with their neighbors.
950 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
951 llvm::APSInt &CRLo = CaseRanges[i].first;
952 llvm::APSInt &CRHi = HiVals[i];
953 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000954
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000955 // Check to see whether the case range overlaps with any
956 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +0000957 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000958 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000959
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000960 // Find the smallest value >= the lower bound. If I is in the
961 // case range, then we have overlap.
962 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
963 CaseVals.end(), CRLo,
964 CaseCompareFunctor());
965 if (I != CaseVals.end() && I->first < CRHi) {
966 OverlapVal = I->first; // Found overlap with scalar.
967 OverlapStmt = I->second;
968 }
Mike Stump11289f42009-09-09 15:08:12 +0000969
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000970 // Find the smallest value bigger than the upper bound.
971 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
972 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
973 OverlapVal = (I-1)->first; // Found overlap with scalar.
974 OverlapStmt = (I-1)->second;
975 }
Mike Stump11289f42009-09-09 15:08:12 +0000976
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000977 // Check to see if this case stmt overlaps with the subsequent
978 // case range.
979 if (i && CRLo <= HiVals[i-1]) {
980 OverlapVal = HiVals[i-1]; // Found overlap with range.
981 OverlapStmt = CaseRanges[i-1].second;
982 }
Mike Stump11289f42009-09-09 15:08:12 +0000983
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000984 if (OverlapStmt) {
985 // If we have a duplicate, report it.
986 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
987 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000988 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000989 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000990 // FIXME: We really want to remove the bogus case stmt from the
991 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 CaseListIsErroneous = true;
993 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000994 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000995 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000996
John McCalld3dfbd62010-05-18 03:19:21 +0000997 // Complain if we have a constant condition and we didn't find a match.
998 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
999 // TODO: it would be nice if we printed enums as enums, chars as
1000 // chars, etc.
1001 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1002 << ConstantCondValue.toString(10)
1003 << CondExpr->getSourceRange();
1004 }
1005
1006 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001007 // values. We only issue a warning if there is not 'default:', but
1008 // we still do the analysis to preserve this information in the AST
1009 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001010 //
Chris Lattner51679082010-09-16 17:09:42 +00001011 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001012
Douglas Gregorbd6839732010-02-08 22:24:16 +00001013 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001014 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001015 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001016 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +00001017 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001018 EnumValsTy EnumVals;
1019
John McCalld3dfbd62010-05-18 03:19:21 +00001020 // Gather all enum values, set their type and sort them,
1021 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001022 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001023 llvm::APSInt Val = EDI->getInitVal();
1024 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001025 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001026 }
1027 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +00001028 EnumValsTy::iterator EIend =
1029 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001030
1031 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001032 EnumValsTy::const_iterator EI = EnumVals.begin();
1033 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1034 CI != CaseVals.end(); CI++) {
1035 while (EI != EIend && EI->first < CI->first)
1036 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001037 if (EI == EIend || EI->first > CI->first) {
1038 Expr *CaseExpr = CI->second->getLHS();
1039 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1040 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1041 << CondTypeBeforePromotion;
1042 }
David Blaikiee476f972012-01-22 02:31:55 +00001043 }
1044 // See which of case ranges aren't in enum
1045 EI = EnumVals.begin();
1046 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1047 RI != CaseRanges.end() && EI != EIend; RI++) {
1048 while (EI != EIend && EI->first < RI->first)
1049 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050
David Blaikiee476f972012-01-22 02:31:55 +00001051 if (EI == EIend || EI->first != RI->first) {
Dmitri Gribenko58683752013-12-05 22:52:07 +00001052 Expr *CaseExpr = RI->second->getLHS();
1053 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1054 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1055 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +00001056 }
David Blaikiee476f972012-01-22 02:31:55 +00001057
Chad Rosier02a84392012-08-10 17:56:09 +00001058 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001059 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1060 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1061 while (EI != EIend && EI->first < Hi)
1062 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001063 if (EI == EIend || EI->first != Hi) {
1064 Expr *CaseExpr = RI->second->getRHS();
1065 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1066 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1067 << CondTypeBeforePromotion;
1068 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070
Ted Kremenekc42f3452010-09-09 00:05:53 +00001071 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +00001072 CaseValsTy::const_iterator CI = CaseVals.begin();
1073 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001074 bool hasCasesNotInSwitch = false;
1075
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001076 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001077
David Blaikiee476f972012-01-22 02:31:55 +00001078 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001079 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001080 while (CI != CaseVals.end() && CI->first < EI->first)
1081 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001082
Douglas Gregorbd6839732010-02-08 22:24:16 +00001083 if (CI != CaseVals.end() && CI->first == EI->first)
1084 continue;
1085
Ted Kremenekc42f3452010-09-09 00:05:53 +00001086 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001087 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001088 llvm::APSInt Hi =
1089 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001090 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001091 if (EI->first <= Hi)
1092 break;
1093 }
1094
Ted Kremenekc42f3452010-09-09 00:05:53 +00001095 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001096 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001097 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001098 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100
David Blaikie60ac6382012-01-23 04:46:12 +00001101 if (TheDefaultStmt && UnhandledNames.empty())
1102 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001103
Chris Lattner51679082010-09-16 17:09:42 +00001104 // Produce a nice diagnostic if multiple values aren't handled.
1105 switch (UnhandledNames.size()) {
1106 case 0: break;
1107 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001108 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001109 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001110 << UnhandledNames[0];
1111 break;
1112 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001113 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001114 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001115 << UnhandledNames[0] << UnhandledNames[1];
1116 break;
1117 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001118 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1119 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001120 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1121 break;
1122 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001123 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1124 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001125 << (unsigned)UnhandledNames.size()
1126 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1127 break;
1128 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001129
1130 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001131 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001132 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001133 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001134
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001135 if (BodyStmt)
1136 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1137 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001138
Mike Stump87c57ac2009-05-16 07:39:55 +00001139 // FIXME: If the case list was broken is some way, we don't have a good system
1140 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001141 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001142 return StmtError();
1143
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001144 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001145}
1146
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001147void
1148Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1149 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001150 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001151 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001152
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001153 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001154 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001155 SrcType->isIntegerType()) {
1156 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1157 SrcExpr->isIntegerConstantExpr(Context)) {
1158 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001159 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001160 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1161
1162 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001163 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001164 const EnumDecl *ED = ET->getDecl();
Joey Gouly1ba27332013-06-06 13:48:00 +00001165 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1166 EnumValsTy;
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001167 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001168
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001169 // Gather all enum values, set their type and sort them,
1170 // allowing easier comparison with rhs constant.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001171 for (auto *EDI : ED->enumerators()) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001172 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly1ba27332013-06-06 13:48:00 +00001173 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001174 EnumVals.push_back(std::make_pair(Val, EDI));
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001175 }
1176 if (EnumVals.empty())
1177 return;
1178 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1179 EnumValsTy::iterator EIend =
Joey Gouly1ba27332013-06-06 13:48:00 +00001180 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001181
Joey Gouly1ba27332013-06-06 13:48:00 +00001182 // See which values aren't in the enum.
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001183 EnumValsTy::const_iterator EI = EnumVals.begin();
1184 while (EI != EIend && EI->first < RhsVal)
1185 EI++;
1186 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly1ba27332013-06-06 13:48:00 +00001187 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001188 << DstType.getUnqualifiedType();
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001189 }
1190 }
1191 }
1192}
1193
John McCalldadc5752010-08-24 06:29:42 +00001194StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001195Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001196 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001197 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001198
Craig Topperc3ec1492014-05-26 06:22:03 +00001199 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001200 if (CondVar) {
1201 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001202 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001203 if (CondResult.isInvalid())
1204 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001205 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001206 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001207 if (!ConditionExpr)
1208 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001209 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001210
John McCallb268a282010-08-23 23:25:46 +00001211 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001212
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001213 if (isa<NullStmt>(Body))
1214 getCurCompoundScope().setHasEmptyLoopBodies();
1215
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001216 return new (Context)
1217 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001218}
1219
John McCalldadc5752010-08-24 06:29:42 +00001220StmtResult
John McCallb268a282010-08-23 23:25:46 +00001221Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001222 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001223 Expr *Cond, SourceLocation CondRParen) {
1224 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001225
Serge Pavlov09f99242014-01-23 15:05:00 +00001226 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001227 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001228 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001229 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001230 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001231
Richard Smith945f8d32013-01-14 22:39:08 +00001232 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001233 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001234 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001235 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236
John McCallb268a282010-08-23 23:25:46 +00001237 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001238
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001239 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001240}
1241
Richard Trieu451a5db2012-04-30 18:01:30 +00001242namespace {
1243 // This visitor will traverse a conditional statement and store all
1244 // the evaluated decls into a vector. Simple is set to true if none
1245 // of the excluded constructs are used.
1246 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001247 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001248 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001249 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001250 public:
1251 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001252
Craig Topper4dd9b432014-08-17 23:49:53 +00001253 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001254 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001255 Inherited(S.Context),
1256 Decls(Decls),
1257 Ranges(Ranges),
1258 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001259
Richard Trieu9d228802013-05-31 22:46:45 +00001260 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001261
Richard Trieu9d228802013-05-31 22:46:45 +00001262 // Replaces the method in EvaluatedExprVisitor.
1263 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001264 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001265 }
1266
1267 // Any Stmt not whitelisted will cause the condition to be marked complex.
1268 void VisitStmt(Stmt *S) {
1269 Simple = false;
1270 }
1271
1272 void VisitBinaryOperator(BinaryOperator *E) {
1273 Visit(E->getLHS());
1274 Visit(E->getRHS());
1275 }
1276
1277 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001278 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001279 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001280
Richard Trieu9d228802013-05-31 22:46:45 +00001281 void VisitUnaryOperator(UnaryOperator *E) {
1282 // Skip checking conditionals with derefernces.
1283 if (E->getOpcode() == UO_Deref)
1284 Simple = false;
1285 else
1286 Visit(E->getSubExpr());
1287 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001288
Richard Trieu9d228802013-05-31 22:46:45 +00001289 void VisitConditionalOperator(ConditionalOperator *E) {
1290 Visit(E->getCond());
1291 Visit(E->getTrueExpr());
1292 Visit(E->getFalseExpr());
1293 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001294
Richard Trieu9d228802013-05-31 22:46:45 +00001295 void VisitParenExpr(ParenExpr *E) {
1296 Visit(E->getSubExpr());
1297 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001298
Richard Trieu9d228802013-05-31 22:46:45 +00001299 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1300 Visit(E->getOpaqueValue()->getSourceExpr());
1301 Visit(E->getFalseExpr());
1302 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001303
Richard Trieu9d228802013-05-31 22:46:45 +00001304 void VisitIntegerLiteral(IntegerLiteral *E) { }
1305 void VisitFloatingLiteral(FloatingLiteral *E) { }
1306 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1307 void VisitCharacterLiteral(CharacterLiteral *E) { }
1308 void VisitGNUNullExpr(GNUNullExpr *E) { }
1309 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001310
Richard Trieu9d228802013-05-31 22:46:45 +00001311 void VisitDeclRefExpr(DeclRefExpr *E) {
1312 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1313 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001314
Richard Trieu9d228802013-05-31 22:46:45 +00001315 Ranges.push_back(E->getSourceRange());
1316
1317 Decls.insert(VD);
1318 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001319
1320 }; // end class DeclExtractor
1321
1322 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001323 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001324 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001325 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001326 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001327
Richard Trieu9d228802013-05-31 22:46:45 +00001328 public:
1329 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001330
Craig Topper4dd9b432014-08-17 23:49:53 +00001331 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001332 Stmt *Statement) :
1333 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1334 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001335
Richard Trieu9d228802013-05-31 22:46:45 +00001336 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001337 }
1338
Richard Trieu9d228802013-05-31 22:46:45 +00001339 void VisitReturnStmt(ReturnStmt *S) {
1340 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001341 }
1342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 void VisitBreakStmt(BreakStmt *S) {
1344 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001345 }
1346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 void VisitGotoStmt(GotoStmt *S) {
1348 FoundDecl = true;
1349 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001350
Richard Trieu9d228802013-05-31 22:46:45 +00001351 void VisitCastExpr(CastExpr *E) {
1352 if (E->getCastKind() == CK_LValueToRValue)
1353 CheckLValueToRValueCast(E->getSubExpr());
1354 else
1355 Visit(E->getSubExpr());
1356 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001357
Richard Trieu9d228802013-05-31 22:46:45 +00001358 void CheckLValueToRValueCast(Expr *E) {
1359 E = E->IgnoreParenImpCasts();
1360
1361 if (isa<DeclRefExpr>(E)) {
1362 return;
1363 }
1364
1365 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1366 Visit(CO->getCond());
1367 CheckLValueToRValueCast(CO->getTrueExpr());
1368 CheckLValueToRValueCast(CO->getFalseExpr());
1369 return;
1370 }
1371
1372 if (BinaryConditionalOperator *BCO =
1373 dyn_cast<BinaryConditionalOperator>(E)) {
1374 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1375 CheckLValueToRValueCast(BCO->getFalseExpr());
1376 return;
1377 }
1378
1379 Visit(E);
1380 }
1381
1382 void VisitDeclRefExpr(DeclRefExpr *E) {
1383 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1384 if (Decls.count(VD))
1385 FoundDecl = true;
1386 }
1387
1388 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001389
1390 }; // end class DeclMatcher
1391
1392 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1393 Expr *Third, Stmt *Body) {
1394 // Condition is empty
1395 if (!Second) return;
1396
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001397 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1398 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001399 return;
1400
1401 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1402 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001403 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001404 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001405 DE.Visit(Second);
1406
1407 // Don't analyze complex conditionals.
1408 if (!DE.isSimple()) return;
1409
1410 // No decls found.
1411 if (Decls.size() == 0) return;
1412
Richard Trieu0030f1d2012-05-04 03:01:54 +00001413 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001414 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1415 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001416 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001417 if ((*I)->getType().isVolatileQualified() ||
1418 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001419
1420 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1421 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1422 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1423 return;
1424
1425 // Load decl names into diagnostic.
1426 if (Decls.size() > 4)
1427 PDiag << 0;
1428 else {
1429 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001430 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1431 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001432 I != E; ++I)
1433 PDiag << (*I)->getDeclName();
1434 }
1435
1436 // Load SourceRanges into diagnostic if there is room.
1437 // Otherwise, load the SourceRange of the conditional expression.
1438 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001439 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001440 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001441 I != E; ++I)
1442 PDiag << *I;
1443 else
1444 PDiag << Second->getSourceRange();
1445
1446 S.Diag(Ranges.begin()->getBegin(), PDiag);
1447 }
1448
Richard Trieu4e7c9622013-08-06 21:31:54 +00001449 // If Statement is an incemement or decrement, return true and sets the
1450 // variables Increment and DRE.
1451 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1452 DeclRefExpr *&DRE) {
1453 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1454 switch (UO->getOpcode()) {
1455 default: return false;
1456 case UO_PostInc:
1457 case UO_PreInc:
1458 Increment = true;
1459 break;
1460 case UO_PostDec:
1461 case UO_PreDec:
1462 Increment = false;
1463 break;
1464 }
1465 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1466 return DRE;
1467 }
1468
1469 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1470 FunctionDecl *FD = Call->getDirectCallee();
1471 if (!FD || !FD->isOverloadedOperator()) return false;
1472 switch (FD->getOverloadedOperator()) {
1473 default: return false;
1474 case OO_PlusPlus:
1475 Increment = true;
1476 break;
1477 case OO_MinusMinus:
1478 Increment = false;
1479 break;
1480 }
1481 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1482 return DRE;
1483 }
1484
1485 return false;
1486 }
1487
Serge Pavlov09f99242014-01-23 15:05:00 +00001488 // A visitor to determine if a continue or break statement is a
1489 // subexpression.
1490 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1491 SourceLocation BreakLoc;
1492 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001493 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001494 BreakContinueFinder(Sema &S, Stmt* Body) :
1495 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001496 Visit(Body);
1497 }
1498
Serge Pavlov09f99242014-01-23 15:05:00 +00001499 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001500
1501 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001502 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001503 }
1504
Serge Pavlov09f99242014-01-23 15:05:00 +00001505 void VisitBreakStmt(BreakStmt* E) {
1506 BreakLoc = E->getBreakLoc();
1507 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001508
Serge Pavlov09f99242014-01-23 15:05:00 +00001509 bool ContinueFound() { return ContinueLoc.isValid(); }
1510 bool BreakFound() { return BreakLoc.isValid(); }
1511 SourceLocation GetContinueLoc() { return ContinueLoc; }
1512 SourceLocation GetBreakLoc() { return BreakLoc; }
1513
1514 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001515
1516 // Emit a warning when a loop increment/decrement appears twice per loop
1517 // iteration. The conditions which trigger this warning are:
1518 // 1) The last statement in the loop body and the third expression in the
1519 // for loop are both increment or both decrement of the same variable
1520 // 2) No continue statements in the loop body.
1521 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1522 // Return when there is nothing to check.
1523 if (!Body || !Third) return;
1524
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001525 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1526 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001527 return;
1528
1529 // Get the last statement from the loop body.
1530 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1531 if (!CS || CS->body_empty()) return;
1532 Stmt *LastStmt = CS->body_back();
1533 if (!LastStmt) return;
1534
1535 bool LoopIncrement, LastIncrement;
1536 DeclRefExpr *LoopDRE, *LastDRE;
1537
1538 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1539 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1540
1541 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001542 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001543 if (LoopIncrement != LastIncrement ||
1544 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1545
Serge Pavlov09f99242014-01-23 15:05:00 +00001546 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001547
1548 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1549 << LastDRE->getDecl() << LastIncrement;
1550 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1551 << LoopIncrement;
1552 }
1553
Richard Trieu451a5db2012-04-30 18:01:30 +00001554} // end namespace
1555
Serge Pavlov09f99242014-01-23 15:05:00 +00001556
1557void Sema::CheckBreakContinueBinding(Expr *E) {
1558 if (!E || getLangOpts().CPlusPlus)
1559 return;
1560 BreakContinueFinder BCFinder(*this, E);
1561 Scope *BreakParent = CurScope->getBreakParent();
1562 if (BCFinder.BreakFound() && BreakParent) {
1563 if (BreakParent->getFlags() & Scope::SwitchScope) {
1564 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1565 } else {
1566 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1567 << "break";
1568 }
1569 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1570 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1571 << "continue";
1572 }
1573}
1574
John McCalldadc5752010-08-24 06:29:42 +00001575StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001576Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001577 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001578 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001579 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001580 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001581 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001582 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1583 // declare identifiers for objects having storage class 'auto' or
1584 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001585 for (auto *DI : DS->decls()) {
1586 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001587 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001588 VD = nullptr;
1589 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001590 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1591 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001592 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001593 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001594 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001595 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001596
Serge Pavlov09f99242014-01-23 15:05:00 +00001597 CheckBreakContinueBinding(second.get());
1598 CheckBreakContinueBinding(third.get());
1599
Richard Trieu451a5db2012-04-30 18:01:30 +00001600 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001601 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001602
John McCalldadc5752010-08-24 06:29:42 +00001603 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001604 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001605 if (secondVar) {
1606 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001607 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001608 if (SecondResult.isInvalid())
1609 return StmtError();
1610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001611
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001612 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001613
Anders Carlsson1682af52009-08-01 01:39:59 +00001614 DiagnoseUnusedExprResult(First);
1615 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001616 DiagnoseUnusedExprResult(Body);
1617
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001618 if (isa<NullStmt>(Body))
1619 getCurCompoundScope().setHasEmptyLoopBodies();
1620
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001621 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1622 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001623}
1624
John McCall34376a62010-12-04 03:47:34 +00001625/// In an Objective C collection iteration statement:
1626/// for (x in y)
1627/// x can be an arbitrary l-value expression. Bind it up as a
1628/// full-expression.
1629StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001630 // Reduce placeholder expressions here. Note that this rejects the
1631 // use of pseudo-object l-values in this position.
1632 ExprResult result = CheckPlaceholderExpr(E);
1633 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001634 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001635
Richard Smith945f8d32013-01-14 22:39:08 +00001636 ExprResult FullExpr = ActOnFinishFullExpr(E);
1637 if (FullExpr.isInvalid())
1638 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001639 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001640}
1641
John McCall53848232011-07-27 01:07:15 +00001642ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001643Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1644 if (!collection)
1645 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001646
John McCall53848232011-07-27 01:07:15 +00001647 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001648 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001649
1650 // Perform normal l-value conversion.
1651 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1652 if (result.isInvalid())
1653 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001654 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001655
1656 // The operand needs to have object-pointer type.
1657 // TODO: should we do a contextual conversion?
1658 const ObjCObjectPointerType *pointerType =
1659 collection->getType()->getAs<ObjCObjectPointerType>();
1660 if (!pointerType)
1661 return Diag(forLoc, diag::err_collection_expr_type)
1662 << collection->getType() << collection->getSourceRange();
1663
1664 // Check that the operand provides
1665 // - countByEnumeratingWithState:objects:count:
1666 const ObjCObjectType *objectType = pointerType->getObjectType();
1667 ObjCInterfaceDecl *iface = objectType->getInterface();
1668
1669 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001670 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001671 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001672 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001674 ? diag::err_arc_collection_forward
1675 : 0,
1676 collection)) {
John McCall53848232011-07-27 01:07:15 +00001677 // Otherwise, if we have any useful type information, check that
1678 // the type declares the appropriate method.
1679 } else if (iface || !objectType->qual_empty()) {
1680 IdentifierInfo *selectorIdents[] = {
1681 &Context.Idents.get("countByEnumeratingWithState"),
1682 &Context.Idents.get("objects"),
1683 &Context.Idents.get("count")
1684 };
1685 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1686
Craig Topperc3ec1492014-05-26 06:22:03 +00001687 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001688
1689 // If there's an interface, look in both the public and private APIs.
1690 if (iface) {
1691 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001692 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001693 }
1694
1695 // Also check protocol qualifiers.
1696 if (!method)
1697 method = LookupMethodInQualifiedType(selector, pointerType,
1698 /*instance*/ true);
1699
1700 // If we didn't find it anywhere, give up.
1701 if (!method) {
1702 Diag(forLoc, diag::warn_collection_expr_type)
1703 << collection->getType() << selector << collection->getSourceRange();
1704 }
1705
1706 // TODO: check for an incompatible signature?
1707 }
1708
1709 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001710 return collection;
John McCall53848232011-07-27 01:07:15 +00001711}
1712
John McCalldadc5752010-08-24 06:29:42 +00001713StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001714Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001715 Stmt *First, Expr *collection,
1716 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001717
1718 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001719 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001720
Fariborz Jahanian93977672008-01-10 20:33:58 +00001721 if (First) {
1722 QualType FirstType;
1723 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001724 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001725 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1726 diag::err_toomany_element_decls));
1727
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001728 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1729 if (!D || D->isInvalidDecl())
1730 return StmtError();
1731
John McCall31168b02011-06-15 23:02:42 +00001732 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001733 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1734 // declare identifiers for objects having storage class 'auto' or
1735 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001736 if (!D->hasLocalStorage())
1737 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001738 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001739
1740 // If the type contained 'auto', deduce the 'auto' to 'id'.
1741 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001742 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1743 VK_RValue);
1744 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001745 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1746 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001747 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001748 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001749 D->setInvalidDecl();
1750 return StmtError();
1751 }
1752
Richard Smith061f1e22013-04-30 21:23:01 +00001753 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001754
1755 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001756 SourceLocation Loc =
1757 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001758 Diag(Loc, diag::warn_auto_var_is_id)
1759 << D->getDeclName();
1760 }
1761 }
1762
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001763 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001764 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001765 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001766 return StmtError(Diag(First->getLocStart(),
1767 diag::err_selector_element_not_lvalue)
1768 << First->getSourceRange());
1769
Mike Stump11289f42009-09-09 15:08:12 +00001770 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001771 if (FirstType.isConstQualified())
1772 Diag(ForLoc, diag::err_selector_element_const_type)
1773 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001774 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001775 if (!FirstType->isDependentType() &&
1776 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001777 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001778 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1779 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001780 }
Chad Rosier02a84392012-08-10 17:56:09 +00001781
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001782 if (CollectionExprResult.isInvalid())
1783 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001784
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001785 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001786 if (CollectionExprResult.isInvalid())
1787 return StmtError();
1788
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001789 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1790 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001791}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001792
Richard Smith02e85f32011-04-14 22:09:26 +00001793/// Finish building a variable declaration for a for-range statement.
1794/// \return true if an error occurs.
1795static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001796 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001797 // Deduce the type for the iterator variable now rather than leaving it to
1798 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001799 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001800 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001801 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001802 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001803 SemaRef.Diag(Loc, DiagID) << Init->getType();
1804 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001805 Decl->setInvalidDecl();
1806 return true;
1807 }
Richard Smith061f1e22013-04-30 21:23:01 +00001808 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001809
John McCall31168b02011-06-15 23:02:42 +00001810 // In ARC, infer lifetime.
1811 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1812 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001813 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001814 SemaRef.inferObjCARCLifetime(Decl))
1815 Decl->setInvalidDecl();
1816
Richard Smith02e85f32011-04-14 22:09:26 +00001817 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1818 /*TypeMayContainAuto=*/false);
1819 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001820 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001821 return false;
1822}
1823
Sam Panzer0f384432012-08-21 00:52:01 +00001824namespace {
1825
Richard Smith02e85f32011-04-14 22:09:26 +00001826/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001827/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001828/// nor from the diagnostics produced when analysing the implicit expressions
1829/// required in a for-range statement.
1830void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001831 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001832 CallExpr *CE = dyn_cast<CallExpr>(E);
1833 if (!CE)
1834 return;
1835 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1836 if (!D)
1837 return;
1838 SourceLocation Loc = D->getLocation();
1839
1840 std::string Description;
1841 bool IsTemplate = false;
1842 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1843 Description = SemaRef.getTemplateArgumentBindingsText(
1844 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1845 IsTemplate = true;
1846 }
1847
1848 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1849 << BEF << IsTemplate << Description << E->getType();
1850}
1851
Sam Panzer0f384432012-08-21 00:52:01 +00001852/// Build a variable declaration for a for-range statement.
1853VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1854 QualType Type, const char *Name) {
1855 DeclContext *DC = SemaRef.CurContext;
1856 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1857 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1858 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001859 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001860 Decl->setImplicit();
1861 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001862}
1863
1864}
1865
Fariborz Jahanian00213472012-07-06 19:04:04 +00001866static bool ObjCEnumerationCollection(Expr *Collection) {
1867 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001868 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001869}
1870
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001871/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001872///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001873/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001874/// A range-based for statement is equivalent to
1875///
1876/// {
1877/// auto && __range = range-init;
1878/// for ( auto __begin = begin-expr,
1879/// __end = end-expr;
1880/// __begin != __end;
1881/// ++__begin ) {
1882/// for-range-declaration = *__begin;
1883/// statement
1884/// }
1885/// }
1886///
1887/// The body of the loop is not available yet, since it cannot be analysed until
1888/// we have determined the type of the for-range-declaration.
1889StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001890Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001891 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001892 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001893 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001894 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001895
Richard Smith3249fed2013-08-21 01:40:36 +00001896 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001897 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001898
1899 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1900 assert(DS && "first part of for range not a decl stmt");
1901
1902 if (!DS->isSingleDecl()) {
1903 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1904 return StmtError();
1905 }
Richard Smith02e85f32011-04-14 22:09:26 +00001906
Richard Smith3249fed2013-08-21 01:40:36 +00001907 Decl *LoopVar = DS->getSingleDecl();
1908 if (LoopVar->isInvalidDecl() || !Range ||
1909 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1910 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001911 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001912 }
Richard Smith02e85f32011-04-14 22:09:26 +00001913
1914 // Build auto && __range = range-init
1915 SourceLocation RangeLoc = Range->getLocStart();
1916 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1917 Context.getAutoRRefDeductType(),
1918 "__range");
1919 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001920 diag::err_for_range_deduction_failure)) {
1921 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001922 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001923 }
Richard Smith02e85f32011-04-14 22:09:26 +00001924
1925 // Claim the type doesn't contain auto: we've already done the checking.
1926 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001927 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001928 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001929 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001930 if (RangeDecl.isInvalid()) {
1931 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001932 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001933 }
Richard Smith02e85f32011-04-14 22:09:26 +00001934
1935 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001936 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1937 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001938}
1939
1940/// \brief Create the initialization, compare, and increment steps for
1941/// the range-based for loop expression.
1942/// This function does not handle array-based for loops,
1943/// which are created in Sema::BuildCXXForRangeStmt.
1944///
1945/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1946/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1947/// CandidateSet and BEF are set and some non-success value is returned on
1948/// failure.
1949static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1950 Expr *BeginRange, Expr *EndRange,
1951 QualType RangeType,
1952 VarDecl *BeginVar,
1953 VarDecl *EndVar,
1954 SourceLocation ColonLoc,
1955 OverloadCandidateSet *CandidateSet,
1956 ExprResult *BeginExpr,
1957 ExprResult *EndExpr,
1958 Sema::BeginEndFunction *BEF) {
1959 DeclarationNameInfo BeginNameInfo(
1960 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1961 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1962 ColonLoc);
1963
1964 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1965 Sema::LookupMemberName);
1966 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1967
1968 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1969 // - if _RangeT is a class type, the unqualified-ids begin and end are
1970 // looked up in the scope of class _RangeT as if by class member access
1971 // lookup (3.4.5), and if either (or both) finds at least one
1972 // declaration, begin-expr and end-expr are __range.begin() and
1973 // __range.end(), respectively;
1974 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1975 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1976
1977 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1978 SourceLocation RangeLoc = BeginVar->getLocation();
1979 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1980
1981 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1982 << RangeLoc << BeginRange->getType() << *BEF;
1983 return Sema::FRS_DiagnosticIssued;
1984 }
1985 } else {
1986 // - otherwise, begin-expr and end-expr are begin(__range) and
1987 // end(__range), respectively, where begin and end are looked up with
1988 // argument-dependent lookup (3.4.2). For the purposes of this name
1989 // lookup, namespace std is an associated namespace.
1990
1991 }
1992
1993 *BEF = Sema::BEF_begin;
1994 Sema::ForRangeStatus RangeStatus =
1995 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1996 Sema::BEF_begin, BeginNameInfo,
1997 BeginMemberLookup, CandidateSet,
1998 BeginRange, BeginExpr);
1999
2000 if (RangeStatus != Sema::FRS_Success)
2001 return RangeStatus;
2002 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2003 diag::err_for_range_iter_deduction_failure)) {
2004 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2005 return Sema::FRS_DiagnosticIssued;
2006 }
2007
2008 *BEF = Sema::BEF_end;
2009 RangeStatus =
2010 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2011 Sema::BEF_end, EndNameInfo,
2012 EndMemberLookup, CandidateSet,
2013 EndRange, EndExpr);
2014 if (RangeStatus != Sema::FRS_Success)
2015 return RangeStatus;
2016 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2017 diag::err_for_range_iter_deduction_failure)) {
2018 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2019 return Sema::FRS_DiagnosticIssued;
2020 }
2021 return Sema::FRS_Success;
2022}
2023
2024/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002025/// If the attempt fails, this function will return a valid, null StmtResult
2026/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002027static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2028 SourceLocation ForLoc,
2029 Stmt *LoopVarDecl,
2030 SourceLocation ColonLoc,
2031 Expr *Range,
2032 SourceLocation RangeLoc,
2033 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002034 // Determine whether we can rebuild the for-range statement with a
2035 // dereferenced range expression.
2036 ExprResult AdjustedRange;
2037 {
2038 Sema::SFINAETrap Trap(SemaRef);
2039
2040 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2041 if (AdjustedRange.isInvalid())
2042 return StmtResult();
2043
2044 StmtResult SR =
2045 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2046 AdjustedRange.get(), RParenLoc,
2047 Sema::BFRK_Check);
2048 if (SR.isInvalid())
2049 return StmtResult();
2050 }
2051
2052 // The attempt to dereference worked well enough that it could produce a valid
2053 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2054 // case there are any other (non-fatal) problems with it.
2055 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2056 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2057 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2058 AdjustedRange.get(), RParenLoc,
2059 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002060}
2061
Richard Smith3249fed2013-08-21 01:40:36 +00002062namespace {
2063/// RAII object to automatically invalidate a declaration if an error occurs.
2064struct InvalidateOnErrorScope {
2065 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2066 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2067 ~InvalidateOnErrorScope() {
2068 if (Enabled && Trap.hasErrorOccurred())
2069 D->setInvalidDecl();
2070 }
2071
2072 DiagnosticErrorTrap Trap;
2073 Decl *D;
2074 bool Enabled;
2075};
2076}
2077
Richard Smitha05b3b52012-09-20 21:52:32 +00002078/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002079StmtResult
2080Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2081 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2082 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002083 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002084 Scope *S = getCurScope();
2085
2086 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2087 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2088 QualType RangeVarType = RangeVar->getType();
2089
2090 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2091 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2092
Richard Smith3249fed2013-08-21 01:40:36 +00002093 // If we hit any errors, mark the loop variable as invalid if its type
2094 // contains 'auto'.
2095 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2096 LoopVar->getType()->isUndeducedType());
2097
Richard Smith02e85f32011-04-14 22:09:26 +00002098 StmtResult BeginEndDecl = BeginEnd;
2099 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2100
Richard Smith27d807c2013-04-30 13:56:41 +00002101 if (RangeVarType->isDependentType()) {
2102 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002103 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002104
2105 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2106 // them in properly when we instantiate the loop.
2107 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2108 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2109 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002110 SourceLocation RangeLoc = RangeVar->getLocation();
2111
Ted Kremenekbed648e2011-10-10 22:36:28 +00002112 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2113
2114 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2115 VK_LValue, ColonLoc);
2116 if (BeginRangeRef.isInvalid())
2117 return StmtError();
2118
2119 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2120 VK_LValue, ColonLoc);
2121 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002122 return StmtError();
2123
2124 QualType AutoType = Context.getAutoDeductType();
2125 Expr *Range = RangeVar->getInit();
2126 if (!Range)
2127 return StmtError();
2128 QualType RangeType = Range->getType();
2129
2130 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002131 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002132 return StmtError();
2133
2134 // Build auto __begin = begin-expr, __end = end-expr.
2135 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2136 "__begin");
2137 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2138 "__end");
2139
2140 // Build begin-expr and end-expr and attach to __begin and __end variables.
2141 ExprResult BeginExpr, EndExpr;
2142 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2143 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2144 // __range + __bound, respectively, where __bound is the array bound. If
2145 // _RangeT is an array of unknown size or an array of incomplete type,
2146 // the program is ill-formed;
2147
2148 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002149 BeginExpr = BeginRangeRef;
2150 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002151 diag::err_for_range_iter_deduction_failure)) {
2152 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2153 return StmtError();
2154 }
2155
2156 // Find the array bound.
2157 ExprResult BoundExpr;
2158 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002159 BoundExpr = IntegerLiteral::Create(
2160 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002161 else if (const VariableArrayType *VAT =
2162 dyn_cast<VariableArrayType>(UnqAT))
2163 BoundExpr = VAT->getSizeExpr();
2164 else {
2165 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2166 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002167 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002168 }
2169
2170 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002171 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002172 BoundExpr.get());
2173 if (EndExpr.isInvalid())
2174 return StmtError();
2175 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2176 diag::err_for_range_iter_deduction_failure)) {
2177 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2178 return StmtError();
2179 }
2180 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002181 OverloadCandidateSet CandidateSet(RangeLoc,
2182 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002183 Sema::BeginEndFunction BEFFailure;
2184 ForRangeStatus RangeStatus =
2185 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2186 EndRangeRef.get(), RangeType,
2187 BeginVar, EndVar, ColonLoc, &CandidateSet,
2188 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002189
Richard Smitha05b3b52012-09-20 21:52:32 +00002190 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002191 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002192 // If the range is being built from an array parameter, emit a
2193 // a diagnostic that it is being treated as a pointer.
2194 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2195 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2196 QualType ArrayTy = PVD->getOriginalType();
2197 QualType PointerTy = PVD->getType();
2198 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2199 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2200 << RangeLoc << PVD << ArrayTy << PointerTy;
2201 Diag(PVD->getLocation(), diag::note_declared_at);
2202 return StmtError();
2203 }
2204 }
2205 }
2206
2207 // If building the range failed, try dereferencing the range expression
2208 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002209 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2210 LoopVarDecl, ColonLoc,
2211 Range, RangeLoc,
2212 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002213 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002214 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002215 }
2216
Sam Panzer0f384432012-08-21 00:52:01 +00002217 // Otherwise, emit diagnostics if we haven't already.
2218 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002219 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002220 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2221 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002222 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002223 }
2224 // Return an error if no fix was discovered.
2225 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002226 return StmtError();
2227 }
2228
Sam Panzer0f384432012-08-21 00:52:01 +00002229 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2230 "invalid range expression in for loop");
2231
2232 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002233 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2234 if (!Context.hasSameType(BeginType, EndType)) {
2235 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2236 << BeginType << EndType;
2237 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2238 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2239 }
2240
2241 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2242 // Claim the type doesn't contain auto: we've already done the checking.
2243 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002244 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002245 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002246 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2247
Ted Kremenekbed648e2011-10-10 22:36:28 +00002248 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2249 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002250 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002251 if (BeginRef.isInvalid())
2252 return StmtError();
2253
Richard Smith02e85f32011-04-14 22:09:26 +00002254 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2255 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002256 if (EndRef.isInvalid())
2257 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002258
2259 // Build and check __begin != __end expression.
2260 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2261 BeginRef.get(), EndRef.get());
2262 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2263 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2264 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002265 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2266 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002267 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2268 if (!Context.hasSameType(BeginType, EndType))
2269 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2270 return StmtError();
2271 }
2272
2273 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002274 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2275 VK_LValue, ColonLoc);
2276 if (BeginRef.isInvalid())
2277 return StmtError();
2278
Richard Smith02e85f32011-04-14 22:09:26 +00002279 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2280 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2281 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002282 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2283 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002284 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2285 return StmtError();
2286 }
2287
2288 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002289 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2290 VK_LValue, ColonLoc);
2291 if (BeginRef.isInvalid())
2292 return StmtError();
2293
Richard Smith02e85f32011-04-14 22:09:26 +00002294 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2295 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002296 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2297 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002298 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2299 return StmtError();
2300 }
2301
Richard Smitha05b3b52012-09-20 21:52:32 +00002302 // Attach *__begin as initializer for VD. Don't touch it if we're just
2303 // trying to determine whether this would be a valid range.
2304 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002305 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2306 /*TypeMayContainAuto=*/true);
2307 if (LoopVar->isInvalidDecl())
2308 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2309 }
2310 }
2311
Richard Smitha05b3b52012-09-20 21:52:32 +00002312 // Don't bother to actually allocate the result if we're just trying to
2313 // determine whether it would be valid.
2314 if (Kind == BFRK_Check)
2315 return StmtResult();
2316
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002317 return new (Context) CXXForRangeStmt(
2318 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2319 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002320}
2321
Chad Rosier02a84392012-08-10 17:56:09 +00002322/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002323/// statement.
2324StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2325 if (!S || !B)
2326 return StmtError();
2327 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002328
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002329 ForStmt->setBody(B);
2330 return S;
2331}
2332
Richard Smith02e85f32011-04-14 22:09:26 +00002333/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2334/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2335/// body cannot be performed until after the type of the range variable is
2336/// determined.
2337StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2338 if (!S || !B)
2339 return StmtError();
2340
Fariborz Jahanian00213472012-07-06 19:04:04 +00002341 if (isa<ObjCForCollectionStmt>(S))
2342 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002343
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002344 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2345 ForStmt->setBody(B);
2346
2347 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2348 diag::warn_empty_range_based_for_body);
2349
Richard Smith02e85f32011-04-14 22:09:26 +00002350 return S;
2351}
2352
Chris Lattnercab02a62011-02-17 20:34:02 +00002353StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2354 SourceLocation LabelLoc,
2355 LabelDecl *TheDecl) {
2356 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002357 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002358 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002359}
Chris Lattner1c310502007-05-31 06:00:00 +00002360
John McCalldadc5752010-08-24 06:29:42 +00002361StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002362Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002363 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002364 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002365 if (!E->isTypeDependent()) {
2366 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002367 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002368 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002369 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002370 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2371 if (ExprRes.isInvalid())
2372 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002373 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002374 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002375 return StmtError();
2376 }
John McCalla95172b2010-08-01 00:26:45 +00002377
Richard Smith945f8d32013-01-14 22:39:08 +00002378 ExprResult ExprRes = ActOnFinishFullExpr(E);
2379 if (ExprRes.isInvalid())
2380 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002381 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002382
John McCallaab3e412010-08-25 08:40:02 +00002383 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002384
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002385 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002386}
2387
John McCalldadc5752010-08-24 06:29:42 +00002388StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002389Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002390 Scope *S = CurScope->getContinueParent();
2391 if (!S) {
2392 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002393 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002394 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002395
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002396 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002397}
2398
John McCalldadc5752010-08-24 06:29:42 +00002399StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002400Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002401 Scope *S = CurScope->getBreakParent();
2402 if (!S) {
2403 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002404 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002405 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002406 if (S->isOpenMPLoopScope())
2407 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2408 << "break");
Sebastian Redl573feed2009-01-18 13:19:59 +00002409
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002410 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002411}
2412
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002413/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002414/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002415///
Douglas Gregor5d369002011-01-21 18:05:27 +00002416/// \param ReturnType If we're determining the copy elision candidate for
2417/// a return statement, this is the return type of the function. If we're
2418/// determining the copy elision candidate for a throw expression, this will
2419/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002420///
Douglas Gregor5d369002011-01-21 18:05:27 +00002421/// \param E The expression being returned from the function or block, or
2422/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002423///
Douglas Gregor86394412011-05-20 15:00:53 +00002424/// \param AllowFunctionParameter Whether we allow function parameters to
2425/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2426/// we re-use this logic to determine whether we should try to move as part of
2427/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002428///
2429/// \returns The NRVO candidate variable, if the return statement may use the
2430/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002431VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2432 Expr *E,
2433 bool AllowFunctionParameter) {
2434 if (!getLangOpts().CPlusPlus)
2435 return nullptr;
2436
2437 // - in a return statement in a function [where] ...
2438 // ... the expression is the name of a non-volatile automatic object ...
2439 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2440 if (!DR || DR->refersToEnclosingLocal())
2441 return nullptr;
2442 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2443 if (!VD)
2444 return nullptr;
2445
2446 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2447 return VD;
2448 return nullptr;
2449}
2450
2451bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2452 bool AllowFunctionParameter) {
2453 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002454 // - in a return statement in a function with ...
2455 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002456 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002457 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002458 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002459 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002460 if (!VDType->isDependentType() &&
2461 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2462 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
John McCall03318c12011-11-11 03:57:31 +00002465 // ...object (other than a function or catch-clause parameter)...
2466 if (VD->getKind() != Decl::Var &&
2467 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002468 return false;
2469 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470
John McCall03318c12011-11-11 03:57:31 +00002471 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002472 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002473
2474 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002475 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002476
2477 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002478 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002479
2480 // Variables with higher required alignment than their type's ABI
2481 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002482 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002483 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002484 return false;
John McCall03318c12011-11-11 03:57:31 +00002485
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002486 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002487}
2488
Douglas Gregor626fbed2011-01-21 21:08:57 +00002489/// \brief Perform the initialization of a potentially-movable value, which
2490/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002491///
2492/// This routine implements C++0x [class.copy]p33, which attempts to treat
2493/// returned lvalues as rvalues in certain cases (to prefer move construction),
2494/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002495ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002496Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2497 const VarDecl *NRVOCandidate,
2498 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002499 Expr *Value,
2500 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002501 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002502 // When the criteria for elision of a copy operation are met or would
2503 // be met save for the fact that the source object is a function
2504 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002505 // overload resolution to select the constructor for the copy is first
2506 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002507 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002508 if (AllowNRVO &&
2509 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002510 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002511 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002512
Douglas Gregorf282a762011-01-21 19:38:21 +00002513 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002515 = InitializationKind::CreateCopy(Value->getLocStart(),
2516 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002517 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518
2519 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002520 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002521 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002522 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002523 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002524 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2525 StepEnd = Seq.step_end();
2526 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002527 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002528 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002529
2530 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002531 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532
Douglas Gregorf282a762011-01-21 19:38:21 +00002533 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002534 = Constructor->getParamDecl(0)->getType()
2535 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002536
Douglas Gregorf282a762011-01-21 19:38:21 +00002537 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002538 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002539 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2540 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002541 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542
Douglas Gregorf282a762011-01-21 19:38:21 +00002543 // Promote "AsRvalue" to the heap, since we now need this
2544 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002545 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002546 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002547
Douglas Gregorf282a762011-01-21 19:38:21 +00002548 // Complete type-checking the initialization of the return type
2549 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002550 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002551 }
2552 }
2553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002554
Douglas Gregorf282a762011-01-21 19:38:21 +00002555 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002557 // (again) now with the return value expression as written.
2558 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002559 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560
Douglas Gregorf282a762011-01-21 19:38:21 +00002561 return Res;
2562}
2563
Richard Smith4db51c22013-09-25 05:02:54 +00002564/// \brief Determine whether the declared return type of the specified function
2565/// contains 'auto'.
2566static bool hasDeducedReturnType(FunctionDecl *FD) {
2567 const FunctionProtoType *FPT =
2568 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002569 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002570}
2571
Eli Friedman34b49062012-01-26 03:00:14 +00002572/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2573/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002574///
John McCalldadc5752010-08-24 06:29:42 +00002575StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002576Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2577 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002578 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002579 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002580 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002581 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002582
Richard Smith4db51c22013-09-25 05:02:54 +00002583 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2584 // In C++1y, the return type may involve 'auto'.
2585 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2586 FunctionDecl *FD = CurLambda->CallOperator;
2587 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002588 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002589
2590 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2591 assert(AT && "lost auto type from lambda return type");
2592 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2593 FD->setInvalidDecl();
2594 return StmtError();
2595 }
Alp Toker314cc812014-01-25 16:55:45 +00002596 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002597 } else if (CurCap->HasImplicitReturnType) {
2598 // For blocks/lambdas with implicit return types, we check each return
2599 // statement individually, and deduce the common return type when the block
2600 // or lambda is completed.
2601 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002602 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002603 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2604 if (Result.isInvalid())
2605 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002606 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002607
Richard Smith4db51c22013-09-25 05:02:54 +00002608 if (!CurContext->isDependentContext())
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002609 FnRetType = RetValExp->getType();
Richard Smith4db51c22013-09-25 05:02:54 +00002610 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002611 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002612 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002613 if (RetValExp) {
2614 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2615 // initializer list, because it is not an expression (even
2616 // though we represent it as one). We still deduce 'void'.
2617 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2618 << RetValExp->getSourceRange();
2619 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002620
Jordan Rosed39e5f12012-07-02 21:19:23 +00002621 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002622 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002623
2624 // Although we'll properly infer the type of the block once it's completed,
2625 // make sure we provide a return type now for better error recovery.
2626 if (CurCap->ReturnType.isNull())
2627 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002628 }
Eli Friedman34b49062012-01-26 03:00:14 +00002629 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002630
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002631 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002632 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2633 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2634 return StmtError();
2635 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002636 } else if (CapturedRegionScopeInfo *CurRegion =
2637 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2638 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2639 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002640 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002641 assert(CurLambda && "unknown kind of captured scope");
2642 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2643 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002644 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2645 return StmtError();
2646 }
2647 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002648
Steve Naroffc540d662008-09-03 18:15:37 +00002649 // Otherwise, verify that this result type matches the previous one. We are
2650 // pickier with blocks than for normal functions because we don't have GCC
2651 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002652 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002653 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002654 // Delay processing for now. TODO: there are lots of dependent
2655 // types we can conclusively prove aren't void.
2656 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002657 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002658 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002659 (RetValExp->isTypeDependent() ||
2660 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002661 if (!getLangOpts().CPlusPlus &&
2662 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002663 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002664 else {
2665 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002666 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002667 }
Steve Naroffc540d662008-09-03 18:15:37 +00002668 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002669 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002670 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2671 } else if (!RetValExp->isTypeDependent()) {
2672 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002673
John McCall5500ef22011-08-17 22:09:46 +00002674 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2675 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2676 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002677
John McCall5500ef22011-08-17 22:09:46 +00002678 // In C++ the return statement is handled via a copy initialization.
2679 // the C version of which boils down to CheckSingleAssignmentConstraints.
2680 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2681 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2682 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002683 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002684 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2685 FnRetType, RetValExp);
2686 if (Res.isInvalid()) {
2687 // FIXME: Cleanup temporaries here, anyway?
2688 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002689 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002690 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002691 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002692 } else {
2693 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002694 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002695
John McCall75f92b52011-08-17 21:34:14 +00002696 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002697 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2698 if (ER.isInvalid())
2699 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002700 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002701 }
John McCall5500ef22011-08-17 22:09:46 +00002702 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2703 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002704
Jordan Rosed39e5f12012-07-02 21:19:23 +00002705 // If we need to check for the named return value optimization,
2706 // or if we need to infer the return type,
2707 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002708 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002709 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002711 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002712}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002713
Nico Weber72889432014-09-06 01:25:55 +00002714namespace {
2715/// \brief Marks all typedefs in all local classes in a type referenced.
2716///
2717/// In a function like
2718/// auto f() {
2719/// struct S { typedef int a; };
2720/// return S();
2721/// }
2722///
2723/// the local type escapes and could be referenced in some TUs but not in
2724/// others. Pretend that all local typedefs are always referenced, to not warn
2725/// on this. This isn't necessary if f has internal linkage, or the typedef
2726/// is private.
2727class LocalTypedefNameReferencer
2728 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2729public:
2730 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2731 bool VisitRecordType(const RecordType *RT);
2732private:
2733 Sema &S;
2734};
2735bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2736 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2737 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2738 R->isDependentType())
2739 return true;
2740 for (auto *TmpD : R->decls())
2741 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2742 if (T->getAccess() != AS_private || R->hasFriends())
2743 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2744 return true;
2745}
2746}
2747
Richard Smith2a7d4812013-05-04 07:00:32 +00002748/// Deduce the return type for a function from a returned expression, per
2749/// C++1y [dcl.spec.auto]p6.
2750bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2751 SourceLocation ReturnLoc,
2752 Expr *&RetExpr,
2753 AutoType *AT) {
2754 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00002755 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith2a7d4812013-05-04 07:00:32 +00002756 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002757
Richard Smithc58f38f2013-08-14 20:16:31 +00002758 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2759 // If the deduction is for a return statement and the initializer is
2760 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002761 Diag(RetExpr->getExprLoc(),
2762 getCurLambda() ? diag::err_lambda_return_init_list
2763 : diag::err_auto_fn_return_init_list)
2764 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002765 return true;
2766 }
2767
2768 if (FD->isDependentContext()) {
2769 // C++1y [dcl.spec.auto]p12:
2770 // Return type deduction [...] occurs when the definition is
2771 // instantiated even if the function body contains a return
2772 // statement with a non-type-dependent operand.
2773 assert(AT->isDeduced() && "should have deduced to dependent type");
2774 return false;
2775 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002776 // If the deduction is for a return statement and the initializer is
2777 // a braced-init-list, the program is ill-formed.
2778 if (isa<InitListExpr>(RetExpr)) {
2779 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2780 return true;
2781 }
2782
2783 // Otherwise, [...] deduce a value for U using the rules of template
2784 // argument deduction.
2785 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2786
2787 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2788 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2789 << OrigResultType.getType() << RetExpr->getType();
2790
2791 if (DAR != DAR_Succeeded)
2792 return true;
Nico Weber72889432014-09-06 01:25:55 +00002793
2794 // If a local type is part of the returned type, mark its fields as
2795 // referenced.
2796 LocalTypedefNameReferencer Referencer(*this);
2797 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00002798 } else {
2799 // In the case of a return with no operand, the initializer is considered
2800 // to be void().
2801 //
2802 // Deduction here can only succeed if the return type is exactly 'cv auto'
2803 // or 'decltype(auto)', so just check for that case directly.
2804 if (!OrigResultType.getType()->getAs<AutoType>()) {
2805 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2806 << OrigResultType.getType();
2807 return true;
2808 }
2809 // We always deduce U = void in this case.
2810 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2811 if (Deduced.isNull())
2812 return true;
2813 }
2814
2815 // If a function with a declared return type that contains a placeholder type
2816 // has multiple return statements, the return type is deduced for each return
2817 // statement. [...] if the type deduced is not the same in each deduction,
2818 // the program is ill-formed.
2819 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2820 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002821 if (!FD->isDependentContext() &&
2822 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002823 const LambdaScopeInfo *LambdaSI = getCurLambda();
2824 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2825 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2826 << NewAT->getDeducedType() << AT->getDeducedType()
2827 << true /*IsLambda*/;
2828 } else {
2829 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2830 << (AT->isDecltypeAuto() ? 1 : 0)
2831 << NewAT->getDeducedType() << AT->getDeducedType();
2832 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002833 return true;
2834 }
2835 } else if (!FD->isInvalidDecl()) {
2836 // Update all declarations of the function to have the deduced return type.
2837 Context.adjustDeducedFunctionResultType(FD, Deduced);
2838 }
2839
2840 return false;
2841}
2842
John McCalldadc5752010-08-24 06:29:42 +00002843StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002844Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2845 Scope *CurScope) {
2846 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2847 if (R.isInvalid()) {
2848 return R;
2849 }
2850
2851 if (VarDecl *VD =
2852 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2853 CurScope->addNRVOCandidate(VD);
2854 } else {
2855 CurScope->setNoNRVO();
2856 }
2857
2858 return R;
2859}
2860
2861StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002862 // Check for unexpanded parameter packs.
2863 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2864 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002865
Eli Friedman34b49062012-01-26 03:00:14 +00002866 if (isa<CapturingScopeInfo>(getCurFunction()))
2867 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002868
Chris Lattner79413952008-12-04 23:50:19 +00002869 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002870 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002871 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002872 bool isObjCMethod = false;
2873
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002874 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002875 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002876 if (FD->hasAttrs())
2877 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002878 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002879 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002880 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002881 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002882 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002883 isObjCMethod = true;
2884 if (MD->hasAttrs())
2885 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002886 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2887 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002888 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002889 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002890 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2891 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002892 }
2893 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002894 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002895
Richard Smith2a7d4812013-05-04 07:00:32 +00002896 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2897 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002898 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002899 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2900 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002901 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002902 FD->setInvalidDecl();
2903 return StmtError();
2904 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002905 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002906 }
2907 }
2908 }
2909
Richard Smithc58f38f2013-08-14 20:16:31 +00002910 bool HasDependentReturnType = FnRetType->isDependentType();
2911
Craig Topperc3ec1492014-05-26 06:22:03 +00002912 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002913 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002914 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002915 if (isa<InitListExpr>(RetValExp)) {
2916 // We simply never allow init lists as the return value of void
2917 // functions. This is compatible because this was never allowed before,
2918 // so there's no legacy code to deal with.
2919 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2920 int FunctionKind = 0;
2921 if (isa<ObjCMethodDecl>(CurDecl))
2922 FunctionKind = 1;
2923 else if (isa<CXXConstructorDecl>(CurDecl))
2924 FunctionKind = 2;
2925 else if (isa<CXXDestructorDecl>(CurDecl))
2926 FunctionKind = 3;
2927
2928 Diag(ReturnLoc, diag::err_return_init_list)
2929 << CurDecl->getDeclName() << FunctionKind
2930 << RetValExp->getSourceRange();
2931
2932 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002933 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002934 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002935 // C99 6.8.6.4p1 (ext_ since GCC warns)
2936 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002937 if (RetValExp->getType()->isVoidType()) {
2938 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2939 if (isa<CXXConstructorDecl>(CurDecl) ||
2940 isa<CXXDestructorDecl>(CurDecl))
2941 D = diag::err_ctor_dtor_returns_void;
2942 else
2943 D = diag::ext_return_has_void_expr;
2944 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002945 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002946 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002947 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00002948 if (Result.isInvalid())
2949 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002950 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002951 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002952 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002953 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002954 // return of void in constructor/destructor is illegal in C++.
2955 if (D == diag::err_ctor_dtor_returns_void) {
2956 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2957 Diag(ReturnLoc, D)
2958 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
2959 << RetValExp->getSourceRange();
2960 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002961 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002962 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002963 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002964 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002965
2966 int FunctionKind = 0;
2967 if (isa<ObjCMethodDecl>(CurDecl))
2968 FunctionKind = 1;
2969 else if (isa<CXXConstructorDecl>(CurDecl))
2970 FunctionKind = 2;
2971 else if (isa<CXXDestructorDecl>(CurDecl))
2972 FunctionKind = 3;
2973
Nick Lewycky1be750a2011-06-01 07:44:31 +00002974 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002975 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002976 << RetValExp->getSourceRange();
2977 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002978 }
Mike Stump11289f42009-09-09 15:08:12 +00002979
Sebastian Redleef474c2012-02-22 10:50:08 +00002980 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002981 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2982 if (ER.isInvalid())
2983 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002984 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00002985 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002986 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987
Craig Topperc3ec1492014-05-26 06:22:03 +00002988 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00002989 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002990 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2991 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002992 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002993
2994 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002995 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002996 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002997 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002998 Result = new (Context) ReturnStmt(ReturnLoc);
2999 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003000 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003001 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003002
3003 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3004
3005 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3006 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3007 // function return.
3008
3009 // In C++ the return statement is handled via a copy initialization,
3010 // the C version of which boils down to CheckSingleAssignmentConstraints.
3011 if (RetValExp)
3012 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003013 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003014 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003015 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003016 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003017 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003018 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003019 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003020 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003021 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003022 return StmtError();
3023 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003024 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003025
3026 // If we have a related result type, we need to implicitly
3027 // convert back to the formal result type. We can't pretend to
3028 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003029 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003030 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003031 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3032 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003033 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3034 if (Res.isInvalid()) {
3035 // FIXME: Clean up temporaries here anyway?
3036 return StmtError();
3037 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003038 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003039 }
3040
Artyom Skrobov9f213442014-01-24 11:10:39 +00003041 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3042 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
John McCallacf0ee52010-10-08 02:01:28 +00003045 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003046 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3047 if (ER.isInvalid())
3048 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003049 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003050 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003051 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053
3054 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003055 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003056 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003057 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003058
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003059 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003060}
3061
John McCalldadc5752010-08-24 06:29:42 +00003062StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003063Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003064 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003065 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003066 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003067 if (Var && Var->isInvalidDecl())
3068 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003069
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003070 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003071}
3072
John McCalldadc5752010-08-24 06:29:42 +00003073StmtResult
John McCallb268a282010-08-23 23:25:46 +00003074Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003075 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003076}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003077
John McCalldadc5752010-08-24 06:29:42 +00003078StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003080 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003081 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003082 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3083
John McCallaab3e412010-08-25 08:40:02 +00003084 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003085 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003086 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3087 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003088}
3089
John McCall0bd3e402012-05-08 21:41:25 +00003090StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003091 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003092 ExprResult Result = DefaultLvalueConversion(Throw);
3093 if (Result.isInvalid())
3094 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003095
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003096 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003097 if (Result.isInvalid())
3098 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003099 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003100
Douglas Gregor2900c162010-04-22 21:44:01 +00003101 QualType ThrowType = Throw->getType();
3102 // Make sure the expression type is an ObjC pointer or "void *".
3103 if (!ThrowType->isDependentType() &&
3104 !ThrowType->isObjCObjectPointerType()) {
3105 const PointerType *PT = ThrowType->getAs<PointerType>();
3106 if (!PT || !PT->getPointeeType()->isVoidType())
3107 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3108 << Throw->getType() << Throw->getSourceRange());
3109 }
3110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003112 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003113}
3114
John McCalldadc5752010-08-24 06:29:42 +00003115StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003117 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003118 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003119 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3120
John McCallb268a282010-08-23 23:25:46 +00003121 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003122 // @throw without an expression designates a rethrow (which much occur
3123 // in the context of an @catch clause).
3124 Scope *AtCatchParent = CurScope;
3125 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3126 AtCatchParent = AtCatchParent->getParent();
3127 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003128 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003129 }
John McCallb268a282010-08-23 23:25:46 +00003130 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003131}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003132
John McCalld9bb7432011-07-27 21:50:02 +00003133ExprResult
3134Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3135 ExprResult result = DefaultLvalueConversion(operand);
3136 if (result.isInvalid())
3137 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003138 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003139
3140 // Make sure the expression type is an ObjC pointer or "void *".
3141 QualType type = operand->getType();
3142 if (!type->isDependentType() &&
3143 !type->isObjCObjectPointerType()) {
3144 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003145 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3146 if (getLangOpts().CPlusPlus) {
3147 if (RequireCompleteType(atLoc, type,
3148 diag::err_incomplete_receiver_type))
3149 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3150 << type << operand->getSourceRange();
3151
3152 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3153 if (!result.isUsable())
3154 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3155 << type << operand->getSourceRange();
3156
3157 operand = result.get();
3158 } else {
3159 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3160 << type << operand->getSourceRange();
3161 }
3162 }
John McCalld9bb7432011-07-27 21:50:02 +00003163 }
3164
3165 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003166 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003167}
3168
John McCalldadc5752010-08-24 06:29:42 +00003169StmtResult
John McCallb268a282010-08-23 23:25:46 +00003170Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3171 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003172 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003173 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003174 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003175}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003176
3177/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3178/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003179StmtResult
John McCall48871652010-08-21 09:40:31 +00003180Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003181 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003182 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003183 return new (Context)
3184 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003185}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003186
John McCall31168b02011-06-15 23:02:42 +00003187StmtResult
3188Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3189 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003190 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003191}
3192
Dan Gohman28ade552010-07-26 21:25:24 +00003193namespace {
3194
Sebastian Redl63c4da02009-07-29 17:15:45 +00003195class TypeWithHandler {
3196 QualType t;
3197 CXXCatchStmt *stmt;
3198public:
3199 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3200 : t(type), stmt(statement) {}
3201
John McCall8ccfcb52009-09-24 19:53:00 +00003202 // An arbitrary order is fine as long as it places identical
3203 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003204 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003205 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003206 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003207 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003208 return false;
3209 else
3210 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3211 }
Mike Stump11289f42009-09-09 15:08:12 +00003212
Sebastian Redl63c4da02009-07-29 17:15:45 +00003213 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003214 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003215 }
Mike Stump11289f42009-09-09 15:08:12 +00003216
Sebastian Redl63c4da02009-07-29 17:15:45 +00003217 CXXCatchStmt *getCatchStmt() const { return stmt; }
3218 SourceLocation getTypeSpecStartLoc() const {
3219 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3220 }
3221};
3222
Dan Gohman28ade552010-07-26 21:25:24 +00003223}
3224
Sebastian Redl9b244a82008-12-22 21:35:02 +00003225/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3226/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003227StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3228 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003229 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003230 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003231 !getSourceManager().isInSystemHeader(TryLoc))
3232 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003233
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003234 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3235 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3236
Robert Wilhelmcafda822013-08-22 09:20:03 +00003237 const unsigned NumHandlers = Handlers.size();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003238 assert(NumHandlers > 0 &&
3239 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003240
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003241 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003242
3243 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003244 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003245 if (!Handler->getExceptionDecl()) {
3246 if (i < NumHandlers - 1)
3247 return StmtError(Diag(Handler->getLocStart(),
3248 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003249
Sebastian Redl63c4da02009-07-29 17:15:45 +00003250 continue;
3251 }
Mike Stump11289f42009-09-09 15:08:12 +00003252
Sebastian Redl63c4da02009-07-29 17:15:45 +00003253 const QualType CaughtType = Handler->getCaughtType();
3254 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3255 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003256 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003257
3258 // Detect handlers for the same type as an earlier one.
3259 if (NumHandlers > 1) {
3260 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003261
Sebastian Redl63c4da02009-07-29 17:15:45 +00003262 TypeWithHandler prev = TypesWithHandlers[0];
3263 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3264 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003265
Sebastian Redl63c4da02009-07-29 17:15:45 +00003266 if (curr == prev) {
3267 Diag(curr.getTypeSpecStartLoc(),
3268 diag::warn_exception_caught_by_earlier_handler)
3269 << curr.getCatchStmt()->getCaughtType().getAsString();
3270 Diag(prev.getTypeSpecStartLoc(),
3271 diag::note_previous_exception_handler)
3272 << prev.getCatchStmt()->getCaughtType().getAsString();
3273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
Sebastian Redl63c4da02009-07-29 17:15:45 +00003275 prev = curr;
3276 }
3277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
John McCallaab3e412010-08-25 08:40:02 +00003279 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003280
Sebastian Redl9b244a82008-12-22 21:35:02 +00003281 // FIXME: We should detect handlers that cannot catch anything because an
3282 // earlier handler catches a superclass. Need to find a method that is not
3283 // quadratic for this.
3284 // Neither of these are explicitly forbidden, but every compiler detects them
3285 // and warns.
3286
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003287 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003288}
John Wiegley1c0675e2011-04-28 01:08:34 +00003289
Warren Huntf6be4cb2014-07-25 20:52:51 +00003290StmtResult
3291Sema::ActOnSEHTryBlock(bool IsCXXTry,
3292 SourceLocation TryLoc,
3293 Stmt *TryBlock,
3294 Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003295 assert(TryBlock && Handler);
3296
3297 getCurFunction()->setHasBranchProtectedScope();
3298
Warren Huntf6be4cb2014-07-25 20:52:51 +00003299 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003300}
3301
3302StmtResult
3303Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3304 Expr *FilterExpr,
3305 Stmt *Block) {
3306 assert(FilterExpr && Block);
3307
3308 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003309 return StmtError(Diag(FilterExpr->getExprLoc(),
3310 diag::err_filter_expression_integral)
3311 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003312 }
3313
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003314 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003315}
3316
3317StmtResult
3318Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3319 Stmt *Block) {
3320 assert(Block);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003321 return SEHFinallyStmt::Create(Context,Loc,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003322}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003323
Nico Weberc7d05962014-07-06 22:32:59 +00003324StmtResult
3325Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003326 Scope *SEHTryParent = CurScope;
3327 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3328 SEHTryParent = SEHTryParent->getParent();
3329 if (!SEHTryParent)
3330 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3331
Nico Weber9b982072014-07-07 00:12:30 +00003332 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003333}
3334
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003335StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3336 bool IsIfExists,
3337 NestedNameSpecifierLoc QualifierLoc,
3338 DeclarationNameInfo NameInfo,
3339 Stmt *Nested)
3340{
3341 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003342 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003343 cast<CompoundStmt>(Nested));
3344}
3345
3346
Chad Rosier02a84392012-08-10 17:56:09 +00003347StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003348 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003349 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003350 UnqualifiedId &Name,
3351 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003352 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003353 SS.getWithLocInContext(Context),
3354 GetNameFromUnqualifiedId(Name),
3355 Nested);
3356}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003357
3358RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003359Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3360 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003361 DeclContext *DC = CurContext;
3362 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3363 DC = DC->getParent();
3364
Craig Topperc3ec1492014-05-26 06:22:03 +00003365 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003366 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003367 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3368 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003369 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003370 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003371
3372 DC->addDecl(RD);
3373 RD->setImplicit();
3374 RD->startDefinition();
3375
Alexey Bataev9959db52014-05-06 10:08:46 +00003376 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003377 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003378 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003379 return RD;
3380}
3381
3382static void buildCapturedStmtCaptureList(
3383 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3384 SmallVectorImpl<Expr *> &CaptureInits,
3385 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3386
3387 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3388 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3389
3390 if (Cap->isThisCapture()) {
3391 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3392 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003393 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003394 continue;
3395 }
3396
3397 assert(Cap->isReferenceCapture() &&
3398 "non-reference capture not yet implemented");
3399
3400 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3401 CapturedStmt::VCK_ByRef,
3402 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003403 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003404 }
3405}
3406
3407void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003408 CapturedRegionKind Kind,
3409 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003410 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003411 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003412
Alexey Bataev9959db52014-05-06 10:08:46 +00003413 // Build the context parameter
3414 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3415 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3416 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3417 ImplicitParamDecl *Param
3418 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3419 DC->addDecl(Param);
3420
3421 CD->setContextParam(0, Param);
3422
3423 // Enter the capturing scope for this captured region.
3424 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3425
3426 if (CurScope)
3427 PushDeclContext(CurScope, CD);
3428 else
3429 CurContext = CD;
3430
3431 PushExpressionEvaluationContext(PotentiallyEvaluated);
3432}
3433
3434void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3435 CapturedRegionKind Kind,
3436 ArrayRef<CapturedParamNameType> Params) {
3437 CapturedDecl *CD = nullptr;
3438 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3439
3440 // Build the context parameter
3441 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3442 bool ContextIsFound = false;
3443 unsigned ParamNum = 0;
3444 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3445 E = Params.end();
3446 I != E; ++I, ++ParamNum) {
3447 if (I->second.isNull()) {
3448 assert(!ContextIsFound &&
3449 "null type has been found already for '__context' parameter");
3450 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3451 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3452 ImplicitParamDecl *Param
3453 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3454 DC->addDecl(Param);
3455 CD->setContextParam(ParamNum, Param);
3456 ContextIsFound = true;
3457 } else {
3458 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3459 ImplicitParamDecl *Param
3460 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3461 DC->addDecl(Param);
3462 CD->setParam(ParamNum, Param);
3463 }
3464 }
3465 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003466 if (!ContextIsFound) {
3467 // Add __context implicitly if it is not specified.
3468 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3469 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3470 ImplicitParamDecl *Param =
3471 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3472 DC->addDecl(Param);
3473 CD->setContextParam(ParamNum, Param);
3474 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003475 // Enter the capturing scope for this captured region.
3476 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3477
3478 if (CurScope)
3479 PushDeclContext(CurScope, CD);
3480 else
3481 CurContext = CD;
3482
3483 PushExpressionEvaluationContext(PotentiallyEvaluated);
3484}
3485
Wei Pan17fbf6e2013-05-04 03:59:06 +00003486void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003487 DiscardCleanupsInEvaluationContext();
3488 PopExpressionEvaluationContext();
3489
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003490 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3491 RecordDecl *Record = RSI->TheRecordDecl;
3492 Record->setInvalidDecl();
3493
Aaron Ballman62e47c42014-03-10 13:43:55 +00003494 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003495 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3496 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003497
Wei Pan17fbf6e2013-05-04 03:59:06 +00003498 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003499 PopFunctionScopeInfo();
3500}
3501
3502StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3503 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3504
3505 SmallVector<CapturedStmt::Capture, 4> Captures;
3506 SmallVector<Expr *, 4> CaptureInits;
3507 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3508
3509 CapturedDecl *CD = RSI->TheCapturedDecl;
3510 RecordDecl *RD = RSI->TheRecordDecl;
3511
Wei Pan17fbf6e2013-05-04 03:59:06 +00003512 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3513 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003514 CaptureInits, CD, RD);
3515
3516 CD->setBody(Res->getCapturedStmt());
3517 RD->completeDefinition();
3518
Wei Pan17fbf6e2013-05-04 03:59:06 +00003519 DiscardCleanupsInEvaluationContext();
3520 PopExpressionEvaluationContext();
3521
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003522 PopDeclContext();
3523 PopFunctionScopeInfo();
3524
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003525 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003526}