blob: a6b98a2f6a7f8370c0a13304f4d7d74c8d6c6fc9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall1cd76e82011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu694e7962012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000022#include "clang/AST/StmtCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/AST/StmtObjC.h"
John McCall209acbd2010-04-06 22:24:14 +000024#include "clang/AST/TypeLoc.h"
Chandler Carruth55fc8732012-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 Lattnerca57b4b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
Richard Smith41956372013-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 Gregorbebbe0d2010-12-15 01:34:56 +000045 return StmtError();
46
Chris Lattner834a72a2008-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 Redla60528c2008-12-21 12:04:03 +000050
Chris Lattner834a72a2008-07-25 23:18:17 +000051 // Same thing in for stmt first clause (when expr) and third clause.
Richard Smith41956372013-01-14 22:39:08 +000052 return Owned(static_cast<Stmt*>(FE.take()));
Reid Spencer5f016e22007-07-11 17:01:13 +000053}
54
55
John McCallb760f112013-03-22 02:10:40 +000056StmtResult Sema::ActOnExprStmtError() {
57 DiscardCleanupsInEvaluationContext();
58 return StmtError();
59}
60
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000061StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000062 bool HasLeadingEmptyMacro) {
63 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000064}
65
Chris Lattner337e5502011-02-18 01:27:55 +000066StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000068 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner20401692009-04-12 20:13:14 +000070 // If we have an invalid decl, just return an error.
71 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000072
Chris Lattner24e1e702009-03-04 04:23:07 +000073 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000074}
75
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000076void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
77 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Wei Pan55c7d022013-05-03 21:07:45 +000078
Douglas Gregor12849d02013-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 Takumidfbb02a2011-01-27 07:10:08 +000083
Douglas Gregor12849d02013-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 McCallf85e1932011-06-15 23:02:42 +000095
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000096 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000097 var->setUsed();
98
John McCall7acddac2011-06-17 06:42:21 +000099 // foreach variables are never actually initialized in the way that
100 // the parser came up with.
101 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +0000102
John McCall7acddac2011-06-17 06:42:21 +0000103 // In ARC, we don't need to retain the iteration variable of a fast
104 // enumeration loop. Rather than actually trying to catch that
105 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +0000106 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +0000107 QualType type = var->getType();
108
109 // Only do this if we inferred the lifetime. Inferred lifetime
110 // will show up as a local qualifier because explicit lifetime
111 // should have shown up as an AttributedType instead.
112 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
113 // Add 'const' and mark the variable as pseudo-strong.
114 var->setType(type.withConst());
115 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +0000116 }
117 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +0000118}
119
Chandler Carruthec8058f2011-08-17 09:34:37 +0000120/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000121///
122/// Adding a cast to void (or other expression wrappers) will prevent the
123/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000124static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000125 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000126 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000127
128 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
129 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000130 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000131
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000132 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
136 if (Op->getOperator() != OO_EqualEqual &&
137 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000138 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000139
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000140 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000141 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
142 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000143 } else {
144 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000145 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000146 }
147
148 // Suppress warnings when the operator, suspicious as it may be, comes from
149 // a macro expansion.
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +0000150 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthec8058f2011-08-17 09:34:37 +0000151 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000152
Chandler Carruthec8058f2011-08-17 09:34:37 +0000153 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000154 << (unsigned)IsNotEqual << E->getSourceRange();
155
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000156 // If the LHS is a plausible entity to assign to, provide a fixit hint to
157 // correct common typos.
158 if (CanAssign) {
159 if (IsNotEqual)
160 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
161 << FixItHint::CreateReplacement(Loc, "|=");
162 else
163 S.Diag(Loc, diag::note_equality_comparison_to_assign)
164 << FixItHint::CreateReplacement(Loc, "=");
165 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000166
167 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000168}
169
Anders Carlsson636463e2009-07-30 22:17:18 +0000170void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000171 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
172 return DiagnoseUnusedExprResult(Label->getSubStmt());
173
Anders Carlsson75443112009-07-30 22:39:03 +0000174 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000175 if (!E)
176 return;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000177 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000178 // In most cases, we don't want to warn if the expression is written in a
179 // macro body, or if the macro comes from a system header. If the offending
180 // expression is a call to a function with the warn_unused_result attribute,
181 // we warn no matter the location. Because of the order in which the various
182 // checks need to happen, we factor out the macro-related test here.
183 bool ShouldSuppress =
184 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
185 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson636463e2009-07-30 22:17:18 +0000186
Eli Friedmana6115062012-05-24 00:47:05 +0000187 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000188 SourceLocation Loc;
189 SourceRange R1, R2;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000190 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000191 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner06b3a062012-08-31 22:39:21 +0000193 // If this is a GNU statement expression expanded from a macro, it is probably
194 // unused because it is a function-like macro that can be used as either an
195 // expression or statement. Don't warn, because it is almost certainly a
196 // false positive.
197 if (isa<StmtExpr>(E) && Loc.isMacroID())
198 return;
199
Chris Lattner419cfb32009-08-16 16:57:27 +0000200 // Okay, we have an unused result. Depending on what the base expression is,
201 // we might want to make a more specific diagnostic. Check for one of these
202 // cases now.
203 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000204 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000205 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000206 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
207 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000208
Chandler Carruthec8058f2011-08-17 09:34:37 +0000209 if (DiagnoseUnusedComparison(*this, E))
210 return;
211
Eli Friedmana6115062012-05-24 00:47:05 +0000212 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000213 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000214 if (E->getType()->isVoidType())
215 return;
216
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000217 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000218 // a more specific message to make it clear what is happening. If the call
219 // is written in a macro body, only warn if it has the warn_unused_result
220 // attribute.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000221 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000222 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000223 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000224 return;
225 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000226 if (ShouldSuppress)
227 return;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000228 if (FD->getAttr<PureAttr>()) {
229 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
230 return;
231 }
232 if (FD->getAttr<ConstAttr>()) {
233 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
234 return;
235 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000236 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000237 } else if (ShouldSuppress)
238 return;
239
240 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000241 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000242 Diag(Loc, diag::err_arc_unused_init_message) << R1;
243 return;
244 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000245 const ObjCMethodDecl *MD = ME->getMethodDecl();
246 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000247 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000248 return;
249 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000250 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
251 const Expr *Source = POE->getSyntacticForm();
252 if (isa<ObjCSubscriptRefExpr>(Source))
253 DiagID = diag::warn_unused_container_subscript_expr;
254 else
255 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000256 } else if (const CXXFunctionalCastExpr *FC
257 = dyn_cast<CXXFunctionalCastExpr>(E)) {
258 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
259 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
260 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000261 }
John McCall209acbd2010-04-06 22:24:14 +0000262 // Diagnose "(void*) blah" as a typo for "(void) blah".
263 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
264 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
265 QualType T = TI->getType();
266
267 // We really do want to use the non-canonical type here.
268 if (T == Context.VoidPtrTy) {
David Blaikie39e6ab42013-02-18 22:06:02 +0000269 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall209acbd2010-04-06 22:24:14 +0000270
271 Diag(Loc, diag::warn_unused_voidptr)
272 << FixItHint::CreateRemoval(TL.getStarLoc());
273 return;
274 }
275 }
276
Eli Friedmana6115062012-05-24 00:47:05 +0000277 if (E->isGLValue() && E->getType().isVolatileQualified()) {
278 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
279 return;
280 }
281
Ted Kremenek351ba912011-02-23 01:52:04 +0000282 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000283}
284
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000285void Sema::ActOnStartOfCompoundStmt() {
286 PushCompoundScope();
287}
288
289void Sema::ActOnFinishOfCompoundStmt() {
290 PopCompoundScope();
291}
292
293sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
294 return getCurFunction()->CompoundScopes.back();
295}
296
John McCall60d7b3a2010-08-24 06:29:42 +0000297StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000298Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000299 MultiStmtArg elts, bool isStmtExpr) {
300 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000301 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000302 // If we're in C89 mode, check that we don't have any decls after stmts. If
303 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000304 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000305 // Note that __extension__ can be around a decl.
306 unsigned i = 0;
307 // Skip over all declarations.
308 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
309 /*empty*/;
310
311 // We found the end of the list or a statement. Scan for another declstmt.
312 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
313 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000315 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000316 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000317 Diag(D->getLocation(), diag::ext_mixed_decls_code);
318 }
319 }
Chris Lattner98414c12007-08-31 21:49:55 +0000320 // Warn about unused expressions in statements.
321 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000322 // Ignore statements that are last in a statement expression.
323 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000324 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson636463e2009-07-30 22:17:18 +0000326 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000327 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000328
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000329 // Check for suspicious empty body (null statement) in `for' and `while'
330 // statements. Don't do anything for template instantiations, this just adds
331 // noise.
332 if (NumElts != 0 && !CurrentInstantiationScope &&
333 getCurCompoundScope().HasEmptyLoopBodies) {
334 for (unsigned i = 0; i != NumElts - 1; ++i)
335 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
336 }
337
Nico Weberd36aa352012-12-29 20:03:39 +0000338 return Owned(new (Context) CompoundStmt(Context,
339 llvm::makeArrayRef(Elts, NumElts),
340 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000341}
342
John McCall60d7b3a2010-08-24 06:29:42 +0000343StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000344Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
345 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000346 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000347 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000348
John McCall781472f2010-08-25 08:40:02 +0000349 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000350 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000351 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000352 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000353
Richard Smith80ad52f2013-01-02 11:42:31 +0000354 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000355 // C99 6.8.4.2p3: The expression shall be an integer constant.
356 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000357 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
358 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
359 if (!LHSVal)
360 return StmtError();
361 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000362
363 // GCC extension: The expression shall be an integer constant.
364
Richard Smith282e7e62012-02-04 09:53:13 +0000365 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
366 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
367 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000368 }
369 }
Ben Langmuira0152d42013-04-29 13:07:42 +0000370
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000371 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
372 getLangOpts().CPlusPlus11).take();
373 if (RHSVal)
374 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
375 getLangOpts().CPlusPlus11).take();
Richard Smith8ef7b202012-01-18 23:55:52 +0000376
Douglas Gregordbb26db2009-05-15 23:57:33 +0000377 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
378 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000379 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000380 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381}
382
Chris Lattner24e1e702009-03-04 04:23:07 +0000383/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000384void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000385 DiagnoseUnusedExprResult(SubStmt);
386
Chris Lattner24e1e702009-03-04 04:23:07 +0000387 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000388 CS->setSubStmt(SubStmt);
389}
390
John McCall60d7b3a2010-08-24 06:29:42 +0000391StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000392Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000393 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000394 DiagnoseUnusedExprResult(SubStmt);
395
John McCall781472f2010-08-25 08:40:02 +0000396 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000397 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000398 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000399 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000400
Douglas Gregordbb26db2009-05-15 23:57:33 +0000401 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000402 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000403 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000404}
405
John McCall60d7b3a2010-08-24 06:29:42 +0000406StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000407Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
408 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000409 // If the label was multiply defined, reject it now.
410 if (TheDecl->getStmt()) {
411 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
412 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000413 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 }
Sebastian Redlde307472009-01-11 00:38:46 +0000415
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000416 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000417 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
418 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000419 if (!TheDecl->isGnuLocal()) {
420 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000421 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000422 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000423 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000424}
425
Richard Smith534986f2012-04-14 00:33:13 +0000426StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000427 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000428 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000429 // Fill in the declaration and return it.
430 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000431 return Owned(LS);
432}
433
John McCall60d7b3a2010-08-24 06:29:42 +0000434StmtResult
John McCalld226f652010-08-21 09:40:31 +0000435Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000436 Stmt *thenStmt, SourceLocation ElseLoc,
437 Stmt *elseStmt) {
Argyrios Kyrtzidis820b23d2013-02-15 18:34:13 +0000438 // If the condition was invalid, discard the if statement. We could recover
439 // better by replacing it with a valid expr, but don't do that yet.
440 if (!CondVal.get() && !CondVar) {
441 getCurFunction()->setHasDroppedStmt();
442 return StmtError();
443 }
444
John McCall60d7b3a2010-08-24 06:29:42 +0000445 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000447 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000448 if (CondVar) {
449 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000450 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000451 if (CondResult.isInvalid())
452 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000453 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000454 Expr *ConditionExpr = CondResult.takeAs<Expr>();
455 if (!ConditionExpr)
456 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457
Anders Carlsson75443112009-07-30 22:39:03 +0000458 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000459
John McCall9ae2f072010-08-23 23:25:46 +0000460 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000461 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
462 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000463 }
464
Anders Carlsson75443112009-07-30 22:39:03 +0000465 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000466
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000467 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000468 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000469}
470
Chris Lattnerf4021e72007-08-23 05:46:52 +0000471/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
472/// the specified width and sign. If an overflow occurs, detect it and emit
473/// the specified diagnostic.
474void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
475 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000476 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000477 unsigned DiagID) {
478 // Perform a conversion to the promoted condition type if needed.
479 if (NewWidth > Val.getBitWidth()) {
480 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000481 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000482 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000483
484 // If the input was signed and negative and the output is
485 // unsigned, don't bother to warn: this is implementation-defined
486 // behavior.
487 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000488 } else if (NewWidth < Val.getBitWidth()) {
489 // If this is a truncation, check for overflow.
490 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000491 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000492 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000493 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000494 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000495 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000496 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Chris Lattnerf4021e72007-08-23 05:46:52 +0000498 // Regardless of whether a diagnostic was emitted, really do the
499 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000500 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000501 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000502 } else if (NewSign != Val.isSigned()) {
503 // Convert the sign to match the sign of the condition. This can cause
504 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000505 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000506 // behavior.
507 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000508 llvm::APSInt OldVal(Val);
509 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000510 }
511}
512
Chris Lattner0471f5b2007-08-23 18:29:20 +0000513namespace {
514 struct CaseCompareFunctor {
515 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
516 const llvm::APSInt &RHS) {
517 return LHS.first < RHS;
518 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000519 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
520 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
521 return LHS.first < RHS.first;
522 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000523 bool operator()(const llvm::APSInt &LHS,
524 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
525 return LHS < RHS.first;
526 }
527 };
528}
529
Chris Lattner764a7ce2007-09-21 18:15:22 +0000530/// CmpCaseVals - Comparison predicate for sorting case values.
531///
532static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
533 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
534 if (lhs.first < rhs.first)
535 return true;
536
537 if (lhs.first == rhs.first &&
538 lhs.second->getCaseLoc().getRawEncoding()
539 < rhs.second->getCaseLoc().getRawEncoding())
540 return true;
541 return false;
542}
543
Douglas Gregorba915af2010-02-08 22:24:16 +0000544/// CmpEnumVals - Comparison predicate for sorting enumeration values.
545///
546static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
547 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
548{
549 return lhs.first < rhs.first;
550}
551
552/// EqEnumVals - Comparison preficate for uniqing enumeration values.
553///
554static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
555 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
556{
557 return lhs.first == rhs.first;
558}
559
Chris Lattner5f048812009-10-16 16:45:22 +0000560/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
561/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000562static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
563 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
564 expr = cleanups->getSubExpr();
565 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
566 if (impcast->getCastKind() != CK_IntegralCast) break;
567 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000568 }
569 return expr->getType();
570}
571
John McCall60d7b3a2010-08-24 06:29:42 +0000572StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000574 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000575 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000576
Douglas Gregor586596f2010-05-06 17:25:47 +0000577 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000578 if (CondVar) {
579 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000580 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
581 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000582 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
John McCall9ae2f072010-08-23 23:25:46 +0000584 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000585 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586
John McCall9ae2f072010-08-23 23:25:46 +0000587 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000588 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589
Douglas Gregorab41fe92012-05-04 22:38:52 +0000590 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
591 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000592
Douglas Gregorab41fe92012-05-04 22:38:52 +0000593 public:
594 SwitchConvertDiagnoser(Expr *Cond)
Richard Smith097e0a22013-05-21 19:05:48 +0000595 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
596 Cond(Cond) {}
Chad Rosier8e1e0542012-06-20 18:51:04 +0000597
Richard Smith097e0a22013-05-21 19:05:48 +0000598 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
599 QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000600 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
601 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000602
Richard Smith097e0a22013-05-21 19:05:48 +0000603 virtual SemaDiagnosticBuilder diagnoseIncomplete(
604 Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000605 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
606 << T << Cond->getSourceRange();
607 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000608
Richard Smith097e0a22013-05-21 19:05:48 +0000609 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
610 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000611 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
612 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000613
Richard Smith097e0a22013-05-21 19:05:48 +0000614 virtual SemaDiagnosticBuilder noteExplicitConv(
615 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000616 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
617 << ConvTy->isEnumeralType() << ConvTy;
618 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000619
Richard Smith097e0a22013-05-21 19:05:48 +0000620 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
621 QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000622 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
623 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000624
Richard Smith097e0a22013-05-21 19:05:48 +0000625 virtual SemaDiagnosticBuilder noteAmbiguous(
626 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000627 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
628 << ConvTy->isEnumeralType() << ConvTy;
629 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000630
Richard Smith097e0a22013-05-21 19:05:48 +0000631 virtual SemaDiagnosticBuilder diagnoseConversion(
632 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
633 llvm_unreachable("conversion functions are permitted");
Douglas Gregorab41fe92012-05-04 22:38:52 +0000634 }
635 } SwitchDiagnoser(Cond);
636
Richard Smith097e0a22013-05-21 19:05:48 +0000637 CondResult =
638 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCall9ae2f072010-08-23 23:25:46 +0000639 if (CondResult.isInvalid()) return StmtError();
640 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641
John McCalla8e0cd82011-08-06 07:30:58 +0000642 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
643 CondResult = UsualUnaryConversions(Cond);
644 if (CondResult.isInvalid()) return StmtError();
645 Cond = CondResult.take();
646
John McCalld226f652010-08-21 09:40:31 +0000647 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000648 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000649 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000650 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000651 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000652 }
John McCallb60a77e2010-08-01 00:26:45 +0000653
John McCall781472f2010-08-25 08:40:02 +0000654 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
John McCall9ae2f072010-08-23 23:25:46 +0000656 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000657 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000658 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000659}
660
Gabor Greif28164ab2010-10-01 22:05:14 +0000661static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
662 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000663 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000664 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000665 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000666 Val.setIsSigned(IsSigned);
667}
668
John McCall60d7b3a2010-08-24 06:29:42 +0000669StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000670Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
671 Stmt *BodyStmt) {
672 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000673 assert(SS == getCurFunction()->SwitchStack.back() &&
674 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000675
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000676 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000677 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000678
Chris Lattnerf4021e72007-08-23 05:46:52 +0000679 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000680 if (!CondExpr) return StmtError();
681
682 QualType CondType = CondExpr->getType();
683
John McCall0fb97082010-05-18 03:19:21 +0000684 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000685 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000686 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000687
Chris Lattner5f048812009-10-16 16:45:22 +0000688 // C++ 6.4.2.p2:
689 // Integral promotions are performed (on the switch condition).
690 //
691 // A case value unrepresentable by the original switch condition
692 // type (before the promotion) doesn't make sense, even when it can
693 // be represented by the promoted type. Therefore we need to find
694 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000695 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000696 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000698 // appropriate type now, just return an error.
699 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000700 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000701
Chris Lattner2b334bb2010-04-16 23:34:13 +0000702 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000703 // switch(bool_expr) {...} is often a programmer error, e.g.
704 // switch(n && mask) { ... } // Doh - should be "n & mask".
705 // One can always use an if statement instead of switch(bool_expr).
706 Diag(SwitchLoc, diag::warn_bool_switch_condition)
707 << CondExpr->getSourceRange();
708 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000709 }
Sebastian Redlde307472009-01-11 00:38:46 +0000710
Chris Lattnerf4021e72007-08-23 05:46:52 +0000711 // Get the bitwidth of the switched-on value before promotions. We must
712 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000713 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000714 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000715 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000716 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000717 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000718 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Chris Lattnerf4021e72007-08-23 05:46:52 +0000720 // Accumulate all of the case values in a vector so that we can sort them
721 // and detect duplicates. This vector contains the APInt for the case after
722 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000723 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000724 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattnerf4021e72007-08-23 05:46:52 +0000726 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000727 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
728 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Chris Lattnerf4021e72007-08-23 05:46:52 +0000730 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000732 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Douglas Gregordbb26db2009-05-15 23:57:33 +0000734 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000735 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000737 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000738 if (TheDefaultStmt) {
739 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000740 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000741
Chris Lattnerf4021e72007-08-23 05:46:52 +0000742 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000743 // we'll return a valid AST. This requires recursing down the AST and
744 // finding it, not something we are set up to do right now. For now,
745 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000746 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000747 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000748 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattnerf4021e72007-08-23 05:46:52 +0000750 } else {
751 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Chris Lattner1e0a3902008-01-16 19:17:22 +0000753 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000754
755 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
756 HasDependentValue = true;
757 break;
758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Richard Smith8ef7b202012-01-18 23:55:52 +0000760 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Richard Smith80ad52f2013-01-02 11:42:31 +0000762 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000763 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
764 // constant expression of the promoted type of the switch condition.
765 ExprResult ConvLo =
766 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
767 if (ConvLo.isInvalid()) {
768 CaseListIsErroneous = true;
769 continue;
770 }
771 Lo = ConvLo.take();
772 } else {
773 // We already verified that the expression has a i-c-e value (C99
774 // 6.8.4.2p3) - get that value now.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000775 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smith8ef7b202012-01-18 23:55:52 +0000776
777 // If the LHS is not the same type as the condition, insert an implicit
778 // cast.
779 Lo = DefaultLvalueConversion(Lo).take();
780 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
781 }
782
783 // Convert the value to the same width/sign as the condition had prior to
784 // integral promotions.
785 //
786 // FIXME: This causes us to reject valid code:
787 // switch ((char)c) { case 256: case 0: return 0; }
788 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000789 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000790 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000791 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000792
Chris Lattner1e0a3902008-01-16 19:17:22 +0000793 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000795 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000796 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000797 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000798 CS->getRHS()->isValueDependent()) {
799 HasDependentValue = true;
800 break;
801 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000802 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000803 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000804 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000805 }
806 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000807
808 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000809 // If we don't have a default statement, check whether the
810 // condition is constant.
811 llvm::APSInt ConstantCondValue;
812 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000813 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000814 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000815 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
816 Expr::SE_AllowSideEffects);
817 assert(!HasConstantCond ||
818 (ConstantCondValue.getBitWidth() == CondWidth &&
819 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000820 }
Richard Smith80d4b552011-12-28 19:48:30 +0000821 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000822
Douglas Gregordbb26db2009-05-15 23:57:33 +0000823 // Sort all the scalar case values so we can easily detect duplicates.
824 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
825
826 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000827 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
828 if (ShouldCheckConstantCond &&
829 CaseVals[i].first == ConstantCondValue)
830 ShouldCheckConstantCond = false;
831
832 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000833 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000834 // First, determine if either case value has a name
835 StringRef PrevString, CurrString;
836 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
837 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
838 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
839 PrevString = DeclRef->getDecl()->getName();
840 }
841 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
842 CurrString = DeclRef->getDecl()->getName();
843 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000844 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000845 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000846
847 if (PrevString == CurrString)
848 Diag(CaseVals[i].second->getLHS()->getLocStart(),
849 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000850 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000851 else
852 Diag(CaseVals[i].second->getLHS()->getLocStart(),
853 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000854 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
855 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000856 CaseValStr;
857
John McCall0fb97082010-05-18 03:19:21 +0000858 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000859 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000860 // FIXME: We really want to remove the bogus case stmt from the
861 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000862 CaseListIsErroneous = true;
863 }
864 }
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregordbb26db2009-05-15 23:57:33 +0000867 // Detect duplicate case ranges, which usually don't exist at all in
868 // the first place.
869 if (!CaseRanges.empty()) {
870 // Sort all the case ranges by their low value so we can easily detect
871 // overlaps between ranges.
872 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Douglas Gregordbb26db2009-05-15 23:57:33 +0000874 // Scan the ranges, computing the high values and removing empty ranges.
875 std::vector<llvm::APSInt> HiVals;
876 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000877 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000878 CaseStmt *CR = CaseRanges[i].second;
879 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000880 llvm::APSInt HiVal;
881
Richard Smith80ad52f2013-01-02 11:42:31 +0000882 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000883 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
884 // constant expression of the promoted type of the switch condition.
885 ExprResult ConvHi =
886 CheckConvertedConstantExpression(Hi, CondType, HiVal,
887 CCEK_CaseValue);
888 if (ConvHi.isInvalid()) {
889 CaseListIsErroneous = true;
890 continue;
891 }
892 Hi = ConvHi.take();
893 } else {
894 HiVal = Hi->EvaluateKnownConstInt(Context);
895
896 // If the RHS is not the same type as the condition, insert an
897 // implicit cast.
898 Hi = DefaultLvalueConversion(Hi).take();
899 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Douglas Gregordbb26db2009-05-15 23:57:33 +0000902 // Convert the value to the same width/sign as the condition.
903 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000904 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000905 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Douglas Gregordbb26db2009-05-15 23:57:33 +0000907 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Douglas Gregordbb26db2009-05-15 23:57:33 +0000909 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000910 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000911 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
912 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000913 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000914 CaseRanges.erase(CaseRanges.begin()+i);
915 --i, --e;
916 continue;
917 }
John McCall0fb97082010-05-18 03:19:21 +0000918
919 if (ShouldCheckConstantCond &&
920 LoVal <= ConstantCondValue &&
921 ConstantCondValue <= HiVal)
922 ShouldCheckConstantCond = false;
923
Douglas Gregordbb26db2009-05-15 23:57:33 +0000924 HiVals.push_back(HiVal);
925 }
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Douglas Gregordbb26db2009-05-15 23:57:33 +0000927 // Rescan the ranges, looking for overlap with singleton values and other
928 // ranges. Since the range list is sorted, we only need to compare case
929 // ranges with their neighbors.
930 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
931 llvm::APSInt &CRLo = CaseRanges[i].first;
932 llvm::APSInt &CRHi = HiVals[i];
933 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Douglas Gregordbb26db2009-05-15 23:57:33 +0000935 // Check to see whether the case range overlaps with any
936 // singleton cases.
937 CaseStmt *OverlapStmt = 0;
938 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregordbb26db2009-05-15 23:57:33 +0000940 // Find the smallest value >= the lower bound. If I is in the
941 // case range, then we have overlap.
942 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
943 CaseVals.end(), CRLo,
944 CaseCompareFunctor());
945 if (I != CaseVals.end() && I->first < CRHi) {
946 OverlapVal = I->first; // Found overlap with scalar.
947 OverlapStmt = I->second;
948 }
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Douglas Gregordbb26db2009-05-15 23:57:33 +0000950 // Find the smallest value bigger than the upper bound.
951 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
952 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
953 OverlapVal = (I-1)->first; // Found overlap with scalar.
954 OverlapStmt = (I-1)->second;
955 }
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Douglas Gregordbb26db2009-05-15 23:57:33 +0000957 // Check to see if this case stmt overlaps with the subsequent
958 // case range.
959 if (i && CRLo <= HiVals[i-1]) {
960 OverlapVal = HiVals[i-1]; // Found overlap with range.
961 OverlapStmt = CaseRanges[i-1].second;
962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Douglas Gregordbb26db2009-05-15 23:57:33 +0000964 if (OverlapStmt) {
965 // If we have a duplicate, report it.
966 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
967 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000968 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000969 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000970 // FIXME: We really want to remove the bogus case stmt from the
971 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000972 CaseListIsErroneous = true;
973 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000974 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000975 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000976
John McCall0fb97082010-05-18 03:19:21 +0000977 // Complain if we have a constant condition and we didn't find a match.
978 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
979 // TODO: it would be nice if we printed enums as enums, chars as
980 // chars, etc.
981 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
982 << ConstantCondValue.toString(10)
983 << CondExpr->getSourceRange();
984 }
985
986 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000987 // values. We only issue a warning if there is not 'default:', but
988 // we still do the analysis to preserve this information in the AST
989 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000990 //
Chris Lattnerce784612010-09-16 17:09:42 +0000991 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000992
Douglas Gregorba915af2010-02-08 22:24:16 +0000993 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000994 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000995 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000996 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000997 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000998 EnumValsTy EnumVals;
999
John McCall0fb97082010-05-18 03:19:21 +00001000 // Gather all enum values, set their type and sort them,
1001 // allowing easier comparison with CaseVals.
1002 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +00001003 EDI != ED->enumerator_end(); ++EDI) {
1004 llvm::APSInt Val = EDI->getInitVal();
1005 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +00001006 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +00001007 }
1008 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +00001009 EnumValsTy::iterator EIend =
1010 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +00001011
1012 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +00001013 EnumValsTy::const_iterator EI = EnumVals.begin();
1014 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1015 CI != CaseVals.end(); CI++) {
1016 while (EI != EIend && EI->first < CI->first)
1017 EI++;
1018 if (EI == EIend || EI->first > CI->first)
1019 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001020 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +00001021 }
1022 // See which of case ranges aren't in enum
1023 EI = EnumVals.begin();
1024 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1025 RI != CaseRanges.end() && EI != EIend; RI++) {
1026 while (EI != EIend && EI->first < RI->first)
1027 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028
David Blaikie93667502012-01-22 02:31:55 +00001029 if (EI == EIend || EI->first != RI->first) {
1030 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001031 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001032 }
David Blaikie93667502012-01-22 02:31:55 +00001033
Chad Rosier1093f492012-08-10 17:56:09 +00001034 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001035 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1036 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1037 while (EI != EIend && EI->first < Hi)
1038 EI++;
1039 if (EI == EIend || EI->first != Hi)
1040 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001041 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001043
Ted Kremenek559fb552010-09-09 00:05:53 +00001044 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001045 CaseValsTy::const_iterator CI = CaseVals.begin();
1046 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001047 bool hasCasesNotInSwitch = false;
1048
Chris Lattner5f9e2722011-07-23 10:55:15 +00001049 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001050
David Blaikie93667502012-01-22 02:31:55 +00001051 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001052 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001053 llvm::APSInt CIVal;
1054 while (CI != CaseVals.end() && CI->first < EI->first)
1055 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001056
Douglas Gregorba915af2010-02-08 22:24:16 +00001057 if (CI != CaseVals.end() && CI->first == EI->first)
1058 continue;
1059
Ted Kremenek559fb552010-09-09 00:05:53 +00001060 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001061 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001062 llvm::APSInt Hi =
1063 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001064 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001065 if (EI->first <= Hi)
1066 break;
1067 }
1068
Ted Kremenek559fb552010-09-09 00:05:53 +00001069 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001070 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001071 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001072 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001073 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074
David Blaikie585d7792012-01-23 04:46:12 +00001075 if (TheDefaultStmt && UnhandledNames.empty())
1076 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001077
Chris Lattnerce784612010-09-16 17:09:42 +00001078 // Produce a nice diagnostic if multiple values aren't handled.
1079 switch (UnhandledNames.size()) {
1080 case 0: break;
1081 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001082 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001083 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001084 << UnhandledNames[0];
1085 break;
1086 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001087 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001088 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001089 << UnhandledNames[0] << UnhandledNames[1];
1090 break;
1091 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001092 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1093 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001094 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1095 break;
1096 default:
David Blaikie585d7792012-01-23 04:46:12 +00001097 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1098 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001099 << (unsigned)UnhandledNames.size()
1100 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1101 break;
1102 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001103
1104 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001105 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001106 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001107 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001108
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001109 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1110 diag::warn_empty_switch_body);
1111
Mike Stump390b4cc2009-05-16 07:39:55 +00001112 // FIXME: If the case list was broken is some way, we don't have a good system
1113 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001114 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001115 return StmtError();
1116
Sebastian Redlde307472009-01-11 00:38:46 +00001117 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001118}
1119
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001120void
1121Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1122 Expr *SrcExpr) {
1123 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001124 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001125 == DiagnosticsEngine::Ignored)
1126 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001127
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001128 if (const EnumType *ET = DstType->getAs<EnumType>())
1129 if (!Context.hasSameType(SrcType, DstType) &&
1130 SrcType->isIntegerType()) {
1131 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1132 SrcExpr->isIntegerConstantExpr(Context)) {
1133 // Get the bitwidth of the enum value before promotions.
1134 unsigned DstWith = Context.getIntWidth(DstType);
1135 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1136
1137 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1138 const EnumDecl *ED = ET->getDecl();
1139 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1140 EnumValsTy;
1141 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001142
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001143 // Gather all enum values, set their type and sort them,
1144 // allowing easier comparison with rhs constant.
1145 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1146 EDI != ED->enumerator_end(); ++EDI) {
1147 llvm::APSInt Val = EDI->getInitVal();
1148 AdjustAPSInt(Val, DstWith, DstIsSigned);
1149 EnumVals.push_back(std::make_pair(Val, *EDI));
1150 }
1151 if (EnumVals.empty())
1152 return;
1153 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1154 EnumValsTy::iterator EIend =
1155 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001156
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001157 // See which case values aren't in enum.
1158 EnumValsTy::const_iterator EI = EnumVals.begin();
1159 while (EI != EIend && EI->first < RhsVal)
1160 EI++;
1161 if (EI == EIend || EI->first != RhsVal) {
1162 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1163 << DstType;
1164 }
1165 }
1166 }
1167}
1168
John McCall60d7b3a2010-08-24 06:29:42 +00001169StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001170Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001171 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001172 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001173
Douglas Gregor5656e142009-11-24 21:15:44 +00001174 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001175 if (CondVar) {
1176 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001177 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001178 if (CondResult.isInvalid())
1179 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001180 }
John McCall9ae2f072010-08-23 23:25:46 +00001181 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001182 if (!ConditionExpr)
1183 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001184
John McCall9ae2f072010-08-23 23:25:46 +00001185 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001187 if (isa<NullStmt>(Body))
1188 getCurCompoundScope().setHasEmptyLoopBodies();
1189
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001190 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001191 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001192}
1193
John McCall60d7b3a2010-08-24 06:29:42 +00001194StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001195Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001196 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001197 Expr *Cond, SourceLocation CondRParen) {
1198 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001199
John Wiegley429bb272011-04-08 18:41:53 +00001200 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001201 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001202 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001203 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001204
Richard Smith41956372013-01-14 22:39:08 +00001205 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001206 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001207 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001208 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001209
John McCall9ae2f072010-08-23 23:25:46 +00001210 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001211
John McCall9ae2f072010-08-23 23:25:46 +00001212 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001213}
1214
Richard Trieu694e7962012-04-30 18:01:30 +00001215namespace {
1216 // This visitor will traverse a conditional statement and store all
1217 // the evaluated decls into a vector. Simple is set to true if none
1218 // of the excluded constructs are used.
1219 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1220 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001221 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001222 bool Simple;
Richard Trieu923cada2013-05-31 22:46:45 +00001223 public:
1224 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001225
Richard Trieu923cada2013-05-31 22:46:45 +00001226 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1227 SmallVector<SourceRange, 10> &Ranges) :
1228 Inherited(S.Context),
1229 Decls(Decls),
1230 Ranges(Ranges),
1231 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001232
Richard Trieu923cada2013-05-31 22:46:45 +00001233 bool isSimple() { return Simple; }
Richard Trieu694e7962012-04-30 18:01:30 +00001234
Richard Trieu923cada2013-05-31 22:46:45 +00001235 // Replaces the method in EvaluatedExprVisitor.
1236 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001237 Simple = false;
Richard Trieu923cada2013-05-31 22:46:45 +00001238 }
1239
1240 // Any Stmt not whitelisted will cause the condition to be marked complex.
1241 void VisitStmt(Stmt *S) {
1242 Simple = false;
1243 }
1244
1245 void VisitBinaryOperator(BinaryOperator *E) {
1246 Visit(E->getLHS());
1247 Visit(E->getRHS());
1248 }
1249
1250 void VisitCastExpr(CastExpr *E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001251 Visit(E->getSubExpr());
Richard Trieu923cada2013-05-31 22:46:45 +00001252 }
Richard Trieu694e7962012-04-30 18:01:30 +00001253
Richard Trieu923cada2013-05-31 22:46:45 +00001254 void VisitUnaryOperator(UnaryOperator *E) {
1255 // Skip checking conditionals with derefernces.
1256 if (E->getOpcode() == UO_Deref)
1257 Simple = false;
1258 else
1259 Visit(E->getSubExpr());
1260 }
Richard Trieu694e7962012-04-30 18:01:30 +00001261
Richard Trieu923cada2013-05-31 22:46:45 +00001262 void VisitConditionalOperator(ConditionalOperator *E) {
1263 Visit(E->getCond());
1264 Visit(E->getTrueExpr());
1265 Visit(E->getFalseExpr());
1266 }
Richard Trieu694e7962012-04-30 18:01:30 +00001267
Richard Trieu923cada2013-05-31 22:46:45 +00001268 void VisitParenExpr(ParenExpr *E) {
1269 Visit(E->getSubExpr());
1270 }
Richard Trieu694e7962012-04-30 18:01:30 +00001271
Richard Trieu923cada2013-05-31 22:46:45 +00001272 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1273 Visit(E->getOpaqueValue()->getSourceExpr());
1274 Visit(E->getFalseExpr());
1275 }
Richard Trieu694e7962012-04-30 18:01:30 +00001276
Richard Trieu923cada2013-05-31 22:46:45 +00001277 void VisitIntegerLiteral(IntegerLiteral *E) { }
1278 void VisitFloatingLiteral(FloatingLiteral *E) { }
1279 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1280 void VisitCharacterLiteral(CharacterLiteral *E) { }
1281 void VisitGNUNullExpr(GNUNullExpr *E) { }
1282 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu694e7962012-04-30 18:01:30 +00001283
Richard Trieu923cada2013-05-31 22:46:45 +00001284 void VisitDeclRefExpr(DeclRefExpr *E) {
1285 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1286 if (!VD) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001287
Richard Trieu923cada2013-05-31 22:46:45 +00001288 Ranges.push_back(E->getSourceRange());
1289
1290 Decls.insert(VD);
1291 }
Richard Trieu694e7962012-04-30 18:01:30 +00001292
1293 }; // end class DeclExtractor
1294
1295 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001296 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001297 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1298 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1299 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001300
Richard Trieu923cada2013-05-31 22:46:45 +00001301 public:
1302 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001303
Richard Trieu923cada2013-05-31 22:46:45 +00001304 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1305 Stmt *Statement) :
1306 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1307 if (!Statement) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001308
Richard Trieu923cada2013-05-31 22:46:45 +00001309 Visit(Statement);
Richard Trieu694e7962012-04-30 18:01:30 +00001310 }
1311
Richard Trieu923cada2013-05-31 22:46:45 +00001312 void VisitReturnStmt(ReturnStmt *S) {
1313 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001314 }
1315
Richard Trieu923cada2013-05-31 22:46:45 +00001316 void VisitBreakStmt(BreakStmt *S) {
1317 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001318 }
1319
Richard Trieu923cada2013-05-31 22:46:45 +00001320 void VisitGotoStmt(GotoStmt *S) {
1321 FoundDecl = true;
1322 }
Richard Trieu694e7962012-04-30 18:01:30 +00001323
Richard Trieu923cada2013-05-31 22:46:45 +00001324 void VisitCastExpr(CastExpr *E) {
1325 if (E->getCastKind() == CK_LValueToRValue)
1326 CheckLValueToRValueCast(E->getSubExpr());
1327 else
1328 Visit(E->getSubExpr());
1329 }
Richard Trieu694e7962012-04-30 18:01:30 +00001330
Richard Trieu923cada2013-05-31 22:46:45 +00001331 void CheckLValueToRValueCast(Expr *E) {
1332 E = E->IgnoreParenImpCasts();
1333
1334 if (isa<DeclRefExpr>(E)) {
1335 return;
1336 }
1337
1338 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1339 Visit(CO->getCond());
1340 CheckLValueToRValueCast(CO->getTrueExpr());
1341 CheckLValueToRValueCast(CO->getFalseExpr());
1342 return;
1343 }
1344
1345 if (BinaryConditionalOperator *BCO =
1346 dyn_cast<BinaryConditionalOperator>(E)) {
1347 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1348 CheckLValueToRValueCast(BCO->getFalseExpr());
1349 return;
1350 }
1351
1352 Visit(E);
1353 }
1354
1355 void VisitDeclRefExpr(DeclRefExpr *E) {
1356 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1357 if (Decls.count(VD))
1358 FoundDecl = true;
1359 }
1360
1361 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu694e7962012-04-30 18:01:30 +00001362
1363 }; // end class DeclMatcher
1364
1365 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1366 Expr *Third, Stmt *Body) {
1367 // Condition is empty
1368 if (!Second) return;
1369
1370 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1371 Second->getLocStart())
1372 == DiagnosticsEngine::Ignored)
1373 return;
1374
1375 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1376 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001377 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001378 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001379 DE.Visit(Second);
1380
1381 // Don't analyze complex conditionals.
1382 if (!DE.isSimple()) return;
1383
1384 // No decls found.
1385 if (Decls.size() == 0) return;
1386
Richard Trieu90875992012-05-04 03:01:54 +00001387 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001388 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1389 E = Decls.end();
1390 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001391 if ((*I)->getType().isVolatileQualified() ||
1392 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001393
1394 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1395 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1396 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1397 return;
1398
1399 // Load decl names into diagnostic.
1400 if (Decls.size() > 4)
1401 PDiag << 0;
1402 else {
1403 PDiag << Decls.size();
1404 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1405 E = Decls.end();
1406 I != E; ++I)
1407 PDiag << (*I)->getDeclName();
1408 }
1409
1410 // Load SourceRanges into diagnostic if there is room.
1411 // Otherwise, load the SourceRange of the conditional expression.
1412 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001413 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1414 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001415 I != E; ++I)
1416 PDiag << *I;
1417 else
1418 PDiag << Second->getSourceRange();
1419
1420 S.Diag(Ranges.begin()->getBegin(), PDiag);
1421 }
1422
1423} // end namespace
1424
John McCall60d7b3a2010-08-24 06:29:42 +00001425StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001426Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001427 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001428 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001429 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001430 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001431 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001432 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1433 // declare identifiers for objects having storage class 'auto' or
1434 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001435 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1436 DI!=DE; ++DI) {
1437 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001438 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001439 VD = 0;
Douglas Gregor12849d02013-04-08 20:52:24 +00001440 if (VD == 0) {
1441 Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
1442 (*DI)->setInvalidDecl();
1443 }
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001444 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001445 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001447
Richard Trieu694e7962012-04-30 18:01:30 +00001448 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1449
John McCall60d7b3a2010-08-24 06:29:42 +00001450 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001451 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001452 if (secondVar) {
1453 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001454 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001455 if (SecondResult.isInvalid())
1456 return StmtError();
1457 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001458
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001459 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460
Anders Carlsson3af708f2009-08-01 01:39:59 +00001461 DiagnoseUnusedExprResult(First);
1462 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001463 DiagnoseUnusedExprResult(Body);
1464
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001465 if (isa<NullStmt>(Body))
1466 getCurCompoundScope().setHasEmptyLoopBodies();
1467
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468 return Owned(new (Context) ForStmt(Context, First,
1469 SecondResult.take(), ConditionVar,
1470 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001471 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001472}
1473
John McCallf6a16482010-12-04 03:47:34 +00001474/// In an Objective C collection iteration statement:
1475/// for (x in y)
1476/// x can be an arbitrary l-value expression. Bind it up as a
1477/// full-expression.
1478StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001479 // Reduce placeholder expressions here. Note that this rejects the
1480 // use of pseudo-object l-values in this position.
1481 ExprResult result = CheckPlaceholderExpr(E);
1482 if (result.isInvalid()) return StmtError();
1483 E = result.take();
1484
Richard Smith41956372013-01-14 22:39:08 +00001485 ExprResult FullExpr = ActOnFinishFullExpr(E);
1486 if (FullExpr.isInvalid())
1487 return StmtError();
1488 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001489}
1490
John McCall990567c2011-07-27 01:07:15 +00001491ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001492Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1493 if (!collection)
1494 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001495
John McCall990567c2011-07-27 01:07:15 +00001496 // Bail out early if we've got a type-dependent expression.
1497 if (collection->isTypeDependent()) return Owned(collection);
1498
1499 // Perform normal l-value conversion.
1500 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1501 if (result.isInvalid())
1502 return ExprError();
1503 collection = result.take();
1504
1505 // The operand needs to have object-pointer type.
1506 // TODO: should we do a contextual conversion?
1507 const ObjCObjectPointerType *pointerType =
1508 collection->getType()->getAs<ObjCObjectPointerType>();
1509 if (!pointerType)
1510 return Diag(forLoc, diag::err_collection_expr_type)
1511 << collection->getType() << collection->getSourceRange();
1512
1513 // Check that the operand provides
1514 // - countByEnumeratingWithState:objects:count:
1515 const ObjCObjectType *objectType = pointerType->getObjectType();
1516 ObjCInterfaceDecl *iface = objectType->getInterface();
1517
1518 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001519 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001520 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001521 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001522 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001523 ? diag::err_arc_collection_forward
1524 : 0,
1525 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001526 // Otherwise, if we have any useful type information, check that
1527 // the type declares the appropriate method.
1528 } else if (iface || !objectType->qual_empty()) {
1529 IdentifierInfo *selectorIdents[] = {
1530 &Context.Idents.get("countByEnumeratingWithState"),
1531 &Context.Idents.get("objects"),
1532 &Context.Idents.get("count")
1533 };
1534 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1535
1536 ObjCMethodDecl *method = 0;
1537
1538 // If there's an interface, look in both the public and private APIs.
1539 if (iface) {
1540 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001541 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001542 }
1543
1544 // Also check protocol qualifiers.
1545 if (!method)
1546 method = LookupMethodInQualifiedType(selector, pointerType,
1547 /*instance*/ true);
1548
1549 // If we didn't find it anywhere, give up.
1550 if (!method) {
1551 Diag(forLoc, diag::warn_collection_expr_type)
1552 << collection->getType() << selector << collection->getSourceRange();
1553 }
1554
1555 // TODO: check for an incompatible signature?
1556 }
1557
1558 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001559 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001560}
1561
John McCall60d7b3a2010-08-24 06:29:42 +00001562StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001563Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001564 Stmt *First, Expr *collection,
1565 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001566
1567 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001568 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001569
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001570 if (First) {
1571 QualType FirstType;
1572 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001573 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001574 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1575 diag::err_toomany_element_decls));
1576
Douglas Gregor12849d02013-04-08 20:52:24 +00001577 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1578 if (!D || D->isInvalidDecl())
1579 return StmtError();
1580
John McCallf85e1932011-06-15 23:02:42 +00001581 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001582 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1583 // declare identifiers for objects having storage class 'auto' or
1584 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001585 if (!D->hasLocalStorage())
1586 return StmtError(Diag(D->getLocation(),
Douglas Gregor12849d02013-04-08 20:52:24 +00001587 diag::err_non_local_variable_decl_in_for));
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001588
1589 // If the type contained 'auto', deduce the 'auto' to 'id'.
1590 if (FirstType->getContainedAutoType()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001591 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1592 VK_RValue);
1593 Expr *DeducedInit = &OpaqueId;
Richard Smith9b131752013-04-30 21:23:01 +00001594 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1595 DAR_Failed)
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001596 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith9b131752013-04-30 21:23:01 +00001597 if (FirstType.isNull()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001598 D->setInvalidDecl();
1599 return StmtError();
1600 }
1601
Richard Smith9b131752013-04-30 21:23:01 +00001602 D->setType(FirstType);
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001603
1604 if (ActiveTemplateInstantiations.empty()) {
Richard Smith9b131752013-04-30 21:23:01 +00001605 SourceLocation Loc =
1606 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001607 Diag(Loc, diag::warn_auto_var_is_id)
1608 << D->getDeclName();
1609 }
1610 }
1611
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001612 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001613 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001614 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001615 return StmtError(Diag(First->getLocStart(),
1616 diag::err_selector_element_not_lvalue)
1617 << First->getSourceRange());
1618
Mike Stump1eb44332009-09-09 15:08:12 +00001619 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001620 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001621 if (!FirstType->isDependentType() &&
1622 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001623 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001624 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1625 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001626 }
Chad Rosier1093f492012-08-10 17:56:09 +00001627
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001628 if (CollectionExprResult.isInvalid())
1629 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001630
Richard Smith41956372013-01-14 22:39:08 +00001631 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1632 if (CollectionExprResult.isInvalid())
1633 return StmtError();
1634
Chad Rosier1093f492012-08-10 17:56:09 +00001635 return Owned(new (Context) ObjCForCollectionStmt(First,
1636 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001637 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001638}
Reid Spencer5f016e22007-07-11 17:01:13 +00001639
Richard Smithad762fc2011-04-14 22:09:26 +00001640/// Finish building a variable declaration for a for-range statement.
1641/// \return true if an error occurs.
1642static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith9b131752013-04-30 21:23:01 +00001643 SourceLocation Loc, int DiagID) {
Richard Smithad762fc2011-04-14 22:09:26 +00001644 // Deduce the type for the iterator variable now rather than leaving it to
1645 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith9b131752013-04-30 21:23:01 +00001646 QualType InitType;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001647 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith9b131752013-04-30 21:23:01 +00001648 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001649 Sema::DAR_Failed)
Richard Smith9b131752013-04-30 21:23:01 +00001650 SemaRef.Diag(Loc, DiagID) << Init->getType();
1651 if (InitType.isNull()) {
Richard Smithad762fc2011-04-14 22:09:26 +00001652 Decl->setInvalidDecl();
1653 return true;
1654 }
Richard Smith9b131752013-04-30 21:23:01 +00001655 Decl->setType(InitType);
Richard Smithad762fc2011-04-14 22:09:26 +00001656
John McCallf85e1932011-06-15 23:02:42 +00001657 // In ARC, infer lifetime.
1658 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1659 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001660 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001661 SemaRef.inferObjCARCLifetime(Decl))
1662 Decl->setInvalidDecl();
1663
Richard Smithad762fc2011-04-14 22:09:26 +00001664 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1665 /*TypeMayContainAuto=*/false);
1666 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001667 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001668 return false;
1669}
1670
Sam Panzere1715b62012-08-21 00:52:01 +00001671namespace {
1672
Richard Smithad762fc2011-04-14 22:09:26 +00001673/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001674/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001675/// nor from the diagnostics produced when analysing the implicit expressions
1676/// required in a for-range statement.
1677void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001678 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001679 CallExpr *CE = dyn_cast<CallExpr>(E);
1680 if (!CE)
1681 return;
1682 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1683 if (!D)
1684 return;
1685 SourceLocation Loc = D->getLocation();
1686
1687 std::string Description;
1688 bool IsTemplate = false;
1689 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1690 Description = SemaRef.getTemplateArgumentBindingsText(
1691 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1692 IsTemplate = true;
1693 }
1694
1695 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1696 << BEF << IsTemplate << Description << E->getType();
1697}
1698
Sam Panzere1715b62012-08-21 00:52:01 +00001699/// Build a variable declaration for a for-range statement.
1700VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1701 QualType Type, const char *Name) {
1702 DeclContext *DC = SemaRef.CurContext;
1703 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1704 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1705 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001706 TInfo, SC_None);
Sam Panzere1715b62012-08-21 00:52:01 +00001707 Decl->setImplicit();
1708 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001709}
1710
1711}
1712
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001713static bool ObjCEnumerationCollection(Expr *Collection) {
1714 return !Collection->isTypeDependent()
1715 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1716}
1717
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001718/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001719///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001720/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001721/// A range-based for statement is equivalent to
1722///
1723/// {
1724/// auto && __range = range-init;
1725/// for ( auto __begin = begin-expr,
1726/// __end = end-expr;
1727/// __begin != __end;
1728/// ++__begin ) {
1729/// for-range-declaration = *__begin;
1730/// statement
1731/// }
1732/// }
1733///
1734/// The body of the loop is not available yet, since it cannot be analysed until
1735/// we have determined the type of the for-range-declaration.
1736StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001737Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001738 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001739 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001740 if (!First || !Range)
1741 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001742
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001743 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001744 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001745
1746 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1747 assert(DS && "first part of for range not a decl stmt");
1748
1749 if (!DS->isSingleDecl()) {
1750 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1751 return StmtError();
1752 }
1753 if (DS->getSingleDecl()->isInvalidDecl())
1754 return StmtError();
1755
1756 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1757 return StmtError();
1758
1759 // Build auto && __range = range-init
1760 SourceLocation RangeLoc = Range->getLocStart();
1761 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1762 Context.getAutoRRefDeductType(),
1763 "__range");
1764 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1765 diag::err_for_range_deduction_failure))
1766 return StmtError();
1767
1768 // Claim the type doesn't contain auto: we've already done the checking.
1769 DeclGroupPtrTy RangeGroup =
1770 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1771 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1772 if (RangeDecl.isInvalid())
1773 return StmtError();
1774
1775 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1776 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001777 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001778}
1779
1780/// \brief Create the initialization, compare, and increment steps for
1781/// the range-based for loop expression.
1782/// This function does not handle array-based for loops,
1783/// which are created in Sema::BuildCXXForRangeStmt.
1784///
1785/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1786/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1787/// CandidateSet and BEF are set and some non-success value is returned on
1788/// failure.
1789static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1790 Expr *BeginRange, Expr *EndRange,
1791 QualType RangeType,
1792 VarDecl *BeginVar,
1793 VarDecl *EndVar,
1794 SourceLocation ColonLoc,
1795 OverloadCandidateSet *CandidateSet,
1796 ExprResult *BeginExpr,
1797 ExprResult *EndExpr,
1798 Sema::BeginEndFunction *BEF) {
1799 DeclarationNameInfo BeginNameInfo(
1800 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1801 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1802 ColonLoc);
1803
1804 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1805 Sema::LookupMemberName);
1806 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1807
1808 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1809 // - if _RangeT is a class type, the unqualified-ids begin and end are
1810 // looked up in the scope of class _RangeT as if by class member access
1811 // lookup (3.4.5), and if either (or both) finds at least one
1812 // declaration, begin-expr and end-expr are __range.begin() and
1813 // __range.end(), respectively;
1814 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1815 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1816
1817 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1818 SourceLocation RangeLoc = BeginVar->getLocation();
1819 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1820
1821 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1822 << RangeLoc << BeginRange->getType() << *BEF;
1823 return Sema::FRS_DiagnosticIssued;
1824 }
1825 } else {
1826 // - otherwise, begin-expr and end-expr are begin(__range) and
1827 // end(__range), respectively, where begin and end are looked up with
1828 // argument-dependent lookup (3.4.2). For the purposes of this name
1829 // lookup, namespace std is an associated namespace.
1830
1831 }
1832
1833 *BEF = Sema::BEF_begin;
1834 Sema::ForRangeStatus RangeStatus =
1835 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1836 Sema::BEF_begin, BeginNameInfo,
1837 BeginMemberLookup, CandidateSet,
1838 BeginRange, BeginExpr);
1839
1840 if (RangeStatus != Sema::FRS_Success)
1841 return RangeStatus;
1842 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1843 diag::err_for_range_iter_deduction_failure)) {
1844 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1845 return Sema::FRS_DiagnosticIssued;
1846 }
1847
1848 *BEF = Sema::BEF_end;
1849 RangeStatus =
1850 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1851 Sema::BEF_end, EndNameInfo,
1852 EndMemberLookup, CandidateSet,
1853 EndRange, EndExpr);
1854 if (RangeStatus != Sema::FRS_Success)
1855 return RangeStatus;
1856 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1857 diag::err_for_range_iter_deduction_failure)) {
1858 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1859 return Sema::FRS_DiagnosticIssued;
1860 }
1861 return Sema::FRS_Success;
1862}
1863
1864/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001865/// If the attempt fails, this function will return a valid, null StmtResult
1866/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001867static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1868 SourceLocation ForLoc,
1869 Stmt *LoopVarDecl,
1870 SourceLocation ColonLoc,
1871 Expr *Range,
1872 SourceLocation RangeLoc,
1873 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001874 // Determine whether we can rebuild the for-range statement with a
1875 // dereferenced range expression.
1876 ExprResult AdjustedRange;
1877 {
1878 Sema::SFINAETrap Trap(SemaRef);
1879
1880 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1881 if (AdjustedRange.isInvalid())
1882 return StmtResult();
1883
1884 StmtResult SR =
1885 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1886 AdjustedRange.get(), RParenLoc,
1887 Sema::BFRK_Check);
1888 if (SR.isInvalid())
1889 return StmtResult();
1890 }
1891
1892 // The attempt to dereference worked well enough that it could produce a valid
1893 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1894 // case there are any other (non-fatal) problems with it.
1895 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1896 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1897 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1898 AdjustedRange.get(), RParenLoc,
1899 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001900}
1901
Richard Smith8b533d92012-09-20 21:52:32 +00001902/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001903StmtResult
1904Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1905 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1906 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001907 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001908 Scope *S = getCurScope();
1909
1910 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1911 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1912 QualType RangeVarType = RangeVar->getType();
1913
1914 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1915 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1916
1917 StmtResult BeginEndDecl = BeginEnd;
1918 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1919
Richard Smithdc7a4f52013-04-30 13:56:41 +00001920 if (RangeVarType->isDependentType()) {
1921 // The range is implicitly used as a placeholder when it is dependent.
1922 RangeVar->setUsed();
1923
1924 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
1925 // them in properly when we instantiate the loop.
1926 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
1927 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
1928 } else if (!BeginEndDecl.get()) {
Richard Smithad762fc2011-04-14 22:09:26 +00001929 SourceLocation RangeLoc = RangeVar->getLocation();
1930
Ted Kremeneke50b0152011-10-10 22:36:28 +00001931 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1932
1933 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1934 VK_LValue, ColonLoc);
1935 if (BeginRangeRef.isInvalid())
1936 return StmtError();
1937
1938 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1939 VK_LValue, ColonLoc);
1940 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001941 return StmtError();
1942
1943 QualType AutoType = Context.getAutoDeductType();
1944 Expr *Range = RangeVar->getInit();
1945 if (!Range)
1946 return StmtError();
1947 QualType RangeType = Range->getType();
1948
1949 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001950 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001951 return StmtError();
1952
1953 // Build auto __begin = begin-expr, __end = end-expr.
1954 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1955 "__begin");
1956 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1957 "__end");
1958
1959 // Build begin-expr and end-expr and attach to __begin and __end variables.
1960 ExprResult BeginExpr, EndExpr;
1961 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1962 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1963 // __range + __bound, respectively, where __bound is the array bound. If
1964 // _RangeT is an array of unknown size or an array of incomplete type,
1965 // the program is ill-formed;
1966
1967 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001968 BeginExpr = BeginRangeRef;
1969 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001970 diag::err_for_range_iter_deduction_failure)) {
1971 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1972 return StmtError();
1973 }
1974
1975 // Find the array bound.
1976 ExprResult BoundExpr;
1977 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1978 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001979 Context.getPointerDiffType(),
1980 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001981 else if (const VariableArrayType *VAT =
1982 dyn_cast<VariableArrayType>(UnqAT))
Richard Smith39b0e262013-04-20 23:28:26 +00001983 // FIXME: Need to build an OpaqueValueExpr for this rather than
1984 // recomputing it!
Richard Smithad762fc2011-04-14 22:09:26 +00001985 BoundExpr = VAT->getSizeExpr();
1986 else {
1987 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1988 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001989 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001990 }
1991
1992 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001993 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001994 BoundExpr.get());
1995 if (EndExpr.isInvalid())
1996 return StmtError();
1997 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1998 diag::err_for_range_iter_deduction_failure)) {
1999 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2000 return StmtError();
2001 }
2002 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00002003 OverloadCandidateSet CandidateSet(RangeLoc);
2004 Sema::BeginEndFunction BEFFailure;
2005 ForRangeStatus RangeStatus =
2006 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2007 EndRangeRef.get(), RangeType,
2008 BeginVar, EndVar, ColonLoc, &CandidateSet,
2009 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00002010
Sam Panzere1715b62012-08-21 00:52:01 +00002011 // If building the range failed, try dereferencing the range expression
2012 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00002013 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00002014 BEFFailure == BEF_begin) {
2015 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2016 LoopVarDecl, ColonLoc,
2017 Range, RangeLoc,
2018 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00002019 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00002020 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00002021 }
2022
Sam Panzere1715b62012-08-21 00:52:01 +00002023 // Otherwise, emit diagnostics if we haven't already.
2024 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00002025 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00002026 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2027 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00002028 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00002029 }
2030 // Return an error if no fix was discovered.
2031 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00002032 return StmtError();
2033 }
2034
Sam Panzere1715b62012-08-21 00:52:01 +00002035 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2036 "invalid range expression in for loop");
2037
2038 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00002039 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2040 if (!Context.hasSameType(BeginType, EndType)) {
2041 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2042 << BeginType << EndType;
2043 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2044 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2045 }
2046
2047 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2048 // Claim the type doesn't contain auto: we've already done the checking.
2049 DeclGroupPtrTy BeginEndGroup =
2050 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
2051 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2052
Ted Kremeneke50b0152011-10-10 22:36:28 +00002053 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2054 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00002055 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002056 if (BeginRef.isInvalid())
2057 return StmtError();
2058
Richard Smithad762fc2011-04-14 22:09:26 +00002059 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2060 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002061 if (EndRef.isInvalid())
2062 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00002063
2064 // Build and check __begin != __end expression.
2065 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2066 BeginRef.get(), EndRef.get());
2067 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2068 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2069 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002070 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2071 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002072 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2073 if (!Context.hasSameType(BeginType, EndType))
2074 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2075 return StmtError();
2076 }
2077
2078 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002079 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2080 VK_LValue, ColonLoc);
2081 if (BeginRef.isInvalid())
2082 return StmtError();
2083
Richard Smithad762fc2011-04-14 22:09:26 +00002084 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2085 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2086 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002087 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2088 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002089 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2090 return StmtError();
2091 }
2092
2093 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002094 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2095 VK_LValue, ColonLoc);
2096 if (BeginRef.isInvalid())
2097 return StmtError();
2098
Richard Smithad762fc2011-04-14 22:09:26 +00002099 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2100 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002101 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2102 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002103 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2104 return StmtError();
2105 }
2106
Richard Smith8b533d92012-09-20 21:52:32 +00002107 // Attach *__begin as initializer for VD. Don't touch it if we're just
2108 // trying to determine whether this would be a valid range.
2109 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002110 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2111 /*TypeMayContainAuto=*/true);
2112 if (LoopVar->isInvalidDecl())
2113 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2114 }
2115 }
2116
Richard Smith8b533d92012-09-20 21:52:32 +00002117 // Don't bother to actually allocate the result if we're just trying to
2118 // determine whether it would be valid.
2119 if (Kind == BFRK_Check)
2120 return StmtResult();
2121
Richard Smithad762fc2011-04-14 22:09:26 +00002122 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2123 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2124 NotEqExpr.take(), IncrExpr.take(),
2125 LoopVarDS, /*Body=*/0, ForLoc,
2126 ColonLoc, RParenLoc));
2127}
2128
Chad Rosier1093f492012-08-10 17:56:09 +00002129/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002130/// statement.
2131StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2132 if (!S || !B)
2133 return StmtError();
2134 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002135
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002136 ForStmt->setBody(B);
2137 return S;
2138}
2139
Richard Smithad762fc2011-04-14 22:09:26 +00002140/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2141/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2142/// body cannot be performed until after the type of the range variable is
2143/// determined.
2144StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2145 if (!S || !B)
2146 return StmtError();
2147
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002148 if (isa<ObjCForCollectionStmt>(S))
2149 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002150
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002151 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2152 ForStmt->setBody(B);
2153
2154 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2155 diag::warn_empty_range_based_for_body);
2156
Richard Smithad762fc2011-04-14 22:09:26 +00002157 return S;
2158}
2159
Chris Lattner57ad3782011-02-17 20:34:02 +00002160StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2161 SourceLocation LabelLoc,
2162 LabelDecl *TheDecl) {
2163 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002164 TheDecl->setUsed();
2165 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002166}
2167
John McCall60d7b3a2010-08-24 06:29:42 +00002168StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002169Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002170 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002171 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002172 if (!E->isTypeDependent()) {
2173 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002174 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002175 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002176 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002177 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2178 if (ExprRes.isInvalid())
2179 return StmtError();
2180 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002181 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002182 return StmtError();
2183 }
John McCallb60a77e2010-08-01 00:26:45 +00002184
Richard Smith41956372013-01-14 22:39:08 +00002185 ExprResult ExprRes = ActOnFinishFullExpr(E);
2186 if (ExprRes.isInvalid())
2187 return StmtError();
2188 E = ExprRes.take();
2189
John McCall781472f2010-08-25 08:40:02 +00002190 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002191
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002192 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002193}
2194
John McCall60d7b3a2010-08-24 06:29:42 +00002195StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002196Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002197 Scope *S = CurScope->getContinueParent();
2198 if (!S) {
2199 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002200 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002202
Ted Kremenek8189cde2009-02-07 01:47:29 +00002203 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002204}
2205
John McCall60d7b3a2010-08-24 06:29:42 +00002206StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002207Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 Scope *S = CurScope->getBreakParent();
2209 if (!S) {
2210 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002211 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002213
Ted Kremenek8189cde2009-02-07 01:47:29 +00002214 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002215}
2216
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002217/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002218/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002219///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002220/// \param ReturnType If we're determining the copy elision candidate for
2221/// a return statement, this is the return type of the function. If we're
2222/// determining the copy elision candidate for a throw expression, this will
2223/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002224///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002225/// \param E The expression being returned from the function or block, or
2226/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002227///
Douglas Gregor4926d832011-05-20 15:00:53 +00002228/// \param AllowFunctionParameter Whether we allow function parameters to
2229/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2230/// we re-use this logic to determine whether we should try to move as part of
2231/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002232///
2233/// \returns The NRVO candidate variable, if the return statement may use the
2234/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002235const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2236 Expr *E,
2237 bool AllowFunctionParameter) {
2238 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002239 // - in a return statement in a function with ...
2240 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002241 if (!ReturnType.isNull()) {
2242 if (!ReturnType->isRecordType())
2243 return 0;
2244 // ... the same cv-unqualified type as the function return type ...
2245 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2246 return 0;
2247 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002248
2249 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002250 // (other than a function or catch-clause parameter)) ...
2251 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002252 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002253 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002254 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2255 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002256 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002257
John McCall1cd76e82011-11-11 03:57:31 +00002258 // ...object (other than a function or catch-clause parameter)...
2259 if (VD->getKind() != Decl::Var &&
2260 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2261 return 0;
2262 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263
John McCall1cd76e82011-11-11 03:57:31 +00002264 // ...automatic...
2265 if (!VD->hasLocalStorage()) return 0;
2266
2267 // ...non-volatile...
2268 if (VD->getType().isVolatileQualified()) return 0;
2269 if (VD->getType()->isReferenceType()) return 0;
2270
2271 // __block variables can't be allocated in a way that permits NRVO.
2272 if (VD->hasAttr<BlocksAttr>()) return 0;
2273
2274 // Variables with higher required alignment than their type's ABI
2275 // alignment cannot use NRVO.
2276 if (VD->hasAttr<AlignedAttr>() &&
2277 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2278 return 0;
2279
2280 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002281}
2282
Douglas Gregor07f402c2011-01-21 21:08:57 +00002283/// \brief Perform the initialization of a potentially-movable value, which
2284/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002285///
2286/// This routine implements C++0x [class.copy]p33, which attempts to treat
2287/// returned lvalues as rvalues in certain cases (to prefer move construction),
2288/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002289ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002290Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2291 const VarDecl *NRVOCandidate,
2292 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002293 Expr *Value,
2294 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002295 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002296 // When the criteria for elision of a copy operation are met or would
2297 // be met save for the fact that the source object is a function
2298 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002299 // overload resolution to select the constructor for the copy is first
2300 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002301 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002302 if (AllowNRVO &&
2303 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002304 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002305 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002306
Douglas Gregorcc15f012011-01-21 19:38:21 +00002307 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002308 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002309 = InitializationKind::CreateCopy(Value->getLocStart(),
2310 Value->getLocStart());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002311 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002312
2313 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002314 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002315 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002316 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002317 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002318 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2319 StepEnd = Seq.step_end();
2320 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002321 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002322 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002323
2324 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002325 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002326
Douglas Gregorcc15f012011-01-21 19:38:21 +00002327 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002328 = Constructor->getParamDecl(0)->getType()
2329 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002330
Douglas Gregorcc15f012011-01-21 19:38:21 +00002331 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002332 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002333 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2334 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002335 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002336
Douglas Gregorcc15f012011-01-21 19:38:21 +00002337 // Promote "AsRvalue" to the heap, since we now need this
2338 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002339 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002340 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341
Douglas Gregorcc15f012011-01-21 19:38:21 +00002342 // Complete type-checking the initialization of the return type
2343 // using the constructor we found.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002344 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorcc15f012011-01-21 19:38:21 +00002345 }
2346 }
2347 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002348
Douglas Gregorcc15f012011-01-21 19:38:21 +00002349 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002350 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002351 // (again) now with the return value expression as written.
2352 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002353 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002354
Douglas Gregorcc15f012011-01-21 19:38:21 +00002355 return Res;
2356}
2357
Eli Friedman84b007f2012-01-26 03:00:14 +00002358/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2359/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002360///
John McCall60d7b3a2010-08-24 06:29:42 +00002361StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002362Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2363 // If this is the first return we've seen, infer the return type.
Richard Smithf45c2992013-05-12 03:09:35 +00002364 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman84b007f2012-01-26 03:00:14 +00002365 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002366 QualType FnRetType = CurCap->ReturnType;
2367
2368 // For blocks/lambdas with implicit return types, we check each return
2369 // statement individually, and deduce the common return type when the block
2370 // or lambda is completed.
Richard Smithf45c2992013-05-12 03:09:35 +00002371 if (AutoType *AT =
2372 FnRetType.isNull() ? 0 : FnRetType->getContainedAutoType()) {
2373 // In C++1y, the return type may involve 'auto'.
2374 FunctionDecl *FD = cast<LambdaScopeInfo>(CurCap)->CallOperator;
2375 if (CurContext->isDependentContext()) {
2376 // C++1y [dcl.spec.auto]p12:
2377 // Return type deduction [...] occurs when the definition is
2378 // instantiated even if the function body contains a return
2379 // statement with a non-type-dependent operand.
2380 CurCap->ReturnType = FnRetType = Context.DependentTy;
2381 } else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2382 FD->setInvalidDecl();
2383 return StmtError();
2384 } else
2385 CurCap->ReturnType = FnRetType = FD->getResultType();
2386 } else if (CurCap->HasImplicitReturnType) {
2387 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregora0c2b212012-02-09 18:40:39 +00002388 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002389 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2390 if (Result.isInvalid())
2391 return StmtError();
2392 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002393
Richard Smithf45c2992013-05-12 03:09:35 +00002394 if (!CurContext->isDependentContext())
Jordan Rose7dd900e2012-07-02 21:19:23 +00002395 FnRetType = RetValExp->getType();
2396 else
2397 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002398 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002399 if (RetValExp) {
2400 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2401 // initializer list, because it is not an expression (even
2402 // though we represent it as one). We still deduce 'void'.
2403 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2404 << RetValExp->getSourceRange();
2405 }
2406
Jordan Rose7dd900e2012-07-02 21:19:23 +00002407 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002408 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002409
2410 // Although we'll properly infer the type of the block once it's completed,
2411 // make sure we provide a return type now for better error recovery.
2412 if (CurCap->ReturnType.isNull())
2413 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002414 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002415 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002416
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002417 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002418 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2419 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2420 return StmtError();
2421 }
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00002422 } else if (CapturedRegionScopeInfo *CurRegion =
2423 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2424 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2425 return StmtError();
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002426 } else {
2427 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2428 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2429 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2430 return StmtError();
2431 }
2432 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002433
Steve Naroff4eb206b2008-09-03 18:15:37 +00002434 // Otherwise, verify that this result type matches the previous one. We are
2435 // pickier with blocks than for normal functions because we don't have GCC
2436 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002437 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002438 if (FnRetType->isDependentType()) {
2439 // Delay processing for now. TODO: there are lots of dependent
2440 // types we can conclusively prove aren't void.
2441 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002442 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002443 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002444 (RetValExp->isTypeDependent() ||
2445 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002446 if (!getLangOpts().CPlusPlus &&
2447 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002448 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002449 else {
2450 Diag(ReturnLoc, diag::err_return_block_has_expr);
2451 RetValExp = 0;
2452 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002453 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002454 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002455 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2456 } else if (!RetValExp->isTypeDependent()) {
2457 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002458
John McCall0a7efe12011-08-17 22:09:46 +00002459 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2460 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2461 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002462
John McCall0a7efe12011-08-17 22:09:46 +00002463 // In C++ the return statement is handled via a copy initialization.
2464 // the C version of which boils down to CheckSingleAssignmentConstraints.
2465 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2466 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2467 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002468 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002469 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2470 FnRetType, RetValExp);
2471 if (Res.isInvalid()) {
2472 // FIXME: Cleanup temporaries here, anyway?
2473 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002474 }
John McCall0a7efe12011-08-17 22:09:46 +00002475 RetValExp = Res.take();
2476 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002477 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002478
John McCalld963c372011-08-17 21:34:14 +00002479 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002480 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2481 if (ER.isInvalid())
2482 return StmtError();
2483 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002484 }
John McCall0a7efe12011-08-17 22:09:46 +00002485 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2486 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002487
Jordan Rose7dd900e2012-07-02 21:19:23 +00002488 // If we need to check for the named return value optimization,
2489 // or if we need to infer the return type,
2490 // save the return statement in our scope for later processing.
2491 if (CurCap->HasImplicitReturnType ||
2492 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2493 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002494 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002495
Douglas Gregor5077c382010-05-15 06:01:05 +00002496 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002497}
Reid Spencer5f016e22007-07-11 17:01:13 +00002498
Richard Smith60e141e2013-05-04 07:00:32 +00002499/// Deduce the return type for a function from a returned expression, per
2500/// C++1y [dcl.spec.auto]p6.
2501bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2502 SourceLocation ReturnLoc,
2503 Expr *&RetExpr,
2504 AutoType *AT) {
2505 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
2506 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
2507 QualType Deduced;
2508
2509 if (RetExpr) {
2510 // If the deduction is for a return statement and the initializer is
2511 // a braced-init-list, the program is ill-formed.
2512 if (isa<InitListExpr>(RetExpr)) {
2513 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2514 return true;
2515 }
2516
2517 // Otherwise, [...] deduce a value for U using the rules of template
2518 // argument deduction.
2519 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2520
2521 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2522 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2523 << OrigResultType.getType() << RetExpr->getType();
2524
2525 if (DAR != DAR_Succeeded)
2526 return true;
2527 } else {
2528 // In the case of a return with no operand, the initializer is considered
2529 // to be void().
2530 //
2531 // Deduction here can only succeed if the return type is exactly 'cv auto'
2532 // or 'decltype(auto)', so just check for that case directly.
2533 if (!OrigResultType.getType()->getAs<AutoType>()) {
2534 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2535 << OrigResultType.getType();
2536 return true;
2537 }
2538 // We always deduce U = void in this case.
2539 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2540 if (Deduced.isNull())
2541 return true;
2542 }
2543
2544 // If a function with a declared return type that contains a placeholder type
2545 // has multiple return statements, the return type is deduced for each return
2546 // statement. [...] if the type deduced is not the same in each deduction,
2547 // the program is ill-formed.
2548 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2549 AutoType *NewAT = Deduced->getContainedAutoType();
2550 if (!Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2551 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2552 << (AT->isDecltypeAuto() ? 1 : 0)
2553 << NewAT->getDeducedType() << AT->getDeducedType();
2554 return true;
2555 }
2556 } else if (!FD->isInvalidDecl()) {
2557 // Update all declarations of the function to have the deduced return type.
2558 Context.adjustDeducedFunctionResultType(FD, Deduced);
2559 }
2560
2561 return false;
2562}
2563
John McCall60d7b3a2010-08-24 06:29:42 +00002564StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002565Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002566 // Check for unexpanded parameter packs.
2567 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2568 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002569
Eli Friedman84b007f2012-01-26 03:00:14 +00002570 if (isa<CapturingScopeInfo>(getCurFunction()))
2571 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002572
Chris Lattner371f2582008-12-04 23:50:19 +00002573 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002574 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002575 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002576 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002577 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002578 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002579 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002580 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002581 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002582 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2583 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002584 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002585 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002586 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2587 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002588 }
2589 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002590 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Richard Smith60e141e2013-05-04 07:00:32 +00002592 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2593 // deduction.
2594 bool HasDependentReturnType = FnRetType->isDependentType();
2595 if (getLangOpts().CPlusPlus1y) {
2596 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2597 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2598 if (CurContext->isDependentContext())
2599 HasDependentReturnType = true;
2600 else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2601 FD->setInvalidDecl();
2602 return StmtError();
2603 } else {
2604 FnRetType = FD->getResultType();
2605 }
2606 }
2607 }
2608
Douglas Gregor5077c382010-05-15 06:01:05 +00002609 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002610 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002611 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002612 if (isa<InitListExpr>(RetValExp)) {
2613 // We simply never allow init lists as the return value of void
2614 // functions. This is compatible because this was never allowed before,
2615 // so there's no legacy code to deal with.
2616 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2617 int FunctionKind = 0;
2618 if (isa<ObjCMethodDecl>(CurDecl))
2619 FunctionKind = 1;
2620 else if (isa<CXXConstructorDecl>(CurDecl))
2621 FunctionKind = 2;
2622 else if (isa<CXXDestructorDecl>(CurDecl))
2623 FunctionKind = 3;
2624
2625 Diag(ReturnLoc, diag::err_return_init_list)
2626 << CurDecl->getDeclName() << FunctionKind
2627 << RetValExp->getSourceRange();
2628
2629 // Drop the expression.
2630 RetValExp = 0;
2631 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002632 // C99 6.8.6.4p1 (ext_ since GCC warns)
2633 unsigned D = diag::ext_return_has_expr;
2634 if (RetValExp->getType()->isVoidType())
2635 D = diag::ext_return_has_void_expr;
2636 else {
2637 ExprResult Result = Owned(RetValExp);
2638 Result = IgnoredValueConversions(Result.take());
2639 if (Result.isInvalid())
2640 return StmtError();
2641 RetValExp = Result.take();
2642 RetValExp = ImpCastExprToType(RetValExp,
2643 Context.VoidTy, CK_ToVoid).take();
2644 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002645
Nick Lewycky8d794612011-06-01 07:44:31 +00002646 // return (some void expression); is legal in C++.
2647 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002648 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002649 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002650
2651 int FunctionKind = 0;
2652 if (isa<ObjCMethodDecl>(CurDecl))
2653 FunctionKind = 1;
2654 else if (isa<CXXConstructorDecl>(CurDecl))
2655 FunctionKind = 2;
2656 else if (isa<CXXDestructorDecl>(CurDecl))
2657 FunctionKind = 3;
2658
Nick Lewycky8d794612011-06-01 07:44:31 +00002659 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002660 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002661 << RetValExp->getSourceRange();
2662 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002663 }
Mike Stump1eb44332009-09-09 15:08:12 +00002664
Sebastian Redl33deb352012-02-22 10:50:08 +00002665 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002666 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2667 if (ER.isInvalid())
2668 return StmtError();
2669 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002670 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002672
Douglas Gregor5077c382010-05-15 06:01:05 +00002673 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
Richard Smith60e141e2013-05-04 07:00:32 +00002674 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002675 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2676 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002677 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002678
2679 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002680 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002681 else
Chris Lattner08631c52008-11-23 21:45:46 +00002682 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002683 Result = new (Context) ReturnStmt(ReturnLoc);
2684 } else {
Richard Smith60e141e2013-05-04 07:00:32 +00002685 assert(RetValExp || HasDependentReturnType);
Douglas Gregor5077c382010-05-15 06:01:05 +00002686 const VarDecl *NRVOCandidate = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00002687 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor5077c382010-05-15 06:01:05 +00002688 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002689
John McCall7cca8212013-03-19 07:04:25 +00002690 QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
Eli Friedman38ac2432012-03-30 01:13:43 +00002691
Douglas Gregor5077c382010-05-15 06:01:05 +00002692 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2693 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2694 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002695
John McCall856d3792011-06-16 23:24:51 +00002696 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002697 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002698 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall7cca8212013-03-19 07:04:25 +00002700 RetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002701 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall7cca8212013-03-19 07:04:25 +00002703 RetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002704 if (Res.isInvalid()) {
John McCall7cca8212013-03-19 07:04:25 +00002705 // FIXME: Clean up temporaries here anyway?
Douglas Gregor5077c382010-05-15 06:01:05 +00002706 return StmtError();
2707 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002708 RetValExp = Res.takeAs<Expr>();
John McCall7cca8212013-03-19 07:04:25 +00002709
2710 // If we have a related result type, we need to implicitly
2711 // convert back to the formal result type. We can't pretend to
2712 // initialize the result again --- we might end double-retaining
2713 // --- so instead we initialize a notional temporary; this can
2714 // lead to less-than-great diagnostics, but this stage is much
2715 // less likely to fail than the previous stage.
2716 if (!RelatedRetType.isNull()) {
2717 Entity = InitializedEntity::InitializeTemporary(FnRetType);
2718 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
2719 if (Res.isInvalid()) {
2720 // FIXME: Clean up temporaries here anyway?
2721 return StmtError();
2722 }
2723 RetValExp = Res.takeAs<Expr>();
2724 }
2725
2726 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002728
John McCallb4eb64d2010-10-08 02:01:28 +00002729 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002730 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2731 if (ER.isInvalid())
2732 return StmtError();
2733 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002734 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002735 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002737
2738 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002739 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002740 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002741 !CurContext->isDependentContext())
2742 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002743
Douglas Gregor5077c382010-05-15 06:01:05 +00002744 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002745}
2746
John McCall60d7b3a2010-08-24 06:29:42 +00002747StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002748Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002749 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002750 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002751 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002752 if (Var && Var->isInvalidDecl())
2753 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002754
John McCall9ae2f072010-08-23 23:25:46 +00002755 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002756}
2757
John McCall60d7b3a2010-08-24 06:29:42 +00002758StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002759Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2760 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002761}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002762
John McCall60d7b3a2010-08-24 06:29:42 +00002763StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002764Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002765 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002766 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002767 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2768
John McCall781472f2010-08-25 08:40:02 +00002769 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002770 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002771 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002772 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002773 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002774 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002775}
2776
John McCalld1376ee2012-05-08 21:41:25 +00002777StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002778 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002779 ExprResult Result = DefaultLvalueConversion(Throw);
2780 if (Result.isInvalid())
2781 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002782
Richard Smith41956372013-01-14 22:39:08 +00002783 Result = ActOnFinishFullExpr(Result.take());
2784 if (Result.isInvalid())
2785 return StmtError();
2786 Throw = Result.take();
2787
Douglas Gregord1377b22010-04-22 21:44:01 +00002788 QualType ThrowType = Throw->getType();
2789 // Make sure the expression type is an ObjC pointer or "void *".
2790 if (!ThrowType->isDependentType() &&
2791 !ThrowType->isObjCObjectPointerType()) {
2792 const PointerType *PT = ThrowType->getAs<PointerType>();
2793 if (!PT || !PT->getPointeeType()->isVoidType())
2794 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2795 << Throw->getType() << Throw->getSourceRange());
2796 }
2797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002798
John McCall9ae2f072010-08-23 23:25:46 +00002799 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002800}
2801
John McCall60d7b3a2010-08-24 06:29:42 +00002802StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002803Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002804 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002805 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002806 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2807
John McCall9ae2f072010-08-23 23:25:46 +00002808 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002809 // @throw without an expression designates a rethrow (which much occur
2810 // in the context of an @catch clause).
2811 Scope *AtCatchParent = CurScope;
2812 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2813 AtCatchParent = AtCatchParent->getParent();
2814 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002815 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002816 }
John McCall9ae2f072010-08-23 23:25:46 +00002817 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002818}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002819
John McCall07524032011-07-27 21:50:02 +00002820ExprResult
2821Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2822 ExprResult result = DefaultLvalueConversion(operand);
2823 if (result.isInvalid())
2824 return ExprError();
2825 operand = result.take();
2826
2827 // Make sure the expression type is an ObjC pointer or "void *".
2828 QualType type = operand->getType();
2829 if (!type->isDependentType() &&
2830 !type->isObjCObjectPointerType()) {
2831 const PointerType *pointerType = type->getAs<PointerType>();
2832 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2833 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2834 << type << operand->getSourceRange();
2835 }
2836
2837 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002838 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002839}
2840
John McCall60d7b3a2010-08-24 06:29:42 +00002841StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002842Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2843 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002844 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002845 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002846 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002847}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002848
2849/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2850/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002851StmtResult
John McCalld226f652010-08-21 09:40:31 +00002852Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002853 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002854 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002855 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002856 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002857 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002858}
Sebastian Redl8351da02008-12-22 21:35:02 +00002859
John McCallf85e1932011-06-15 23:02:42 +00002860StmtResult
2861Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2862 getCurFunction()->setHasBranchProtectedScope();
2863 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2864}
2865
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002866namespace {
2867
Sebastian Redlc447aba2009-07-29 17:15:45 +00002868class TypeWithHandler {
2869 QualType t;
2870 CXXCatchStmt *stmt;
2871public:
2872 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2873 : t(type), stmt(statement) {}
2874
John McCall0953e762009-09-24 19:53:00 +00002875 // An arbitrary order is fine as long as it places identical
2876 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002877 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002878 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002879 return true;
John McCall0953e762009-09-24 19:53:00 +00002880 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002881 return false;
2882 else
2883 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2884 }
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Sebastian Redlc447aba2009-07-29 17:15:45 +00002886 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002887 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002888 }
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Sebastian Redlc447aba2009-07-29 17:15:45 +00002890 CXXCatchStmt *getCatchStmt() const { return stmt; }
2891 SourceLocation getTypeSpecStartLoc() const {
2892 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2893 }
2894};
2895
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002896}
2897
Sebastian Redl8351da02008-12-22 21:35:02 +00002898/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2899/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002900StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002901Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002902 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002903 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002904 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002905 !getSourceManager().isInSystemHeader(TryLoc))
2906 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002907
Sebastian Redl8351da02008-12-22 21:35:02 +00002908 unsigned NumHandlers = RawHandlers.size();
2909 assert(NumHandlers > 0 &&
2910 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002911 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002912
Chris Lattner5f9e2722011-07-23 10:55:15 +00002913 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002914
2915 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002916 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002917 if (!Handler->getExceptionDecl()) {
2918 if (i < NumHandlers - 1)
2919 return StmtError(Diag(Handler->getLocStart(),
2920 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Sebastian Redlc447aba2009-07-29 17:15:45 +00002922 continue;
2923 }
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Sebastian Redlc447aba2009-07-29 17:15:45 +00002925 const QualType CaughtType = Handler->getCaughtType();
2926 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2927 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002928 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002929
2930 // Detect handlers for the same type as an earlier one.
2931 if (NumHandlers > 1) {
2932 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002933
Sebastian Redlc447aba2009-07-29 17:15:45 +00002934 TypeWithHandler prev = TypesWithHandlers[0];
2935 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2936 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Sebastian Redlc447aba2009-07-29 17:15:45 +00002938 if (curr == prev) {
2939 Diag(curr.getTypeSpecStartLoc(),
2940 diag::warn_exception_caught_by_earlier_handler)
2941 << curr.getCatchStmt()->getCaughtType().getAsString();
2942 Diag(prev.getTypeSpecStartLoc(),
2943 diag::note_previous_exception_handler)
2944 << prev.getCatchStmt()->getCaughtType().getAsString();
2945 }
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Sebastian Redlc447aba2009-07-29 17:15:45 +00002947 prev = curr;
2948 }
2949 }
Mike Stump1eb44332009-09-09 15:08:12 +00002950
John McCall781472f2010-08-25 08:40:02 +00002951 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002952
Sebastian Redl8351da02008-12-22 21:35:02 +00002953 // FIXME: We should detect handlers that cannot catch anything because an
2954 // earlier handler catches a superclass. Need to find a method that is not
2955 // quadratic for this.
2956 // Neither of these are explicitly forbidden, but every compiler detects them
2957 // and warns.
2958
John McCall9ae2f072010-08-23 23:25:46 +00002959 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002960 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002961}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002962
2963StmtResult
2964Sema::ActOnSEHTryBlock(bool IsCXXTry,
2965 SourceLocation TryLoc,
2966 Stmt *TryBlock,
2967 Stmt *Handler) {
2968 assert(TryBlock && Handler);
2969
2970 getCurFunction()->setHasBranchProtectedScope();
2971
2972 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2973}
2974
2975StmtResult
2976Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2977 Expr *FilterExpr,
2978 Stmt *Block) {
2979 assert(FilterExpr && Block);
2980
2981 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002982 return StmtError(Diag(FilterExpr->getExprLoc(),
2983 diag::err_filter_expression_integral)
2984 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002985 }
2986
2987 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2988}
2989
2990StmtResult
2991Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2992 Stmt *Block) {
2993 assert(Block);
2994 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2995}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002996
2997StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2998 bool IsIfExists,
2999 NestedNameSpecifierLoc QualifierLoc,
3000 DeclarationNameInfo NameInfo,
3001 Stmt *Nested)
3002{
3003 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003004 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003005 cast<CompoundStmt>(Nested));
3006}
3007
3008
Chad Rosier1093f492012-08-10 17:56:09 +00003009StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003010 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003011 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003012 UnqualifiedId &Name,
3013 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00003014 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003015 SS.getWithLocInContext(Context),
3016 GetNameFromUnqualifiedId(Name),
3017 Nested);
3018}
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003019
3020RecordDecl*
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003021Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3022 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003023 DeclContext *DC = CurContext;
3024 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3025 DC = DC->getParent();
3026
3027 RecordDecl *RD = 0;
3028 if (getLangOpts().CPlusPlus)
3029 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3030 else
3031 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3032
3033 DC->addDecl(RD);
3034 RD->setImplicit();
3035 RD->startDefinition();
3036
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003037 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003038 DC->addDecl(CD);
3039
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003040 // Build the context parameter
3041 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3042 DC = CapturedDecl::castToDeclContext(CD);
3043 IdentifierInfo *VarName = &Context.Idents.get("__context");
3044 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3045 ImplicitParamDecl *Param
3046 = ImplicitParamDecl::Create(Context, DC, Loc, VarName, ParamType);
3047 DC->addDecl(Param);
3048
3049 CD->setContextParam(Param);
3050
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003051 return RD;
3052}
3053
3054static void buildCapturedStmtCaptureList(
3055 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3056 SmallVectorImpl<Expr *> &CaptureInits,
3057 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3058
3059 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3060 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3061
3062 if (Cap->isThisCapture()) {
3063 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3064 CapturedStmt::VCK_This));
Richard Smith0d8e9642013-05-16 06:20:58 +00003065 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003066 continue;
3067 }
3068
3069 assert(Cap->isReferenceCapture() &&
3070 "non-reference capture not yet implemented");
3071
3072 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3073 CapturedStmt::VCK_ByRef,
3074 Cap->getVariable()));
Richard Smith0d8e9642013-05-16 06:20:58 +00003075 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003076 }
3077}
3078
3079void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003080 CapturedRegionKind Kind,
3081 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003082 CapturedDecl *CD = 0;
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003083 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003084
3085 // Enter the capturing scope for this captured region.
3086 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3087
3088 if (CurScope)
3089 PushDeclContext(CurScope, CD);
3090 else
3091 CurContext = CD;
3092
3093 PushExpressionEvaluationContext(PotentiallyEvaluated);
3094}
3095
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003096void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003097 DiscardCleanupsInEvaluationContext();
3098 PopExpressionEvaluationContext();
3099
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003100 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3101 RecordDecl *Record = RSI->TheRecordDecl;
3102 Record->setInvalidDecl();
3103
3104 SmallVector<Decl*, 4> Fields;
3105 for (RecordDecl::field_iterator I = Record->field_begin(),
3106 E = Record->field_end(); I != E; ++I)
3107 Fields.push_back(*I);
3108 ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
3109 SourceLocation(), SourceLocation(), /*AttributeList=*/0);
3110
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003111 PopDeclContext();
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003112 PopFunctionScopeInfo();
3113}
3114
3115StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3116 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3117
3118 SmallVector<CapturedStmt::Capture, 4> Captures;
3119 SmallVector<Expr *, 4> CaptureInits;
3120 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3121
3122 CapturedDecl *CD = RSI->TheCapturedDecl;
3123 RecordDecl *RD = RSI->TheRecordDecl;
3124
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003125 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3126 RSI->CapRegionKind, Captures,
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003127 CaptureInits, CD, RD);
3128
3129 CD->setBody(Res->getCapturedStmt());
3130 RD->completeDefinition();
3131
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003132 DiscardCleanupsInEvaluationContext();
3133 PopExpressionEvaluationContext();
3134
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003135 PopDeclContext();
3136 PopFunctionScopeInfo();
3137
3138 return Owned(Res);
3139}