blob: d726f5f16ca8aa2f2939abe70960465bcbb38cba [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000022#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000024#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000035using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000036using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000037
Richard Smith945f8d32013-01-14 22:39:08 +000038StmtResult Sema::ActOnExprStmt(ExprResult FE) {
39 if (FE.isInvalid())
40 return StmtError();
41
42 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
43 /*DiscardedValue*/ true);
44 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000045 return StmtError();
46
Chris Lattner903eb512008-07-25 23:18:17 +000047 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
48 // void expression for its side effects. Conversion to void allows any
49 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000050
Chris Lattner903eb512008-07-25 23:18:17 +000051 // Same thing in for stmt first clause (when expr) and third clause.
Richard Smith945f8d32013-01-14 22:39:08 +000052 return Owned(static_cast<Stmt*>(FE.take()));
Chris Lattner1ec5f562007-06-27 05:38:08 +000053}
54
55
John McCalleaef89b2013-03-22 02:10:40 +000056StmtResult Sema::ActOnExprStmtError() {
57 DiscardCleanupsInEvaluationContext();
58 return StmtError();
59}
60
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000061StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000062 bool HasLeadingEmptyMacro) {
63 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000064}
65
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000066StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000068 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattnercbafe8d2009-04-12 20:13:14 +000070 // If we have an invalid decl, just return an error.
71 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattner34a22092009-03-04 04:23:07 +000073 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000074}
Chris Lattneraf8d5812006-11-10 05:07:45 +000075
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000076void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000077 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000078
Douglas Gregor2eb1c572013-04-08 20:52:24 +000079 // If we don't have a declaration, or we have an invalid declaration,
80 // just return.
81 if (DG.isNull() || !DG.isSingleDecl())
82 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083
Douglas Gregor2eb1c572013-04-08 20:52:24 +000084 Decl *decl = DG.getSingleDecl();
85 if (!decl || decl->isInvalidDecl())
86 return;
87
88 // Only variable declarations are permitted.
89 VarDecl *var = dyn_cast<VarDecl>(decl);
90 if (!var) {
91 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
92 decl->setInvalidDecl();
93 return;
94 }
John McCall31168b02011-06-15 23:02:42 +000095
John McCalld4631322011-06-17 06:42:21 +000096 // foreach variables are never actually initialized in the way that
97 // the parser came up with.
98 var->setInit(0);
John McCall31168b02011-06-15 23:02:42 +000099
John McCalld4631322011-06-17 06:42:21 +0000100 // In ARC, we don't need to retain the iteration variable of a fast
101 // enumeration loop. Rather than actually trying to catch that
102 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000103 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000104 QualType type = var->getType();
105
106 // Only do this if we inferred the lifetime. Inferred lifetime
107 // will show up as a local qualifier because explicit lifetime
108 // should have shown up as an AttributedType instead.
109 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
110 // Add 'const' and mark the variable as pseudo-strong.
111 var->setType(type.withConst());
112 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000113 }
114 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000115}
116
Chandler Carruthe2669392011-08-17 09:34:37 +0000117/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000118///
119/// Adding a cast to void (or other expression wrappers) will prevent the
120/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000121static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000122 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000123 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124
125 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
126 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthe2669392011-08-17 09:34:37 +0000127 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000128
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000130 IsNotEqual = Op->getOpcode() == BO_NE;
131 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
133 if (Op->getOperator() != OO_EqualEqual &&
134 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthe2669392011-08-17 09:34:37 +0000135 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000136
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
139 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000140 } else {
141 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000142 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000143 }
144
145 // Suppress warnings when the operator, suspicious as it may be, comes from
146 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000147 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000148 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000149
Chandler Carruthe2669392011-08-17 09:34:37 +0000150 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000151 << (unsigned)IsNotEqual << E->getSourceRange();
152
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000153 // If the LHS is a plausible entity to assign to, provide a fixit hint to
154 // correct common typos.
155 if (CanAssign) {
156 if (IsNotEqual)
157 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
158 << FixItHint::CreateReplacement(Loc, "|=");
159 else
160 S.Diag(Loc, diag::note_equality_comparison_to_assign)
161 << FixItHint::CreateReplacement(Loc, "=");
162 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000163
164 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000165}
166
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000167void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000168 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
169 return DiagnoseUnusedExprResult(Label->getSubStmt());
170
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000171 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000172 if (!E)
173 return;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000174 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000175 // In most cases, we don't want to warn if the expression is written in a
176 // macro body, or if the macro comes from a system header. If the offending
177 // expression is a call to a function with the warn_unused_result attribute,
178 // we warn no matter the location. Because of the order in which the various
179 // checks need to happen, we factor out the macro-related test here.
180 bool ShouldSuppress =
181 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
182 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000183
Eli Friedmanc11535c2012-05-24 00:47:05 +0000184 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000185 SourceLocation Loc;
186 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000187 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000188 return;
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattner6dc7e572012-08-31 22:39:21 +0000190 // If this is a GNU statement expression expanded from a macro, it is probably
191 // unused because it is a function-like macro that can be used as either an
192 // expression or statement. Don't warn, because it is almost certainly a
193 // false positive.
194 if (isa<StmtExpr>(E) && Loc.isMacroID())
195 return;
196
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000197 // Okay, we have an unused result. Depending on what the base expression is,
198 // we might want to make a more specific diagnostic. Check for one of these
199 // cases now.
200 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000201 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000202 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000203 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
204 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000205
Chandler Carruthe2669392011-08-17 09:34:37 +0000206 if (DiagnoseUnusedComparison(*this, E))
207 return;
208
Eli Friedmanc11535c2012-05-24 00:47:05 +0000209 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000210 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000211 if (E->getType()->isVoidType())
212 return;
213
Chris Lattner1a6babf2009-10-13 04:53:48 +0000214 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000215 // a more specific message to make it clear what is happening. If the call
216 // is written in a macro body, only warn if it has the warn_unused_result
217 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000218 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000219 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000220 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000221 return;
222 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000223 if (ShouldSuppress)
224 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000225 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000226 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
227 return;
228 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000229 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000230 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
231 return;
232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000234 } else if (ShouldSuppress)
235 return;
236
237 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000238 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000239 Diag(Loc, diag::err_arc_unused_init_message) << R1;
240 return;
241 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000242 const ObjCMethodDecl *MD = ME->getMethodDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +0000243 if (MD && MD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000244 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000245 return;
246 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000247 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
248 const Expr *Source = POE->getSyntacticForm();
249 if (isa<ObjCSubscriptRefExpr>(Source))
250 DiagID = diag::warn_unused_container_subscript_expr;
251 else
252 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000253 } else if (const CXXFunctionalCastExpr *FC
254 = dyn_cast<CXXFunctionalCastExpr>(E)) {
255 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
256 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
257 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000258 }
John McCall2351cb92010-04-06 22:24:14 +0000259 // Diagnose "(void*) blah" as a typo for "(void) blah".
260 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
261 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
262 QualType T = TI->getType();
263
264 // We really do want to use the non-canonical type here.
265 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000266 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000267
268 Diag(Loc, diag::warn_unused_voidptr)
269 << FixItHint::CreateRemoval(TL.getStarLoc());
270 return;
271 }
272 }
273
Eli Friedmanc11535c2012-05-24 00:47:05 +0000274 if (E->isGLValue() && E->getType().isVolatileQualified()) {
275 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
276 return;
277 }
278
Ted Kremenek3427fac2011-02-23 01:52:04 +0000279 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000280}
281
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000282void Sema::ActOnStartOfCompoundStmt() {
283 PushCompoundScope();
284}
285
286void Sema::ActOnFinishOfCompoundStmt() {
287 PopCompoundScope();
288}
289
290sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
291 return getCurFunction()->CompoundScopes.back();
292}
293
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000294StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
295 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
296 const unsigned NumElts = Elts.size();
297
Chris Lattnerd864daf2007-08-27 04:29:41 +0000298 // If we're in C89 mode, check that we don't have any decls after stmts. If
299 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000300 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000301 // Note that __extension__ can be around a decl.
302 unsigned i = 0;
303 // Skip over all declarations.
304 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
305 /*empty*/;
306
307 // We found the end of the list or a statement. Scan for another declstmt.
308 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
309 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattnerd864daf2007-08-27 04:29:41 +0000311 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000312 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000313 Diag(D->getLocation(), diag::ext_mixed_decls_code);
314 }
315 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000316 // Warn about unused expressions in statements.
317 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000318 // Ignore statements that are last in a statement expression.
319 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000320 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000321
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000322 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000323 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000324
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000325 // Check for suspicious empty body (null statement) in `for' and `while'
326 // statements. Don't do anything for template instantiations, this just adds
327 // noise.
328 if (NumElts != 0 && !CurrentInstantiationScope &&
329 getCurCompoundScope().HasEmptyLoopBodies) {
330 for (unsigned i = 0; i != NumElts - 1; ++i)
331 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
332 }
333
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000334 return Owned(new (Context) CompoundStmt(Context, Elts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000335}
336
John McCalldadc5752010-08-24 06:29:42 +0000337StmtResult
John McCallb268a282010-08-23 23:25:46 +0000338Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
339 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000340 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000341 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000342
John McCallaab3e412010-08-25 08:40:02 +0000343 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000344 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000345 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000346 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000347
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000348 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000349 // C99 6.8.4.2p3: The expression shall be an integer constant.
350 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000351 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
352 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
353 if (!LHSVal)
354 return StmtError();
355 }
Richard Smithf8379a02012-01-18 23:55:52 +0000356
357 // GCC extension: The expression shall be an integer constant.
358
Richard Smithf4c51d92012-02-04 09:53:13 +0000359 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
360 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
361 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000362 }
363 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000364
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000365 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
366 getLangOpts().CPlusPlus11).take();
367 if (RHSVal)
368 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
369 getLangOpts().CPlusPlus11).take();
Richard Smithf8379a02012-01-18 23:55:52 +0000370
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000371 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
372 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000373 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000374 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000375}
376
Chris Lattner34a22092009-03-04 04:23:07 +0000377/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000378void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000379 DiagnoseUnusedExprResult(SubStmt);
380
Chris Lattner34a22092009-03-04 04:23:07 +0000381 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000382 CS->setSubStmt(SubStmt);
383}
384
John McCalldadc5752010-08-24 06:29:42 +0000385StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000386Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000387 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000388 DiagnoseUnusedExprResult(SubStmt);
389
John McCallaab3e412010-08-25 08:40:02 +0000390 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000391 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000392 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000393 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000394
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000395 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000396 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000397 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000398}
399
John McCalldadc5752010-08-24 06:29:42 +0000400StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000401Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
402 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000403 // If the label was multiply defined, reject it now.
404 if (TheDecl->getStmt()) {
405 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
406 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000407 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000408 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000409
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000410 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000411 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
412 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000413 if (!TheDecl->isGnuLocal()) {
414 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000415 TheDecl->setLocation(IdentLoc);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000416 }
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000417 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000418}
419
Richard Smithc202b282012-04-14 00:33:13 +0000420StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000421 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000422 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000423 // Fill in the declaration and return it.
424 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smithc202b282012-04-14 00:33:13 +0000425 return Owned(LS);
426}
427
John McCalldadc5752010-08-24 06:29:42 +0000428StmtResult
John McCall48871652010-08-21 09:40:31 +0000429Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000430 Stmt *thenStmt, SourceLocation ElseLoc,
431 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000432 // If the condition was invalid, discard the if statement. We could recover
433 // better by replacing it with a valid expr, but don't do that yet.
434 if (!CondVal.get() && !CondVar) {
435 getCurFunction()->setHasDroppedStmt();
436 return StmtError();
437 }
438
John McCalldadc5752010-08-24 06:29:42 +0000439 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000440
Douglas Gregor633caca2009-11-23 23:44:04 +0000441 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000442 if (CondVar) {
443 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000444 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000445 if (CondResult.isInvalid())
446 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000447 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000448 Expr *ConditionExpr = CondResult.takeAs<Expr>();
449 if (!ConditionExpr)
450 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000452 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000453
John McCallb268a282010-08-23 23:25:46 +0000454 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000455 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
456 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000457 }
458
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000459 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000460
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000462 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000463}
Steve Naroff86272ea2007-05-29 02:14:17 +0000464
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000465/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
466/// the specified width and sign. If an overflow occurs, detect it and emit
467/// the specified diagnostic.
468void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
469 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000470 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000471 unsigned DiagID) {
472 // Perform a conversion to the promoted condition type if needed.
473 if (NewWidth > Val.getBitWidth()) {
474 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000475 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000476 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000477
478 // If the input was signed and negative and the output is
479 // unsigned, don't bother to warn: this is implementation-defined
480 // behavior.
481 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000482 } else if (NewWidth < Val.getBitWidth()) {
483 // If this is a truncation, check for overflow.
484 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000485 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000486 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000487 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000488 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000489 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000490 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000491
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000492 // Regardless of whether a diagnostic was emitted, really do the
493 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000494 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000495 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000496 } else if (NewSign != Val.isSigned()) {
497 // Convert the sign to match the sign of the condition. This can cause
498 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000500 // behavior.
501 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000502 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000503 }
504}
505
Chris Lattner67998452007-08-23 18:29:20 +0000506namespace {
507 struct CaseCompareFunctor {
508 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
509 const llvm::APSInt &RHS) {
510 return LHS.first < RHS;
511 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000512 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
513 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
514 return LHS.first < RHS.first;
515 }
Chris Lattner67998452007-08-23 18:29:20 +0000516 bool operator()(const llvm::APSInt &LHS,
517 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
518 return LHS < RHS.first;
519 }
520 };
521}
522
Chris Lattner4b2ff022007-09-21 18:15:22 +0000523/// CmpCaseVals - Comparison predicate for sorting case values.
524///
525static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
526 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
527 if (lhs.first < rhs.first)
528 return true;
529
530 if (lhs.first == rhs.first &&
531 lhs.second->getCaseLoc().getRawEncoding()
532 < rhs.second->getCaseLoc().getRawEncoding())
533 return true;
534 return false;
535}
536
Douglas Gregorbd6839732010-02-08 22:24:16 +0000537/// CmpEnumVals - Comparison predicate for sorting enumeration values.
538///
539static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
540 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
541{
542 return lhs.first < rhs.first;
543}
544
545/// EqEnumVals - Comparison preficate for uniqing enumeration values.
546///
547static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
548 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
549{
550 return lhs.first == rhs.first;
551}
552
Chris Lattnera96d4272009-10-16 16:45:22 +0000553/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
554/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000555static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
556 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
557 expr = cleanups->getSubExpr();
558 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
559 if (impcast->getCastKind() != CK_IntegralCast) break;
560 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000561 }
562 return expr->getType();
563}
564
John McCalldadc5752010-08-24 06:29:42 +0000565StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000567 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000568 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000569
Douglas Gregore60e41a2010-05-06 17:25:47 +0000570 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000571 if (CondVar) {
572 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000573 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
574 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000575 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576
John McCallb268a282010-08-23 23:25:46 +0000577 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579
John McCallb268a282010-08-23 23:25:46 +0000580 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000581 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregore2b37442012-05-04 22:38:52 +0000583 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
584 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000585
Douglas Gregore2b37442012-05-04 22:38:52 +0000586 public:
587 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000588 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
589 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000590
Richard Smithccc11812013-05-21 19:05:48 +0000591 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
592 QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000593 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
594 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000595
Richard Smithccc11812013-05-21 19:05:48 +0000596 virtual SemaDiagnosticBuilder diagnoseIncomplete(
597 Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000598 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
599 << T << Cond->getSourceRange();
600 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000601
Richard Smithccc11812013-05-21 19:05:48 +0000602 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
603 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000604 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
605 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000606
Richard Smithccc11812013-05-21 19:05:48 +0000607 virtual SemaDiagnosticBuilder noteExplicitConv(
608 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000609 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
610 << ConvTy->isEnumeralType() << ConvTy;
611 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000612
Richard Smithccc11812013-05-21 19:05:48 +0000613 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
614 QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000615 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
616 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000617
Richard Smithccc11812013-05-21 19:05:48 +0000618 virtual SemaDiagnosticBuilder noteAmbiguous(
619 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000620 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
621 << ConvTy->isEnumeralType() << ConvTy;
622 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000623
Richard Smithccc11812013-05-21 19:05:48 +0000624 virtual SemaDiagnosticBuilder diagnoseConversion(
625 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
626 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000627 }
628 } SwitchDiagnoser(Cond);
629
Richard Smithccc11812013-05-21 19:05:48 +0000630 CondResult =
631 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000632 if (CondResult.isInvalid()) return StmtError();
633 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
John McCall5939b162011-08-06 07:30:58 +0000635 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
636 CondResult = UsualUnaryConversions(Cond);
637 if (CondResult.isInvalid()) return StmtError();
638 Cond = CondResult.take();
639
John McCall48871652010-08-21 09:40:31 +0000640 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000641 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000642 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000643 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000644 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000645 }
John McCalla95172b2010-08-01 00:26:45 +0000646
John McCallaab3e412010-08-25 08:40:02 +0000647 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648
John McCallb268a282010-08-23 23:25:46 +0000649 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000650 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000651 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000652}
653
Gabor Greif16e02862010-10-01 22:05:14 +0000654static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
655 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000656 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000657 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000658 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000659 Val.setIsSigned(IsSigned);
660}
661
Dmitri Gribenko58683752013-12-05 22:52:07 +0000662/// Returns true if we should emit a diagnostic about this case expression not
663/// being a part of the enum used in the switch controlling expression.
664static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
665 const EnumDecl *ED,
666 const Expr *CaseExpr) {
667 // Don't warn if the 'case' expression refers to a static const variable of
668 // the enum type.
669 CaseExpr = CaseExpr->IgnoreParenImpCasts();
670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
671 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
672 if (!VD->hasGlobalStorage())
673 return true;
674 QualType VarType = VD->getType();
675 if (!VarType.isConstQualified())
676 return true;
677 QualType EnumType = Ctx.getTypeDeclType(ED);
678 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
679 return false;
680 }
681 }
682 return true;
683}
684
John McCalldadc5752010-08-24 06:29:42 +0000685StmtResult
John McCallb268a282010-08-23 23:25:46 +0000686Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
687 Stmt *BodyStmt) {
688 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000689 assert(SS == getCurFunction()->SwitchStack.back() &&
690 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000691
Steve Naroff42a350a2007-09-01 21:08:38 +0000692 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000693 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000694
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000695 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000696 if (!CondExpr) return StmtError();
697
698 QualType CondType = CondExpr->getType();
699
John McCalld3dfbd62010-05-18 03:19:21 +0000700 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000701 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000702 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000703
Chris Lattnera96d4272009-10-16 16:45:22 +0000704 // C++ 6.4.2.p2:
705 // Integral promotions are performed (on the switch condition).
706 //
707 // A case value unrepresentable by the original switch condition
708 // type (before the promotion) doesn't make sense, even when it can
709 // be represented by the promoted type. Therefore we need to find
710 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000711 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000712 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000714 // appropriate type now, just return an error.
715 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000716 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000717
Chris Lattner4ebae652010-04-16 23:34:13 +0000718 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000719 // switch(bool_expr) {...} is often a programmer error, e.g.
720 // switch(n && mask) { ... } // Doh - should be "n & mask".
721 // One can always use an if statement instead of switch(bool_expr).
722 Diag(SwitchLoc, diag::warn_bool_switch_condition)
723 << CondExpr->getSourceRange();
724 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000725 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000726
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000727 // Get the bitwidth of the switched-on value before promotions. We must
728 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000729 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000730 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000731 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000732 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier02a84392012-08-10 17:56:09 +0000733 bool CondIsSigned
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000734 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000736 // Accumulate all of the case values in a vector so that we can sort them
737 // and detect duplicates. This vector contains the APInt for the case after
738 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000739 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000740 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000742 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000743 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
744 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000746 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattner10cb5e52007-08-23 06:23:56 +0000748 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000749
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000750 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000751 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000752
Anders Carlsson51873c22007-07-22 07:07:56 +0000753 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000754 if (TheDefaultStmt) {
755 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000756 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000757
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000758 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000759 // we'll return a valid AST. This requires recursing down the AST and
760 // finding it, not something we are set up to do right now. For now,
761 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000762 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000763 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000764 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000765
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000766 } else {
767 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattnera65e1f32008-01-16 19:17:22 +0000769 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000770
771 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
772 HasDependentValue = true;
773 break;
774 }
Mike Stump11289f42009-09-09 15:08:12 +0000775
Richard Smithf8379a02012-01-18 23:55:52 +0000776 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000777
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000778 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000779 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
780 // constant expression of the promoted type of the switch condition.
781 ExprResult ConvLo =
782 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
783 if (ConvLo.isInvalid()) {
784 CaseListIsErroneous = true;
785 continue;
786 }
787 Lo = ConvLo.take();
788 } else {
789 // We already verified that the expression has a i-c-e value (C99
790 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000791 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000792
793 // If the LHS is not the same type as the condition, insert an implicit
794 // cast.
795 Lo = DefaultLvalueConversion(Lo).take();
796 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
797 }
798
799 // Convert the value to the same width/sign as the condition had prior to
800 // integral promotions.
801 //
802 // FIXME: This causes us to reject valid code:
803 // switch ((char)c) { case 256: case 0: return 0; }
804 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000805 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000806 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000807 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000808
Chris Lattnera65e1f32008-01-16 19:17:22 +0000809 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000810
Chris Lattner10cb5e52007-08-23 06:23:56 +0000811 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000812 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000813 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000814 CS->getRHS()->isValueDependent()) {
815 HasDependentValue = true;
816 break;
817 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000818 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000819 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000820 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000821 }
822 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000823
824 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000825 // If we don't have a default statement, check whether the
826 // condition is constant.
827 llvm::APSInt ConstantCondValue;
828 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000829 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000830 HasConstantCond
Richard Smith5fab0c92011-12-28 19:48:30 +0000831 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
832 Expr::SE_AllowSideEffects);
833 assert(!HasConstantCond ||
834 (ConstantCondValue.getBitWidth() == CondWidth &&
835 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000836 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000837 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000838
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000839 // Sort all the scalar case values so we can easily detect duplicates.
840 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
841
842 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000843 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
844 if (ShouldCheckConstantCond &&
845 CaseVals[i].first == ConstantCondValue)
846 ShouldCheckConstantCond = false;
847
848 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000849 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000850 // First, determine if either case value has a name
851 StringRef PrevString, CurrString;
852 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
853 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
854 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
855 PrevString = DeclRef->getDecl()->getName();
856 }
857 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
858 CurrString = DeclRef->getDecl()->getName();
859 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000860 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000861 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000862
863 if (PrevString == CurrString)
864 Diag(CaseVals[i].second->getLHS()->getLocStart(),
865 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000866 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000867 else
868 Diag(CaseVals[i].second->getLHS()->getLocStart(),
869 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000870 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
871 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000872 CaseValStr;
873
John McCalld3dfbd62010-05-18 03:19:21 +0000874 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000875 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000876 // FIXME: We really want to remove the bogus case stmt from the
877 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000878 CaseListIsErroneous = true;
879 }
880 }
881 }
Mike Stump11289f42009-09-09 15:08:12 +0000882
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000883 // Detect duplicate case ranges, which usually don't exist at all in
884 // the first place.
885 if (!CaseRanges.empty()) {
886 // Sort all the case ranges by their low value so we can easily detect
887 // overlaps between ranges.
888 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000889
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000890 // Scan the ranges, computing the high values and removing empty ranges.
891 std::vector<llvm::APSInt> HiVals;
892 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000893 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000894 CaseStmt *CR = CaseRanges[i].second;
895 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000896 llvm::APSInt HiVal;
897
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000898 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000899 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
900 // constant expression of the promoted type of the switch condition.
901 ExprResult ConvHi =
902 CheckConvertedConstantExpression(Hi, CondType, HiVal,
903 CCEK_CaseValue);
904 if (ConvHi.isInvalid()) {
905 CaseListIsErroneous = true;
906 continue;
907 }
908 Hi = ConvHi.take();
909 } else {
910 HiVal = Hi->EvaluateKnownConstInt(Context);
911
912 // If the RHS is not the same type as the condition, insert an
913 // implicit cast.
914 Hi = DefaultLvalueConversion(Hi).take();
915 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
916 }
Mike Stump11289f42009-09-09 15:08:12 +0000917
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000918 // Convert the value to the same width/sign as the condition.
919 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000920 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000921 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000923 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000924
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000925 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000926 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000927 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
928 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000929 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000930 CaseRanges.erase(CaseRanges.begin()+i);
931 --i, --e;
932 continue;
933 }
John McCalld3dfbd62010-05-18 03:19:21 +0000934
935 if (ShouldCheckConstantCond &&
936 LoVal <= ConstantCondValue &&
937 ConstantCondValue <= HiVal)
938 ShouldCheckConstantCond = false;
939
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000940 HiVals.push_back(HiVal);
941 }
Mike Stump11289f42009-09-09 15:08:12 +0000942
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000943 // Rescan the ranges, looking for overlap with singleton values and other
944 // ranges. Since the range list is sorted, we only need to compare case
945 // ranges with their neighbors.
946 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
947 llvm::APSInt &CRLo = CaseRanges[i].first;
948 llvm::APSInt &CRHi = HiVals[i];
949 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000950
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000951 // Check to see whether the case range overlaps with any
952 // singleton cases.
953 CaseStmt *OverlapStmt = 0;
954 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000955
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000956 // Find the smallest value >= the lower bound. If I is in the
957 // case range, then we have overlap.
958 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
959 CaseVals.end(), CRLo,
960 CaseCompareFunctor());
961 if (I != CaseVals.end() && I->first < CRHi) {
962 OverlapVal = I->first; // Found overlap with scalar.
963 OverlapStmt = I->second;
964 }
Mike Stump11289f42009-09-09 15:08:12 +0000965
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000966 // Find the smallest value bigger than the upper bound.
967 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
968 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
969 OverlapVal = (I-1)->first; // Found overlap with scalar.
970 OverlapStmt = (I-1)->second;
971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000973 // Check to see if this case stmt overlaps with the subsequent
974 // case range.
975 if (i && CRLo <= HiVals[i-1]) {
976 OverlapVal = HiVals[i-1]; // Found overlap with range.
977 OverlapStmt = CaseRanges[i-1].second;
978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000980 if (OverlapStmt) {
981 // If we have a duplicate, report it.
982 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
983 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000984 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000985 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000986 // FIXME: We really want to remove the bogus case stmt from the
987 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000988 CaseListIsErroneous = true;
989 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000990 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000991 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000992
John McCalld3dfbd62010-05-18 03:19:21 +0000993 // Complain if we have a constant condition and we didn't find a match.
994 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
995 // TODO: it would be nice if we printed enums as enums, chars as
996 // chars, etc.
997 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
998 << ConstantCondValue.toString(10)
999 << CondExpr->getSourceRange();
1000 }
1001
1002 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001003 // values. We only issue a warning if there is not 'default:', but
1004 // we still do the analysis to preserve this information in the AST
1005 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001006 //
Chris Lattner51679082010-09-16 17:09:42 +00001007 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001008
Douglas Gregorbd6839732010-02-08 22:24:16 +00001009 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001010 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001011 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001012 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +00001013 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001014 EnumValsTy EnumVals;
1015
John McCalld3dfbd62010-05-18 03:19:21 +00001016 // Gather all enum values, set their type and sort them,
1017 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001018 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001019 llvm::APSInt Val = EDI->getInitVal();
1020 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001021 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001022 }
1023 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +00001024 EnumValsTy::iterator EIend =
1025 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001026
1027 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001028 EnumValsTy::const_iterator EI = EnumVals.begin();
1029 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1030 CI != CaseVals.end(); CI++) {
1031 while (EI != EIend && EI->first < CI->first)
1032 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001033 if (EI == EIend || EI->first > CI->first) {
1034 Expr *CaseExpr = CI->second->getLHS();
1035 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1036 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1037 << CondTypeBeforePromotion;
1038 }
David Blaikiee476f972012-01-22 02:31:55 +00001039 }
1040 // See which of case ranges aren't in enum
1041 EI = EnumVals.begin();
1042 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1043 RI != CaseRanges.end() && EI != EIend; RI++) {
1044 while (EI != EIend && EI->first < RI->first)
1045 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
David Blaikiee476f972012-01-22 02:31:55 +00001047 if (EI == EIend || EI->first != RI->first) {
Dmitri Gribenko58683752013-12-05 22:52:07 +00001048 Expr *CaseExpr = RI->second->getLHS();
1049 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1050 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1051 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +00001052 }
David Blaikiee476f972012-01-22 02:31:55 +00001053
Chad Rosier02a84392012-08-10 17:56:09 +00001054 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001055 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1056 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1057 while (EI != EIend && EI->first < Hi)
1058 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001059 if (EI == EIend || EI->first != Hi) {
1060 Expr *CaseExpr = RI->second->getRHS();
1061 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1062 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1063 << CondTypeBeforePromotion;
1064 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
Ted Kremenekc42f3452010-09-09 00:05:53 +00001067 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +00001068 CaseValsTy::const_iterator CI = CaseVals.begin();
1069 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001070 bool hasCasesNotInSwitch = false;
1071
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073
David Blaikiee476f972012-01-22 02:31:55 +00001074 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001075 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001076 while (CI != CaseVals.end() && CI->first < EI->first)
1077 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078
Douglas Gregorbd6839732010-02-08 22:24:16 +00001079 if (CI != CaseVals.end() && CI->first == EI->first)
1080 continue;
1081
Ted Kremenekc42f3452010-09-09 00:05:53 +00001082 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001083 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001084 llvm::APSInt Hi =
1085 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001086 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001087 if (EI->first <= Hi)
1088 break;
1089 }
1090
Ted Kremenekc42f3452010-09-09 00:05:53 +00001091 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001092 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001093 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001094 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
David Blaikie60ac6382012-01-23 04:46:12 +00001097 if (TheDefaultStmt && UnhandledNames.empty())
1098 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001099
Chris Lattner51679082010-09-16 17:09:42 +00001100 // Produce a nice diagnostic if multiple values aren't handled.
1101 switch (UnhandledNames.size()) {
1102 case 0: break;
1103 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001104 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001105 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001106 << UnhandledNames[0];
1107 break;
1108 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001109 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001110 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001111 << UnhandledNames[0] << UnhandledNames[1];
1112 break;
1113 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001114 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1115 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001116 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1117 break;
1118 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001119 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1120 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001121 << (unsigned)UnhandledNames.size()
1122 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1123 break;
1124 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001125
1126 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001127 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001128 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001129 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001130
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001131 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1132 diag::warn_empty_switch_body);
1133
Mike Stump87c57ac2009-05-16 07:39:55 +00001134 // FIXME: If the case list was broken is some way, we don't have a good system
1135 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001136 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001137 return StmtError();
1138
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001139 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001140}
1141
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001142void
1143Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1144 Expr *SrcExpr) {
Joey Gouly1ba27332013-06-06 13:48:00 +00001145 if (Diags.getDiagnosticLevel(diag::warn_not_in_enum_assignment,
1146 SrcExpr->getExprLoc()) ==
1147 DiagnosticsEngine::Ignored)
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001148 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001149
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001150 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001151 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001152 SrcType->isIntegerType()) {
1153 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1154 SrcExpr->isIntegerConstantExpr(Context)) {
1155 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001156 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001157 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1158
1159 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001160 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001161 const EnumDecl *ED = ET->getDecl();
Joey Gouly1ba27332013-06-06 13:48:00 +00001162 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1163 EnumValsTy;
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001164 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001165
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001166 // Gather all enum values, set their type and sort them,
1167 // allowing easier comparison with rhs constant.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001168 for (auto *EDI : ED->enumerators()) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001169 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly1ba27332013-06-06 13:48:00 +00001170 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001171 EnumVals.push_back(std::make_pair(Val, EDI));
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001172 }
1173 if (EnumVals.empty())
1174 return;
1175 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1176 EnumValsTy::iterator EIend =
Joey Gouly1ba27332013-06-06 13:48:00 +00001177 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001178
Joey Gouly1ba27332013-06-06 13:48:00 +00001179 // See which values aren't in the enum.
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001180 EnumValsTy::const_iterator EI = EnumVals.begin();
1181 while (EI != EIend && EI->first < RhsVal)
1182 EI++;
1183 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly1ba27332013-06-06 13:48:00 +00001184 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001185 << DstType.getUnqualifiedType();
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001186 }
1187 }
1188 }
1189}
1190
John McCalldadc5752010-08-24 06:29:42 +00001191StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001192Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001193 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001194 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001195
Douglas Gregor680f8612009-11-24 21:15:44 +00001196 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001197 if (CondVar) {
1198 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001199 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001200 if (CondResult.isInvalid())
1201 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001202 }
John McCallb268a282010-08-23 23:25:46 +00001203 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001204 if (!ConditionExpr)
1205 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001206 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001207
John McCallb268a282010-08-23 23:25:46 +00001208 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001210 if (isa<NullStmt>(Body))
1211 getCurCompoundScope().setHasEmptyLoopBodies();
1212
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001213 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +00001214 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001215}
1216
John McCalldadc5752010-08-24 06:29:42 +00001217StmtResult
John McCallb268a282010-08-23 23:25:46 +00001218Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001219 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001220 Expr *Cond, SourceLocation CondRParen) {
1221 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001222
Serge Pavlov09f99242014-01-23 15:05:00 +00001223 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001224 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001225 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001226 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +00001227 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +00001228
Richard Smith945f8d32013-01-14 22:39:08 +00001229 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001230 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001231 return StmtError();
John McCallb268a282010-08-23 23:25:46 +00001232 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233
John McCallb268a282010-08-23 23:25:46 +00001234 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001235
John McCallb268a282010-08-23 23:25:46 +00001236 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001237}
1238
Richard Trieu451a5db2012-04-30 18:01:30 +00001239namespace {
1240 // This visitor will traverse a conditional statement and store all
1241 // the evaluated decls into a vector. Simple is set to true if none
1242 // of the excluded constructs are used.
1243 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1244 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001245 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001246 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001247 public:
1248 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001249
Richard Trieu9d228802013-05-31 22:46:45 +00001250 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001251 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001252 Inherited(S.Context),
1253 Decls(Decls),
1254 Ranges(Ranges),
1255 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001256
Richard Trieu9d228802013-05-31 22:46:45 +00001257 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001258
Richard Trieu9d228802013-05-31 22:46:45 +00001259 // Replaces the method in EvaluatedExprVisitor.
1260 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001261 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001262 }
1263
1264 // Any Stmt not whitelisted will cause the condition to be marked complex.
1265 void VisitStmt(Stmt *S) {
1266 Simple = false;
1267 }
1268
1269 void VisitBinaryOperator(BinaryOperator *E) {
1270 Visit(E->getLHS());
1271 Visit(E->getRHS());
1272 }
1273
1274 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001275 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001276 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001277
Richard Trieu9d228802013-05-31 22:46:45 +00001278 void VisitUnaryOperator(UnaryOperator *E) {
1279 // Skip checking conditionals with derefernces.
1280 if (E->getOpcode() == UO_Deref)
1281 Simple = false;
1282 else
1283 Visit(E->getSubExpr());
1284 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001285
Richard Trieu9d228802013-05-31 22:46:45 +00001286 void VisitConditionalOperator(ConditionalOperator *E) {
1287 Visit(E->getCond());
1288 Visit(E->getTrueExpr());
1289 Visit(E->getFalseExpr());
1290 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001291
Richard Trieu9d228802013-05-31 22:46:45 +00001292 void VisitParenExpr(ParenExpr *E) {
1293 Visit(E->getSubExpr());
1294 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001295
Richard Trieu9d228802013-05-31 22:46:45 +00001296 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1297 Visit(E->getOpaqueValue()->getSourceExpr());
1298 Visit(E->getFalseExpr());
1299 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001300
Richard Trieu9d228802013-05-31 22:46:45 +00001301 void VisitIntegerLiteral(IntegerLiteral *E) { }
1302 void VisitFloatingLiteral(FloatingLiteral *E) { }
1303 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1304 void VisitCharacterLiteral(CharacterLiteral *E) { }
1305 void VisitGNUNullExpr(GNUNullExpr *E) { }
1306 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001307
Richard Trieu9d228802013-05-31 22:46:45 +00001308 void VisitDeclRefExpr(DeclRefExpr *E) {
1309 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1310 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001311
Richard Trieu9d228802013-05-31 22:46:45 +00001312 Ranges.push_back(E->getSourceRange());
1313
1314 Decls.insert(VD);
1315 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001316
1317 }; // end class DeclExtractor
1318
1319 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001320 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001321 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1322 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1323 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001324
Richard Trieu9d228802013-05-31 22:46:45 +00001325 public:
1326 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001327
Richard Trieu9d228802013-05-31 22:46:45 +00001328 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1329 Stmt *Statement) :
1330 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1331 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001332
Richard Trieu9d228802013-05-31 22:46:45 +00001333 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001334 }
1335
Richard Trieu9d228802013-05-31 22:46:45 +00001336 void VisitReturnStmt(ReturnStmt *S) {
1337 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001338 }
1339
Richard Trieu9d228802013-05-31 22:46:45 +00001340 void VisitBreakStmt(BreakStmt *S) {
1341 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001342 }
1343
Richard Trieu9d228802013-05-31 22:46:45 +00001344 void VisitGotoStmt(GotoStmt *S) {
1345 FoundDecl = true;
1346 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001347
Richard Trieu9d228802013-05-31 22:46:45 +00001348 void VisitCastExpr(CastExpr *E) {
1349 if (E->getCastKind() == CK_LValueToRValue)
1350 CheckLValueToRValueCast(E->getSubExpr());
1351 else
1352 Visit(E->getSubExpr());
1353 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001354
Richard Trieu9d228802013-05-31 22:46:45 +00001355 void CheckLValueToRValueCast(Expr *E) {
1356 E = E->IgnoreParenImpCasts();
1357
1358 if (isa<DeclRefExpr>(E)) {
1359 return;
1360 }
1361
1362 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1363 Visit(CO->getCond());
1364 CheckLValueToRValueCast(CO->getTrueExpr());
1365 CheckLValueToRValueCast(CO->getFalseExpr());
1366 return;
1367 }
1368
1369 if (BinaryConditionalOperator *BCO =
1370 dyn_cast<BinaryConditionalOperator>(E)) {
1371 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1372 CheckLValueToRValueCast(BCO->getFalseExpr());
1373 return;
1374 }
1375
1376 Visit(E);
1377 }
1378
1379 void VisitDeclRefExpr(DeclRefExpr *E) {
1380 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1381 if (Decls.count(VD))
1382 FoundDecl = true;
1383 }
1384
1385 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001386
1387 }; // end class DeclMatcher
1388
1389 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1390 Expr *Third, Stmt *Body) {
1391 // Condition is empty
1392 if (!Second) return;
1393
1394 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1395 Second->getLocStart())
1396 == DiagnosticsEngine::Ignored)
1397 return;
1398
1399 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1400 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001401 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001402 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001403 DE.Visit(Second);
1404
1405 // Don't analyze complex conditionals.
1406 if (!DE.isSimple()) return;
1407
1408 // No decls found.
1409 if (Decls.size() == 0) return;
1410
Richard Trieu0030f1d2012-05-04 03:01:54 +00001411 // Don't warn on volatile, static, or global variables.
Richard Trieu451a5db2012-04-30 18:01:30 +00001412 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1413 E = Decls.end();
1414 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001415 if ((*I)->getType().isVolatileQualified() ||
1416 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001417
1418 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1419 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1420 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1421 return;
1422
1423 // Load decl names into diagnostic.
1424 if (Decls.size() > 4)
1425 PDiag << 0;
1426 else {
1427 PDiag << Decls.size();
1428 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1429 E = Decls.end();
1430 I != E; ++I)
1431 PDiag << (*I)->getDeclName();
1432 }
1433
1434 // Load SourceRanges into diagnostic if there is room.
1435 // Otherwise, load the SourceRange of the conditional expression.
1436 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001437 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001438 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001439 I != E; ++I)
1440 PDiag << *I;
1441 else
1442 PDiag << Second->getSourceRange();
1443
1444 S.Diag(Ranges.begin()->getBegin(), PDiag);
1445 }
1446
Richard Trieu4e7c9622013-08-06 21:31:54 +00001447 // If Statement is an incemement or decrement, return true and sets the
1448 // variables Increment and DRE.
1449 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1450 DeclRefExpr *&DRE) {
1451 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1452 switch (UO->getOpcode()) {
1453 default: return false;
1454 case UO_PostInc:
1455 case UO_PreInc:
1456 Increment = true;
1457 break;
1458 case UO_PostDec:
1459 case UO_PreDec:
1460 Increment = false;
1461 break;
1462 }
1463 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1464 return DRE;
1465 }
1466
1467 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1468 FunctionDecl *FD = Call->getDirectCallee();
1469 if (!FD || !FD->isOverloadedOperator()) return false;
1470 switch (FD->getOverloadedOperator()) {
1471 default: return false;
1472 case OO_PlusPlus:
1473 Increment = true;
1474 break;
1475 case OO_MinusMinus:
1476 Increment = false;
1477 break;
1478 }
1479 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1480 return DRE;
1481 }
1482
1483 return false;
1484 }
1485
Serge Pavlov09f99242014-01-23 15:05:00 +00001486 // A visitor to determine if a continue or break statement is a
1487 // subexpression.
1488 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1489 SourceLocation BreakLoc;
1490 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001491 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001492 BreakContinueFinder(Sema &S, Stmt* Body) :
1493 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001494 Visit(Body);
1495 }
1496
Serge Pavlov09f99242014-01-23 15:05:00 +00001497 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001498
1499 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001500 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001501 }
1502
Serge Pavlov09f99242014-01-23 15:05:00 +00001503 void VisitBreakStmt(BreakStmt* E) {
1504 BreakLoc = E->getBreakLoc();
1505 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001506
Serge Pavlov09f99242014-01-23 15:05:00 +00001507 bool ContinueFound() { return ContinueLoc.isValid(); }
1508 bool BreakFound() { return BreakLoc.isValid(); }
1509 SourceLocation GetContinueLoc() { return ContinueLoc; }
1510 SourceLocation GetBreakLoc() { return BreakLoc; }
1511
1512 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001513
1514 // Emit a warning when a loop increment/decrement appears twice per loop
1515 // iteration. The conditions which trigger this warning are:
1516 // 1) The last statement in the loop body and the third expression in the
1517 // for loop are both increment or both decrement of the same variable
1518 // 2) No continue statements in the loop body.
1519 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1520 // Return when there is nothing to check.
1521 if (!Body || !Third) return;
1522
1523 if (S.Diags.getDiagnosticLevel(diag::warn_redundant_loop_iteration,
1524 Third->getLocStart())
1525 == DiagnosticsEngine::Ignored)
1526 return;
1527
1528 // Get the last statement from the loop body.
1529 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1530 if (!CS || CS->body_empty()) return;
1531 Stmt *LastStmt = CS->body_back();
1532 if (!LastStmt) return;
1533
1534 bool LoopIncrement, LastIncrement;
1535 DeclRefExpr *LoopDRE, *LastDRE;
1536
1537 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1538 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1539
1540 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001541 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001542 if (LoopIncrement != LastIncrement ||
1543 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1544
Serge Pavlov09f99242014-01-23 15:05:00 +00001545 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001546
1547 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1548 << LastDRE->getDecl() << LastIncrement;
1549 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1550 << LoopIncrement;
1551 }
1552
Richard Trieu451a5db2012-04-30 18:01:30 +00001553} // end namespace
1554
Serge Pavlov09f99242014-01-23 15:05:00 +00001555
1556void Sema::CheckBreakContinueBinding(Expr *E) {
1557 if (!E || getLangOpts().CPlusPlus)
1558 return;
1559 BreakContinueFinder BCFinder(*this, E);
1560 Scope *BreakParent = CurScope->getBreakParent();
1561 if (BCFinder.BreakFound() && BreakParent) {
1562 if (BreakParent->getFlags() & Scope::SwitchScope) {
1563 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1564 } else {
1565 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1566 << "break";
1567 }
1568 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1569 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1570 << "continue";
1571 }
1572}
1573
John McCalldadc5752010-08-24 06:29:42 +00001574StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001575Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001576 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001577 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001578 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001579 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001580 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001581 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1582 // declare identifiers for objects having storage class 'auto' or
1583 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001584 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1585 DI!=DE; ++DI) {
1586 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001587 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001588 VD = 0;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001589 if (VD == 0) {
1590 Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
1591 (*DI)->setInvalidDecl();
1592 }
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());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001604 VarDecl *ConditionVar = 0;
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
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001612 Expr *Third = third.release().takeAs<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
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621 return Owned(new (Context) ForStmt(Context, First,
1622 SecondResult.take(), ConditionVar,
1623 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001624 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001625}
1626
John McCall34376a62010-12-04 03:47:34 +00001627/// In an Objective C collection iteration statement:
1628/// for (x in y)
1629/// x can be an arbitrary l-value expression. Bind it up as a
1630/// full-expression.
1631StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001632 // Reduce placeholder expressions here. Note that this rejects the
1633 // use of pseudo-object l-values in this position.
1634 ExprResult result = CheckPlaceholderExpr(E);
1635 if (result.isInvalid()) return StmtError();
1636 E = result.take();
1637
Richard Smith945f8d32013-01-14 22:39:08 +00001638 ExprResult FullExpr = ActOnFinishFullExpr(E);
1639 if (FullExpr.isInvalid())
1640 return StmtError();
1641 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCall34376a62010-12-04 03:47:34 +00001642}
1643
John McCall53848232011-07-27 01:07:15 +00001644ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001645Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1646 if (!collection)
1647 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001648
John McCall53848232011-07-27 01:07:15 +00001649 // Bail out early if we've got a type-dependent expression.
1650 if (collection->isTypeDependent()) return Owned(collection);
1651
1652 // Perform normal l-value conversion.
1653 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1654 if (result.isInvalid())
1655 return ExprError();
1656 collection = result.take();
1657
1658 // The operand needs to have object-pointer type.
1659 // TODO: should we do a contextual conversion?
1660 const ObjCObjectPointerType *pointerType =
1661 collection->getType()->getAs<ObjCObjectPointerType>();
1662 if (!pointerType)
1663 return Diag(forLoc, diag::err_collection_expr_type)
1664 << collection->getType() << collection->getSourceRange();
1665
1666 // Check that the operand provides
1667 // - countByEnumeratingWithState:objects:count:
1668 const ObjCObjectType *objectType = pointerType->getObjectType();
1669 ObjCInterfaceDecl *iface = objectType->getInterface();
1670
1671 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001672 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001673 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001674 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001675 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001676 ? diag::err_arc_collection_forward
1677 : 0,
1678 collection)) {
John McCall53848232011-07-27 01:07:15 +00001679 // Otherwise, if we have any useful type information, check that
1680 // the type declares the appropriate method.
1681 } else if (iface || !objectType->qual_empty()) {
1682 IdentifierInfo *selectorIdents[] = {
1683 &Context.Idents.get("countByEnumeratingWithState"),
1684 &Context.Idents.get("objects"),
1685 &Context.Idents.get("count")
1686 };
1687 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1688
1689 ObjCMethodDecl *method = 0;
1690
1691 // If there's an interface, look in both the public and private APIs.
1692 if (iface) {
1693 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001694 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001695 }
1696
1697 // Also check protocol qualifiers.
1698 if (!method)
1699 method = LookupMethodInQualifiedType(selector, pointerType,
1700 /*instance*/ true);
1701
1702 // If we didn't find it anywhere, give up.
1703 if (!method) {
1704 Diag(forLoc, diag::warn_collection_expr_type)
1705 << collection->getType() << selector << collection->getSourceRange();
1706 }
1707
1708 // TODO: check for an incompatible signature?
1709 }
1710
1711 // Wrap up any cleanups in the expression.
Richard Smith945f8d32013-01-14 22:39:08 +00001712 return Owned(collection);
John McCall53848232011-07-27 01:07:15 +00001713}
1714
John McCalldadc5752010-08-24 06:29:42 +00001715StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001716Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001717 Stmt *First, Expr *collection,
1718 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001719
1720 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001721 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001722
Fariborz Jahanian93977672008-01-10 20:33:58 +00001723 if (First) {
1724 QualType FirstType;
1725 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001726 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001727 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1728 diag::err_toomany_element_decls));
1729
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001730 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1731 if (!D || D->isInvalidDecl())
1732 return StmtError();
1733
John McCall31168b02011-06-15 23:02:42 +00001734 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001735 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1736 // declare identifiers for objects having storage class 'auto' or
1737 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001738 if (!D->hasLocalStorage())
1739 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001740 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001741
1742 // If the type contained 'auto', deduce the 'auto' to 'id'.
1743 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001744 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1745 VK_RValue);
1746 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001747 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1748 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001749 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001750 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001751 D->setInvalidDecl();
1752 return StmtError();
1753 }
1754
Richard Smith061f1e22013-04-30 21:23:01 +00001755 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001756
1757 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001758 SourceLocation Loc =
1759 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001760 Diag(Loc, diag::warn_auto_var_is_id)
1761 << D->getDeclName();
1762 }
1763 }
1764
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001765 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001766 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001767 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001768 return StmtError(Diag(First->getLocStart(),
1769 diag::err_selector_element_not_lvalue)
1770 << First->getSourceRange());
1771
Mike Stump11289f42009-09-09 15:08:12 +00001772 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001773 if (FirstType.isConstQualified())
1774 Diag(ForLoc, diag::err_selector_element_const_type)
1775 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001776 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001777 if (!FirstType->isDependentType() &&
1778 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001779 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001780 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1781 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001782 }
Chad Rosier02a84392012-08-10 17:56:09 +00001783
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001784 if (CollectionExprResult.isInvalid())
1785 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001786
Richard Smith945f8d32013-01-14 22:39:08 +00001787 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1788 if (CollectionExprResult.isInvalid())
1789 return StmtError();
1790
Chad Rosier02a84392012-08-10 17:56:09 +00001791 return Owned(new (Context) ObjCForCollectionStmt(First,
1792 CollectionExprResult.take(), 0,
Ted Kremenek5a201952009-02-07 01:47:29 +00001793 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001794}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001795
Richard Smith02e85f32011-04-14 22:09:26 +00001796/// Finish building a variable declaration for a for-range statement.
1797/// \return true if an error occurs.
1798static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001799 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001800 // Deduce the type for the iterator variable now rather than leaving it to
1801 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001802 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001803 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001804 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001805 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001806 SemaRef.Diag(Loc, DiagID) << Init->getType();
1807 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001808 Decl->setInvalidDecl();
1809 return true;
1810 }
Richard Smith061f1e22013-04-30 21:23:01 +00001811 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001812
John McCall31168b02011-06-15 23:02:42 +00001813 // In ARC, infer lifetime.
1814 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1815 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001816 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001817 SemaRef.inferObjCARCLifetime(Decl))
1818 Decl->setInvalidDecl();
1819
Richard Smith02e85f32011-04-14 22:09:26 +00001820 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1821 /*TypeMayContainAuto=*/false);
1822 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001823 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001824 return false;
1825}
1826
Sam Panzer0f384432012-08-21 00:52:01 +00001827namespace {
1828
Richard Smith02e85f32011-04-14 22:09:26 +00001829/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001830/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001831/// nor from the diagnostics produced when analysing the implicit expressions
1832/// required in a for-range statement.
1833void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001834 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001835 CallExpr *CE = dyn_cast<CallExpr>(E);
1836 if (!CE)
1837 return;
1838 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1839 if (!D)
1840 return;
1841 SourceLocation Loc = D->getLocation();
1842
1843 std::string Description;
1844 bool IsTemplate = false;
1845 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1846 Description = SemaRef.getTemplateArgumentBindingsText(
1847 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1848 IsTemplate = true;
1849 }
1850
1851 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1852 << BEF << IsTemplate << Description << E->getType();
1853}
1854
Sam Panzer0f384432012-08-21 00:52:01 +00001855/// Build a variable declaration for a for-range statement.
1856VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1857 QualType Type, const char *Name) {
1858 DeclContext *DC = SemaRef.CurContext;
1859 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1860 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1861 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001862 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001863 Decl->setImplicit();
1864 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001865}
1866
1867}
1868
Fariborz Jahanian00213472012-07-06 19:04:04 +00001869static bool ObjCEnumerationCollection(Expr *Collection) {
1870 return !Collection->isTypeDependent()
1871 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1872}
1873
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001874/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001875///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001876/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001877/// A range-based for statement is equivalent to
1878///
1879/// {
1880/// auto && __range = range-init;
1881/// for ( auto __begin = begin-expr,
1882/// __end = end-expr;
1883/// __begin != __end;
1884/// ++__begin ) {
1885/// for-range-declaration = *__begin;
1886/// statement
1887/// }
1888/// }
1889///
1890/// The body of the loop is not available yet, since it cannot be analysed until
1891/// we have determined the type of the for-range-declaration.
1892StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001893Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001894 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001895 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001896 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001897 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001898
Richard Smith3249fed2013-08-21 01:40:36 +00001899 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001900 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001901
1902 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1903 assert(DS && "first part of for range not a decl stmt");
1904
1905 if (!DS->isSingleDecl()) {
1906 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1907 return StmtError();
1908 }
Richard Smith02e85f32011-04-14 22:09:26 +00001909
Richard Smith3249fed2013-08-21 01:40:36 +00001910 Decl *LoopVar = DS->getSingleDecl();
1911 if (LoopVar->isInvalidDecl() || !Range ||
1912 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1913 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001914 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001915 }
Richard Smith02e85f32011-04-14 22:09:26 +00001916
1917 // Build auto && __range = range-init
1918 SourceLocation RangeLoc = Range->getLocStart();
1919 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1920 Context.getAutoRRefDeductType(),
1921 "__range");
1922 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001923 diag::err_for_range_deduction_failure)) {
1924 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001925 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001926 }
Richard Smith02e85f32011-04-14 22:09:26 +00001927
1928 // Claim the type doesn't contain auto: we've already done the checking.
1929 DeclGroupPtrTy RangeGroup =
Rafael Espindolaab417692013-07-09 12:05:01 +00001930 BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1931 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001932 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001933 if (RangeDecl.isInvalid()) {
1934 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001935 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001936 }
Richard Smith02e85f32011-04-14 22:09:26 +00001937
1938 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1939 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smitha05b3b52012-09-20 21:52:32 +00001940 RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001941}
1942
1943/// \brief Create the initialization, compare, and increment steps for
1944/// the range-based for loop expression.
1945/// This function does not handle array-based for loops,
1946/// which are created in Sema::BuildCXXForRangeStmt.
1947///
1948/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1949/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1950/// CandidateSet and BEF are set and some non-success value is returned on
1951/// failure.
1952static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1953 Expr *BeginRange, Expr *EndRange,
1954 QualType RangeType,
1955 VarDecl *BeginVar,
1956 VarDecl *EndVar,
1957 SourceLocation ColonLoc,
1958 OverloadCandidateSet *CandidateSet,
1959 ExprResult *BeginExpr,
1960 ExprResult *EndExpr,
1961 Sema::BeginEndFunction *BEF) {
1962 DeclarationNameInfo BeginNameInfo(
1963 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1964 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1965 ColonLoc);
1966
1967 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1968 Sema::LookupMemberName);
1969 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1970
1971 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1972 // - if _RangeT is a class type, the unqualified-ids begin and end are
1973 // looked up in the scope of class _RangeT as if by class member access
1974 // lookup (3.4.5), and if either (or both) finds at least one
1975 // declaration, begin-expr and end-expr are __range.begin() and
1976 // __range.end(), respectively;
1977 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1978 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1979
1980 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1981 SourceLocation RangeLoc = BeginVar->getLocation();
1982 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1983
1984 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1985 << RangeLoc << BeginRange->getType() << *BEF;
1986 return Sema::FRS_DiagnosticIssued;
1987 }
1988 } else {
1989 // - otherwise, begin-expr and end-expr are begin(__range) and
1990 // end(__range), respectively, where begin and end are looked up with
1991 // argument-dependent lookup (3.4.2). For the purposes of this name
1992 // lookup, namespace std is an associated namespace.
1993
1994 }
1995
1996 *BEF = Sema::BEF_begin;
1997 Sema::ForRangeStatus RangeStatus =
1998 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1999 Sema::BEF_begin, BeginNameInfo,
2000 BeginMemberLookup, CandidateSet,
2001 BeginRange, BeginExpr);
2002
2003 if (RangeStatus != Sema::FRS_Success)
2004 return RangeStatus;
2005 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2006 diag::err_for_range_iter_deduction_failure)) {
2007 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2008 return Sema::FRS_DiagnosticIssued;
2009 }
2010
2011 *BEF = Sema::BEF_end;
2012 RangeStatus =
2013 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2014 Sema::BEF_end, EndNameInfo,
2015 EndMemberLookup, CandidateSet,
2016 EndRange, EndExpr);
2017 if (RangeStatus != Sema::FRS_Success)
2018 return RangeStatus;
2019 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2020 diag::err_for_range_iter_deduction_failure)) {
2021 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2022 return Sema::FRS_DiagnosticIssued;
2023 }
2024 return Sema::FRS_Success;
2025}
2026
2027/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002028/// If the attempt fails, this function will return a valid, null StmtResult
2029/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002030static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2031 SourceLocation ForLoc,
2032 Stmt *LoopVarDecl,
2033 SourceLocation ColonLoc,
2034 Expr *Range,
2035 SourceLocation RangeLoc,
2036 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002037 // Determine whether we can rebuild the for-range statement with a
2038 // dereferenced range expression.
2039 ExprResult AdjustedRange;
2040 {
2041 Sema::SFINAETrap Trap(SemaRef);
2042
2043 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2044 if (AdjustedRange.isInvalid())
2045 return StmtResult();
2046
2047 StmtResult SR =
2048 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2049 AdjustedRange.get(), RParenLoc,
2050 Sema::BFRK_Check);
2051 if (SR.isInvalid())
2052 return StmtResult();
2053 }
2054
2055 // The attempt to dereference worked well enough that it could produce a valid
2056 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2057 // case there are any other (non-fatal) problems with it.
2058 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2059 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2060 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2061 AdjustedRange.get(), RParenLoc,
2062 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002063}
2064
Richard Smith3249fed2013-08-21 01:40:36 +00002065namespace {
2066/// RAII object to automatically invalidate a declaration if an error occurs.
2067struct InvalidateOnErrorScope {
2068 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2069 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2070 ~InvalidateOnErrorScope() {
2071 if (Enabled && Trap.hasErrorOccurred())
2072 D->setInvalidDecl();
2073 }
2074
2075 DiagnosticErrorTrap Trap;
2076 Decl *D;
2077 bool Enabled;
2078};
2079}
2080
Richard Smitha05b3b52012-09-20 21:52:32 +00002081/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002082StmtResult
2083Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2084 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2085 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002086 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002087 Scope *S = getCurScope();
2088
2089 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2090 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2091 QualType RangeVarType = RangeVar->getType();
2092
2093 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2094 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2095
Richard Smith3249fed2013-08-21 01:40:36 +00002096 // If we hit any errors, mark the loop variable as invalid if its type
2097 // contains 'auto'.
2098 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2099 LoopVar->getType()->isUndeducedType());
2100
Richard Smith02e85f32011-04-14 22:09:26 +00002101 StmtResult BeginEndDecl = BeginEnd;
2102 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2103
Richard Smith27d807c2013-04-30 13:56:41 +00002104 if (RangeVarType->isDependentType()) {
2105 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002106 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002107
2108 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2109 // them in properly when we instantiate the loop.
2110 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2111 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2112 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002113 SourceLocation RangeLoc = RangeVar->getLocation();
2114
Ted Kremenekbed648e2011-10-10 22:36:28 +00002115 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2116
2117 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2118 VK_LValue, ColonLoc);
2119 if (BeginRangeRef.isInvalid())
2120 return StmtError();
2121
2122 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2123 VK_LValue, ColonLoc);
2124 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002125 return StmtError();
2126
2127 QualType AutoType = Context.getAutoDeductType();
2128 Expr *Range = RangeVar->getInit();
2129 if (!Range)
2130 return StmtError();
2131 QualType RangeType = Range->getType();
2132
2133 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002134 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002135 return StmtError();
2136
2137 // Build auto __begin = begin-expr, __end = end-expr.
2138 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2139 "__begin");
2140 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2141 "__end");
2142
2143 // Build begin-expr and end-expr and attach to __begin and __end variables.
2144 ExprResult BeginExpr, EndExpr;
2145 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2146 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2147 // __range + __bound, respectively, where __bound is the array bound. If
2148 // _RangeT is an array of unknown size or an array of incomplete type,
2149 // the program is ill-formed;
2150
2151 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002152 BeginExpr = BeginRangeRef;
2153 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002154 diag::err_for_range_iter_deduction_failure)) {
2155 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2156 return StmtError();
2157 }
2158
2159 // Find the array bound.
2160 ExprResult BoundExpr;
2161 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2162 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00002163 Context.getPointerDiffType(),
2164 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00002165 else if (const VariableArrayType *VAT =
2166 dyn_cast<VariableArrayType>(UnqAT))
2167 BoundExpr = VAT->getSizeExpr();
2168 else {
2169 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2170 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002171 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002172 }
2173
2174 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002175 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002176 BoundExpr.get());
2177 if (EndExpr.isInvalid())
2178 return StmtError();
2179 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2180 diag::err_for_range_iter_deduction_failure)) {
2181 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2182 return StmtError();
2183 }
2184 } else {
Sam Panzer0f384432012-08-21 00:52:01 +00002185 OverloadCandidateSet CandidateSet(RangeLoc);
2186 Sema::BeginEndFunction BEFFailure;
2187 ForRangeStatus RangeStatus =
2188 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2189 EndRangeRef.get(), RangeType,
2190 BeginVar, EndVar, ColonLoc, &CandidateSet,
2191 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002192
Richard Smitha05b3b52012-09-20 21:52:32 +00002193 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002194 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002195 // If the range is being built from an array parameter, emit a
2196 // a diagnostic that it is being treated as a pointer.
2197 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2198 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2199 QualType ArrayTy = PVD->getOriginalType();
2200 QualType PointerTy = PVD->getType();
2201 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2202 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2203 << RangeLoc << PVD << ArrayTy << PointerTy;
2204 Diag(PVD->getLocation(), diag::note_declared_at);
2205 return StmtError();
2206 }
2207 }
2208 }
2209
2210 // If building the range failed, try dereferencing the range expression
2211 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002212 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2213 LoopVarDecl, ColonLoc,
2214 Range, RangeLoc,
2215 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002216 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002217 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002218 }
2219
Sam Panzer0f384432012-08-21 00:52:01 +00002220 // Otherwise, emit diagnostics if we haven't already.
2221 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002222 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002223 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2224 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002225 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002226 }
2227 // Return an error if no fix was discovered.
2228 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002229 return StmtError();
2230 }
2231
Sam Panzer0f384432012-08-21 00:52:01 +00002232 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2233 "invalid range expression in for loop");
2234
2235 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002236 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2237 if (!Context.hasSameType(BeginType, EndType)) {
2238 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2239 << BeginType << EndType;
2240 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2241 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2242 }
2243
2244 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2245 // Claim the type doesn't contain auto: we've already done the checking.
2246 DeclGroupPtrTy BeginEndGroup =
Rafael Espindolaab417692013-07-09 12:05:01 +00002247 BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>(BeginEndDecls, 2),
2248 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002249 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2250
Ted Kremenekbed648e2011-10-10 22:36:28 +00002251 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2252 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002253 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002254 if (BeginRef.isInvalid())
2255 return StmtError();
2256
Richard Smith02e85f32011-04-14 22:09:26 +00002257 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2258 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002259 if (EndRef.isInvalid())
2260 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002261
2262 // Build and check __begin != __end expression.
2263 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2264 BeginRef.get(), EndRef.get());
2265 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2266 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2267 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002268 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2269 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002270 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2271 if (!Context.hasSameType(BeginType, EndType))
2272 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2273 return StmtError();
2274 }
2275
2276 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002277 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2278 VK_LValue, ColonLoc);
2279 if (BeginRef.isInvalid())
2280 return StmtError();
2281
Richard Smith02e85f32011-04-14 22:09:26 +00002282 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2283 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2284 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002285 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2286 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002287 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2288 return StmtError();
2289 }
2290
2291 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002292 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2293 VK_LValue, ColonLoc);
2294 if (BeginRef.isInvalid())
2295 return StmtError();
2296
Richard Smith02e85f32011-04-14 22:09:26 +00002297 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2298 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002299 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2300 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002301 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2302 return StmtError();
2303 }
2304
Richard Smitha05b3b52012-09-20 21:52:32 +00002305 // Attach *__begin as initializer for VD. Don't touch it if we're just
2306 // trying to determine whether this would be a valid range.
2307 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002308 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2309 /*TypeMayContainAuto=*/true);
2310 if (LoopVar->isInvalidDecl())
2311 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2312 }
2313 }
2314
Richard Smitha05b3b52012-09-20 21:52:32 +00002315 // Don't bother to actually allocate the result if we're just trying to
2316 // determine whether it would be valid.
2317 if (Kind == BFRK_Check)
2318 return StmtResult();
2319
Richard Smith02e85f32011-04-14 22:09:26 +00002320 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2321 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2322 NotEqExpr.take(), IncrExpr.take(),
2323 LoopVarDS, /*Body=*/0, ForLoc,
2324 ColonLoc, RParenLoc));
2325}
2326
Chad Rosier02a84392012-08-10 17:56:09 +00002327/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002328/// statement.
2329StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2330 if (!S || !B)
2331 return StmtError();
2332 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002333
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002334 ForStmt->setBody(B);
2335 return S;
2336}
2337
Richard Smith02e85f32011-04-14 22:09:26 +00002338/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2339/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2340/// body cannot be performed until after the type of the range variable is
2341/// determined.
2342StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2343 if (!S || !B)
2344 return StmtError();
2345
Fariborz Jahanian00213472012-07-06 19:04:04 +00002346 if (isa<ObjCForCollectionStmt>(S))
2347 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002348
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002349 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2350 ForStmt->setBody(B);
2351
2352 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2353 diag::warn_empty_range_based_for_body);
2354
Richard Smith02e85f32011-04-14 22:09:26 +00002355 return S;
2356}
2357
Chris Lattnercab02a62011-02-17 20:34:02 +00002358StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2359 SourceLocation LabelLoc,
2360 LabelDecl *TheDecl) {
2361 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002362 TheDecl->markUsed(Context);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002363 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002364}
Chris Lattner1c310502007-05-31 06:00:00 +00002365
John McCalldadc5752010-08-24 06:29:42 +00002366StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002367Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002368 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002369 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002370 if (!E->isTypeDependent()) {
2371 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002372 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00002373 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00002374 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002375 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2376 if (ExprRes.isInvalid())
2377 return StmtError();
2378 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00002379 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002380 return StmtError();
2381 }
John McCalla95172b2010-08-01 00:26:45 +00002382
Richard Smith945f8d32013-01-14 22:39:08 +00002383 ExprResult ExprRes = ActOnFinishFullExpr(E);
2384 if (ExprRes.isInvalid())
2385 return StmtError();
2386 E = ExprRes.take();
2387
John McCallaab3e412010-08-25 08:40:02 +00002388 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002389
Douglas Gregor30776d42009-05-16 00:20:29 +00002390 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002391}
2392
John McCalldadc5752010-08-24 06:29:42 +00002393StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002394Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002395 Scope *S = CurScope->getContinueParent();
2396 if (!S) {
2397 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002398 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002399 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002400
Ted Kremenek5a201952009-02-07 01:47:29 +00002401 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002402}
2403
John McCalldadc5752010-08-24 06:29:42 +00002404StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002405Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002406 Scope *S = CurScope->getBreakParent();
2407 if (!S) {
2408 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002409 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002410 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002411
Ted Kremenek5a201952009-02-07 01:47:29 +00002412 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002413}
2414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002415/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002416/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002417///
Douglas Gregor5d369002011-01-21 18:05:27 +00002418/// \param ReturnType If we're determining the copy elision candidate for
2419/// a return statement, this is the return type of the function. If we're
2420/// determining the copy elision candidate for a throw expression, this will
2421/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002422///
Douglas Gregor5d369002011-01-21 18:05:27 +00002423/// \param E The expression being returned from the function or block, or
2424/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002425///
Douglas Gregor86394412011-05-20 15:00:53 +00002426/// \param AllowFunctionParameter Whether we allow function parameters to
2427/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2428/// we re-use this logic to determine whether we should try to move as part of
2429/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002430///
2431/// \returns The NRVO candidate variable, if the return statement may use the
2432/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00002433const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2434 Expr *E,
2435 bool AllowFunctionParameter) {
2436 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002437 // - in a return statement in a function with ...
2438 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00002439 if (!ReturnType.isNull()) {
2440 if (!ReturnType->isRecordType())
2441 return 0;
2442 // ... the same cv-unqualified type as the function return type ...
2443 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2444 return 0;
2445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002446
2447 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00002448 // (other than a function or catch-clause parameter)) ...
2449 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber13253842012-07-11 22:50:15 +00002450 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002451 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002452 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2453 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002454 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455
John McCall03318c12011-11-11 03:57:31 +00002456 // ...object (other than a function or catch-clause parameter)...
2457 if (VD->getKind() != Decl::Var &&
2458 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2459 return 0;
2460 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002461
John McCall03318c12011-11-11 03:57:31 +00002462 // ...automatic...
2463 if (!VD->hasLocalStorage()) return 0;
2464
2465 // ...non-volatile...
2466 if (VD->getType().isVolatileQualified()) return 0;
2467 if (VD->getType()->isReferenceType()) return 0;
2468
2469 // __block variables can't be allocated in a way that permits NRVO.
2470 if (VD->hasAttr<BlocksAttr>()) return 0;
2471
2472 // Variables with higher required alignment than their type's ABI
2473 // alignment cannot use NRVO.
2474 if (VD->hasAttr<AlignedAttr>() &&
2475 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2476 return 0;
2477
2478 return VD;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002479}
2480
Douglas Gregor626fbed2011-01-21 21:08:57 +00002481/// \brief Perform the initialization of a potentially-movable value, which
2482/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002483///
2484/// This routine implements C++0x [class.copy]p33, which attempts to treat
2485/// returned lvalues as rvalues in certain cases (to prefer move construction),
2486/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002487ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002488Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2489 const VarDecl *NRVOCandidate,
2490 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002491 Expr *Value,
2492 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002493 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002494 // When the criteria for elision of a copy operation are met or would
2495 // be met save for the fact that the source object is a function
2496 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002497 // overload resolution to select the constructor for the copy is first
2498 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002499 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002500 if (AllowNRVO &&
2501 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002502 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002503 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002504
Douglas Gregorf282a762011-01-21 19:38:21 +00002505 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002507 = InitializationKind::CreateCopy(Value->getLocStart(),
2508 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002509 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002510
2511 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002512 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002513 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002514 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002515 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002516 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2517 StepEnd = Seq.step_end();
2518 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002519 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002520 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002521
2522 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002523 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524
Douglas Gregorf282a762011-01-21 19:38:21 +00002525 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002526 = Constructor->getParamDecl(0)->getType()
2527 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002528
Douglas Gregorf282a762011-01-21 19:38:21 +00002529 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002531 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2532 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002533 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534
Douglas Gregorf282a762011-01-21 19:38:21 +00002535 // Promote "AsRvalue" to the heap, since we now need this
2536 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002537 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002538 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
Douglas Gregorf282a762011-01-21 19:38:21 +00002540 // Complete type-checking the initialization of the return type
2541 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002542 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002543 }
2544 }
2545 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002546
Douglas Gregorf282a762011-01-21 19:38:21 +00002547 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002549 // (again) now with the return value expression as written.
2550 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002551 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552
Douglas Gregorf282a762011-01-21 19:38:21 +00002553 return Res;
2554}
2555
Richard Smith4db51c22013-09-25 05:02:54 +00002556/// \brief Determine whether the declared return type of the specified function
2557/// contains 'auto'.
2558static bool hasDeducedReturnType(FunctionDecl *FD) {
2559 const FunctionProtoType *FPT =
2560 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002561 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002562}
2563
Eli Friedman34b49062012-01-26 03:00:14 +00002564/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2565/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002566///
John McCalldadc5752010-08-24 06:29:42 +00002567StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002568Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2569 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002570 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002571 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002572 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002573 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002574
Richard Smith4db51c22013-09-25 05:02:54 +00002575 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2576 // In C++1y, the return type may involve 'auto'.
2577 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2578 FunctionDecl *FD = CurLambda->CallOperator;
2579 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002580 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002581
2582 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2583 assert(AT && "lost auto type from lambda return type");
2584 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2585 FD->setInvalidDecl();
2586 return StmtError();
2587 }
Alp Toker314cc812014-01-25 16:55:45 +00002588 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002589 } else if (CurCap->HasImplicitReturnType) {
2590 // For blocks/lambdas with implicit return types, we check each return
2591 // statement individually, and deduce the common return type when the block
2592 // or lambda is completed.
2593 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002594 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002595 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2596 if (Result.isInvalid())
2597 return StmtError();
2598 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002599
Richard Smith4db51c22013-09-25 05:02:54 +00002600 if (!CurContext->isDependentContext())
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002601 FnRetType = RetValExp->getType();
Richard Smith4db51c22013-09-25 05:02:54 +00002602 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002603 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002604 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002605 if (RetValExp) {
2606 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2607 // initializer list, because it is not an expression (even
2608 // though we represent it as one). We still deduce 'void'.
2609 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2610 << RetValExp->getSourceRange();
2611 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002612
Jordan Rosed39e5f12012-07-02 21:19:23 +00002613 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002614 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002615
2616 // Although we'll properly infer the type of the block once it's completed,
2617 // make sure we provide a return type now for better error recovery.
2618 if (CurCap->ReturnType.isNull())
2619 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002620 }
Eli Friedman34b49062012-01-26 03:00:14 +00002621 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002622
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002623 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002624 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2625 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2626 return StmtError();
2627 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002628 } else if (CapturedRegionScopeInfo *CurRegion =
2629 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2630 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2631 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002632 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002633 assert(CurLambda && "unknown kind of captured scope");
2634 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2635 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002636 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2637 return StmtError();
2638 }
2639 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002640
Steve Naroffc540d662008-09-03 18:15:37 +00002641 // Otherwise, verify that this result type matches the previous one. We are
2642 // pickier with blocks than for normal functions because we don't have GCC
2643 // compatibility to worry about here.
John McCall75f92b52011-08-17 21:34:14 +00002644 const VarDecl *NRVOCandidate = 0;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002645 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002646 // Delay processing for now. TODO: there are lots of dependent
2647 // types we can conclusively prove aren't void.
2648 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002649 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002650 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002651 (RetValExp->isTypeDependent() ||
2652 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002653 if (!getLangOpts().CPlusPlus &&
2654 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002655 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002656 else {
2657 Diag(ReturnLoc, diag::err_return_block_has_expr);
2658 RetValExp = 0;
2659 }
Steve Naroffc540d662008-09-03 18:15:37 +00002660 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002661 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002662 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2663 } else if (!RetValExp->isTypeDependent()) {
2664 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002665
John McCall5500ef22011-08-17 22:09:46 +00002666 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2667 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2668 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002669
John McCall5500ef22011-08-17 22:09:46 +00002670 // In C++ the return statement is handled via a copy initialization.
2671 // the C version of which boils down to CheckSingleAssignmentConstraints.
2672 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2673 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2674 FnRetType,
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00002675 NRVOCandidate != 0);
John McCall5500ef22011-08-17 22:09:46 +00002676 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2677 FnRetType, RetValExp);
2678 if (Res.isInvalid()) {
2679 // FIXME: Cleanup temporaries here, anyway?
2680 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002681 }
John McCall5500ef22011-08-17 22:09:46 +00002682 RetValExp = Res.take();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002683 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +00002684 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002685
John McCall75f92b52011-08-17 21:34:14 +00002686 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002687 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2688 if (ER.isInvalid())
2689 return StmtError();
2690 RetValExp = ER.take();
John McCall75f92b52011-08-17 21:34:14 +00002691 }
John McCall5500ef22011-08-17 22:09:46 +00002692 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2693 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002694
Jordan Rosed39e5f12012-07-02 21:19:23 +00002695 // If we need to check for the named return value optimization,
2696 // or if we need to infer the return type,
2697 // save the return statement in our scope for later processing.
2698 if (CurCap->HasImplicitReturnType ||
2699 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2700 !CurContext->isDependentContext()))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002701 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002703 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00002704}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002705
Richard Smith2a7d4812013-05-04 07:00:32 +00002706/// Deduce the return type for a function from a returned expression, per
2707/// C++1y [dcl.spec.auto]p6.
2708bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2709 SourceLocation ReturnLoc,
2710 Expr *&RetExpr,
2711 AutoType *AT) {
2712 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00002713 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith2a7d4812013-05-04 07:00:32 +00002714 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002715
Richard Smithc58f38f2013-08-14 20:16:31 +00002716 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2717 // If the deduction is for a return statement and the initializer is
2718 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002719 Diag(RetExpr->getExprLoc(),
2720 getCurLambda() ? diag::err_lambda_return_init_list
2721 : diag::err_auto_fn_return_init_list)
2722 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002723 return true;
2724 }
2725
2726 if (FD->isDependentContext()) {
2727 // C++1y [dcl.spec.auto]p12:
2728 // Return type deduction [...] occurs when the definition is
2729 // instantiated even if the function body contains a return
2730 // statement with a non-type-dependent operand.
2731 assert(AT->isDeduced() && "should have deduced to dependent type");
2732 return false;
2733 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002734 // If the deduction is for a return statement and the initializer is
2735 // a braced-init-list, the program is ill-formed.
2736 if (isa<InitListExpr>(RetExpr)) {
2737 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2738 return true;
2739 }
2740
2741 // Otherwise, [...] deduce a value for U using the rules of template
2742 // argument deduction.
2743 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2744
2745 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2746 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2747 << OrigResultType.getType() << RetExpr->getType();
2748
2749 if (DAR != DAR_Succeeded)
2750 return true;
2751 } else {
2752 // In the case of a return with no operand, the initializer is considered
2753 // to be void().
2754 //
2755 // Deduction here can only succeed if the return type is exactly 'cv auto'
2756 // or 'decltype(auto)', so just check for that case directly.
2757 if (!OrigResultType.getType()->getAs<AutoType>()) {
2758 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2759 << OrigResultType.getType();
2760 return true;
2761 }
2762 // We always deduce U = void in this case.
2763 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2764 if (Deduced.isNull())
2765 return true;
2766 }
2767
2768 // If a function with a declared return type that contains a placeholder type
2769 // has multiple return statements, the return type is deduced for each return
2770 // statement. [...] if the type deduced is not the same in each deduction,
2771 // the program is ill-formed.
2772 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2773 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002774 if (!FD->isDependentContext() &&
2775 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002776 const LambdaScopeInfo *LambdaSI = getCurLambda();
2777 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2778 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2779 << NewAT->getDeducedType() << AT->getDeducedType()
2780 << true /*IsLambda*/;
2781 } else {
2782 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2783 << (AT->isDecltypeAuto() ? 1 : 0)
2784 << NewAT->getDeducedType() << AT->getDeducedType();
2785 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002786 return true;
2787 }
2788 } else if (!FD->isInvalidDecl()) {
2789 // Update all declarations of the function to have the deduced return type.
2790 Context.adjustDeducedFunctionResultType(FD, Deduced);
2791 }
2792
2793 return false;
2794}
2795
John McCalldadc5752010-08-24 06:29:42 +00002796StmtResult
John McCallb268a282010-08-23 23:25:46 +00002797Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002798 // Check for unexpanded parameter packs.
2799 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2800 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002801
Eli Friedman34b49062012-01-26 03:00:14 +00002802 if (isa<CapturingScopeInfo>(getCurFunction()))
2803 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002804
Chris Lattner79413952008-12-04 23:50:19 +00002805 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002806 QualType RelatedRetType;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002807 const AttrVec *Attrs = 0;
2808 bool isObjCMethod = false;
2809
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002810 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002811 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002812 if (FD->hasAttrs())
2813 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002814 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002815 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002816 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002817 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002818 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002819 isObjCMethod = true;
2820 if (MD->hasAttrs())
2821 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002822 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2823 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002824 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002825 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002826 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2827 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002828 }
2829 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002830 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002831
Richard Smith2a7d4812013-05-04 07:00:32 +00002832 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2833 // deduction.
Richard Smith2a7d4812013-05-04 07:00:32 +00002834 if (getLangOpts().CPlusPlus1y) {
2835 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2836 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002837 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002838 FD->setInvalidDecl();
2839 return StmtError();
2840 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002841 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002842 }
2843 }
2844 }
2845
Richard Smithc58f38f2013-08-14 20:16:31 +00002846 bool HasDependentReturnType = FnRetType->isDependentType();
2847
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002848 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002849 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002850 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002851 if (isa<InitListExpr>(RetValExp)) {
2852 // We simply never allow init lists as the return value of void
2853 // functions. This is compatible because this was never allowed before,
2854 // so there's no legacy code to deal with.
2855 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2856 int FunctionKind = 0;
2857 if (isa<ObjCMethodDecl>(CurDecl))
2858 FunctionKind = 1;
2859 else if (isa<CXXConstructorDecl>(CurDecl))
2860 FunctionKind = 2;
2861 else if (isa<CXXDestructorDecl>(CurDecl))
2862 FunctionKind = 3;
2863
2864 Diag(ReturnLoc, diag::err_return_init_list)
2865 << CurDecl->getDeclName() << FunctionKind
2866 << RetValExp->getSourceRange();
2867
2868 // Drop the expression.
2869 RetValExp = 0;
2870 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002871 // C99 6.8.6.4p1 (ext_ since GCC warns)
2872 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002873 if (RetValExp->getType()->isVoidType()) {
2874 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2875 if (isa<CXXConstructorDecl>(CurDecl) ||
2876 isa<CXXDestructorDecl>(CurDecl))
2877 D = diag::err_ctor_dtor_returns_void;
2878 else
2879 D = diag::ext_return_has_void_expr;
2880 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002881 else {
2882 ExprResult Result = Owned(RetValExp);
2883 Result = IgnoredValueConversions(Result.take());
2884 if (Result.isInvalid())
2885 return StmtError();
2886 RetValExp = Result.take();
2887 RetValExp = ImpCastExprToType(RetValExp,
2888 Context.VoidTy, CK_ToVoid).take();
2889 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002890 // return of void in constructor/destructor is illegal in C++.
2891 if (D == diag::err_ctor_dtor_returns_void) {
2892 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2893 Diag(ReturnLoc, D)
2894 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
2895 << RetValExp->getSourceRange();
2896 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002897 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002898 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002899 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002900 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002901
2902 int FunctionKind = 0;
2903 if (isa<ObjCMethodDecl>(CurDecl))
2904 FunctionKind = 1;
2905 else if (isa<CXXConstructorDecl>(CurDecl))
2906 FunctionKind = 2;
2907 else if (isa<CXXDestructorDecl>(CurDecl))
2908 FunctionKind = 3;
2909
Nick Lewycky1be750a2011-06-01 07:44:31 +00002910 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002911 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002912 << RetValExp->getSourceRange();
2913 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002914 }
Mike Stump11289f42009-09-09 15:08:12 +00002915
Sebastian Redleef474c2012-02-22 10:50:08 +00002916 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002917 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2918 if (ER.isInvalid())
2919 return StmtError();
2920 RetValExp = ER.take();
Sebastian Redleef474c2012-02-22 10:50:08 +00002921 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002924 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
Richard Smith2a7d4812013-05-04 07:00:32 +00002925 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002926 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2927 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002928 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002929
2930 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002931 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002932 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002933 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002934 Result = new (Context) ReturnStmt(ReturnLoc);
2935 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00002936 assert(RetValExp || HasDependentReturnType);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002937 const VarDecl *NRVOCandidate = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00002938 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002939 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002940
John McCall5ec7e7d2013-03-19 07:04:25 +00002941 QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
Eli Friedman410fc7a2012-03-30 01:13:43 +00002942
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002943 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2944 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2945 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002946
John McCallfa272342011-06-16 23:24:51 +00002947 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002948 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00002949 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00002951 RetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00002952 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00002954 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002955 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00002956 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002957 return StmtError();
2958 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002959 RetValExp = Res.takeAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00002960
2961 // If we have a related result type, we need to implicitly
2962 // convert back to the formal result type. We can't pretend to
2963 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002964 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00002965 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002966 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
2967 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00002968 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
2969 if (Res.isInvalid()) {
2970 // FIXME: Clean up temporaries here anyway?
2971 return StmtError();
2972 }
2973 RetValExp = Res.takeAs<Expr>();
2974 }
2975
Artyom Skrobov9f213442014-01-24 11:10:39 +00002976 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
2977 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00002978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979
John McCallacf0ee52010-10-08 02:01:28 +00002980 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002981 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2982 if (ER.isInvalid())
2983 return StmtError();
2984 RetValExp = ER.take();
John McCallacf0ee52010-10-08 02:01:28 +00002985 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002986 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00002987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
2989 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002990 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002991 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002992 !CurContext->isDependentContext())
2993 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00002994
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002995 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002996}
2997
John McCalldadc5752010-08-24 06:29:42 +00002998StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002999Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003000 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003001 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003002 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003003 if (Var && Var->isInvalidDecl())
3004 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005
John McCallb268a282010-08-23 23:25:46 +00003006 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003007}
3008
John McCalldadc5752010-08-24 06:29:42 +00003009StmtResult
John McCallb268a282010-08-23 23:25:46 +00003010Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3011 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003012}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003013
John McCalldadc5752010-08-24 06:29:42 +00003014StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003015Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003016 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003017 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003018 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3019
John McCallaab3e412010-08-25 08:40:02 +00003020 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003021 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00003022 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003023 CatchStmts.data(),
Douglas Gregor96c79492010-04-23 22:50:49 +00003024 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00003025 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003026}
3027
John McCall0bd3e402012-05-08 21:41:25 +00003028StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003029 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003030 ExprResult Result = DefaultLvalueConversion(Throw);
3031 if (Result.isInvalid())
3032 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003033
Richard Smith945f8d32013-01-14 22:39:08 +00003034 Result = ActOnFinishFullExpr(Result.take());
3035 if (Result.isInvalid())
3036 return StmtError();
3037 Throw = Result.take();
3038
Douglas Gregor2900c162010-04-22 21:44:01 +00003039 QualType ThrowType = Throw->getType();
3040 // Make sure the expression type is an ObjC pointer or "void *".
3041 if (!ThrowType->isDependentType() &&
3042 !ThrowType->isObjCObjectPointerType()) {
3043 const PointerType *PT = ThrowType->getAs<PointerType>();
3044 if (!PT || !PT->getPointeeType()->isVoidType())
3045 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3046 << Throw->getType() << Throw->getSourceRange());
3047 }
3048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049
John McCallb268a282010-08-23 23:25:46 +00003050 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00003051}
3052
John McCalldadc5752010-08-24 06:29:42 +00003053StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003055 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003056 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003057 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3058
John McCallb268a282010-08-23 23:25:46 +00003059 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003060 // @throw without an expression designates a rethrow (which much occur
3061 // in the context of an @catch clause).
3062 Scope *AtCatchParent = CurScope;
3063 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3064 AtCatchParent = AtCatchParent->getParent();
3065 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003066 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003067 }
John McCallb268a282010-08-23 23:25:46 +00003068 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003069}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003070
John McCalld9bb7432011-07-27 21:50:02 +00003071ExprResult
3072Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3073 ExprResult result = DefaultLvalueConversion(operand);
3074 if (result.isInvalid())
3075 return ExprError();
3076 operand = result.take();
3077
3078 // Make sure the expression type is an ObjC pointer or "void *".
3079 QualType type = operand->getType();
3080 if (!type->isDependentType() &&
3081 !type->isObjCObjectPointerType()) {
3082 const PointerType *pointerType = type->getAs<PointerType>();
3083 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3084 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3085 << type << operand->getSourceRange();
3086 }
3087
3088 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003089 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003090}
3091
John McCalldadc5752010-08-24 06:29:42 +00003092StmtResult
John McCallb268a282010-08-23 23:25:46 +00003093Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3094 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003095 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003096 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00003097 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003098}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003099
3100/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3101/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003102StmtResult
John McCall48871652010-08-21 09:40:31 +00003103Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003104 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003105 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00003106 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00003107 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00003108 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00003109}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003110
John McCall31168b02011-06-15 23:02:42 +00003111StmtResult
3112Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3113 getCurFunction()->setHasBranchProtectedScope();
3114 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3115}
3116
Dan Gohman28ade552010-07-26 21:25:24 +00003117namespace {
3118
Sebastian Redl63c4da02009-07-29 17:15:45 +00003119class TypeWithHandler {
3120 QualType t;
3121 CXXCatchStmt *stmt;
3122public:
3123 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3124 : t(type), stmt(statement) {}
3125
John McCall8ccfcb52009-09-24 19:53:00 +00003126 // An arbitrary order is fine as long as it places identical
3127 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003128 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003129 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003130 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003131 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003132 return false;
3133 else
3134 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3135 }
Mike Stump11289f42009-09-09 15:08:12 +00003136
Sebastian Redl63c4da02009-07-29 17:15:45 +00003137 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003138 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
Sebastian Redl63c4da02009-07-29 17:15:45 +00003141 CXXCatchStmt *getCatchStmt() const { return stmt; }
3142 SourceLocation getTypeSpecStartLoc() const {
3143 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3144 }
3145};
3146
Dan Gohman28ade552010-07-26 21:25:24 +00003147}
3148
Sebastian Redl9b244a82008-12-22 21:35:02 +00003149/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3150/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003151StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3152 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003153 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003154 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003155 !getSourceManager().isInSystemHeader(TryLoc))
3156 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003157
Robert Wilhelmcafda822013-08-22 09:20:03 +00003158 const unsigned NumHandlers = Handlers.size();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003159 assert(NumHandlers > 0 &&
3160 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003161
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003162 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003163
3164 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003165 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003166 if (!Handler->getExceptionDecl()) {
3167 if (i < NumHandlers - 1)
3168 return StmtError(Diag(Handler->getLocStart(),
3169 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003170
Sebastian Redl63c4da02009-07-29 17:15:45 +00003171 continue;
3172 }
Mike Stump11289f42009-09-09 15:08:12 +00003173
Sebastian Redl63c4da02009-07-29 17:15:45 +00003174 const QualType CaughtType = Handler->getCaughtType();
3175 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3176 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003177 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003178
3179 // Detect handlers for the same type as an earlier one.
3180 if (NumHandlers > 1) {
3181 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003182
Sebastian Redl63c4da02009-07-29 17:15:45 +00003183 TypeWithHandler prev = TypesWithHandlers[0];
3184 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3185 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003186
Sebastian Redl63c4da02009-07-29 17:15:45 +00003187 if (curr == prev) {
3188 Diag(curr.getTypeSpecStartLoc(),
3189 diag::warn_exception_caught_by_earlier_handler)
3190 << curr.getCatchStmt()->getCaughtType().getAsString();
3191 Diag(prev.getTypeSpecStartLoc(),
3192 diag::note_previous_exception_handler)
3193 << prev.getCatchStmt()->getCaughtType().getAsString();
3194 }
Mike Stump11289f42009-09-09 15:08:12 +00003195
Sebastian Redl63c4da02009-07-29 17:15:45 +00003196 prev = curr;
3197 }
3198 }
Mike Stump11289f42009-09-09 15:08:12 +00003199
John McCallaab3e412010-08-25 08:40:02 +00003200 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003201
Sebastian Redl9b244a82008-12-22 21:35:02 +00003202 // FIXME: We should detect handlers that cannot catch anything because an
3203 // earlier handler catches a superclass. Need to find a method that is not
3204 // quadratic for this.
3205 // Neither of these are explicitly forbidden, but every compiler detects them
3206 // and warns.
3207
Robert Wilhelmcafda822013-08-22 09:20:03 +00003208 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003209}
John Wiegley1c0675e2011-04-28 01:08:34 +00003210
3211StmtResult
3212Sema::ActOnSEHTryBlock(bool IsCXXTry,
3213 SourceLocation TryLoc,
3214 Stmt *TryBlock,
3215 Stmt *Handler) {
3216 assert(TryBlock && Handler);
3217
3218 getCurFunction()->setHasBranchProtectedScope();
3219
3220 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3221}
3222
3223StmtResult
3224Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3225 Expr *FilterExpr,
3226 Stmt *Block) {
3227 assert(FilterExpr && Block);
3228
3229 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003230 return StmtError(Diag(FilterExpr->getExprLoc(),
3231 diag::err_filter_expression_integral)
3232 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003233 }
3234
3235 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3236}
3237
3238StmtResult
3239Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3240 Stmt *Block) {
3241 assert(Block);
3242 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3243}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003244
3245StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3246 bool IsIfExists,
3247 NestedNameSpecifierLoc QualifierLoc,
3248 DeclarationNameInfo NameInfo,
3249 Stmt *Nested)
3250{
3251 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003252 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003253 cast<CompoundStmt>(Nested));
3254}
3255
3256
Chad Rosier02a84392012-08-10 17:56:09 +00003257StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003258 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003259 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003260 UnqualifiedId &Name,
3261 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003262 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003263 SS.getWithLocInContext(Context),
3264 GetNameFromUnqualifiedId(Name),
3265 Nested);
3266}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003267
3268RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003269Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3270 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003271 DeclContext *DC = CurContext;
3272 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3273 DC = DC->getParent();
3274
3275 RecordDecl *RD = 0;
3276 if (getLangOpts().CPlusPlus)
3277 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3278 else
3279 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3280
3281 DC->addDecl(RD);
3282 RD->setImplicit();
3283 RD->startDefinition();
3284
Ben Langmuir37943a72013-05-03 19:00:33 +00003285 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003286 DC->addDecl(CD);
3287
Ben Langmuir37943a72013-05-03 19:00:33 +00003288 // Build the context parameter
3289 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3290 DC = CapturedDecl::castToDeclContext(CD);
3291 IdentifierInfo *VarName = &Context.Idents.get("__context");
3292 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3293 ImplicitParamDecl *Param
3294 = ImplicitParamDecl::Create(Context, DC, Loc, VarName, ParamType);
3295 DC->addDecl(Param);
3296
3297 CD->setContextParam(Param);
3298
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003299 return RD;
3300}
3301
3302static void buildCapturedStmtCaptureList(
3303 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3304 SmallVectorImpl<Expr *> &CaptureInits,
3305 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3306
3307 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3308 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3309
3310 if (Cap->isThisCapture()) {
3311 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3312 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003313 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003314 continue;
3315 }
3316
3317 assert(Cap->isReferenceCapture() &&
3318 "non-reference capture not yet implemented");
3319
3320 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3321 CapturedStmt::VCK_ByRef,
3322 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003323 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003324 }
3325}
3326
3327void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003328 CapturedRegionKind Kind,
3329 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003330 CapturedDecl *CD = 0;
Ben Langmuir37943a72013-05-03 19:00:33 +00003331 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003332
3333 // Enter the capturing scope for this captured region.
3334 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3335
3336 if (CurScope)
3337 PushDeclContext(CurScope, CD);
3338 else
3339 CurContext = CD;
3340
3341 PushExpressionEvaluationContext(PotentiallyEvaluated);
3342}
3343
Wei Pan17fbf6e2013-05-04 03:59:06 +00003344void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003345 DiscardCleanupsInEvaluationContext();
3346 PopExpressionEvaluationContext();
3347
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003348 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3349 RecordDecl *Record = RSI->TheRecordDecl;
3350 Record->setInvalidDecl();
3351
Aaron Ballman62e47c42014-03-10 13:43:55 +00003352 SmallVector<Decl*, 4> Fields(Record->fields());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003353 ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
3354 SourceLocation(), SourceLocation(), /*AttributeList=*/0);
3355
Wei Pan17fbf6e2013-05-04 03:59:06 +00003356 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003357 PopFunctionScopeInfo();
3358}
3359
3360StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3361 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3362
3363 SmallVector<CapturedStmt::Capture, 4> Captures;
3364 SmallVector<Expr *, 4> CaptureInits;
3365 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3366
3367 CapturedDecl *CD = RSI->TheCapturedDecl;
3368 RecordDecl *RD = RSI->TheRecordDecl;
3369
Wei Pan17fbf6e2013-05-04 03:59:06 +00003370 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3371 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003372 CaptureInits, CD, RD);
3373
3374 CD->setBody(Res->getCapturedStmt());
3375 RD->completeDefinition();
3376
Wei Pan17fbf6e2013-05-04 03:59:06 +00003377 DiscardCleanupsInEvaluationContext();
3378 PopExpressionEvaluationContext();
3379
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003380 PopDeclContext();
3381 PopFunctionScopeInfo();
3382
3383 return Owned(Res);
3384}