blob: 7c2ee9dbe770198c5674ce6834d252071aabd6cc [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) {
Joey Gouly48a1e812013-06-06 13:48:00 +00001123 if (Diags.getDiagnosticLevel(diag::warn_not_in_enum_assignment,
1124 SrcExpr->getExprLoc()) ==
1125 DiagnosticsEngine::Ignored)
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001126 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.
Joey Gouly48a1e812013-06-06 13:48:00 +00001134 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001135 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1136
1137 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly48a1e812013-06-06 13:48:00 +00001138 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001139 const EnumDecl *ED = ET->getDecl();
Joey Gouly48a1e812013-06-06 13:48:00 +00001140 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1141 EnumValsTy;
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001142 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001143
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001144 // Gather all enum values, set their type and sort them,
1145 // allowing easier comparison with rhs constant.
1146 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1147 EDI != ED->enumerator_end(); ++EDI) {
1148 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly48a1e812013-06-06 13:48:00 +00001149 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001150 EnumVals.push_back(std::make_pair(Val, *EDI));
1151 }
1152 if (EnumVals.empty())
1153 return;
1154 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1155 EnumValsTy::iterator EIend =
Joey Gouly48a1e812013-06-06 13:48:00 +00001156 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001157
Joey Gouly48a1e812013-06-06 13:48:00 +00001158 // See which values aren't in the enum.
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001159 EnumValsTy::const_iterator EI = EnumVals.begin();
1160 while (EI != EIend && EI->first < RhsVal)
1161 EI++;
1162 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly48a1e812013-06-06 13:48:00 +00001163 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001164 << DstType;
1165 }
1166 }
1167 }
1168}
1169
John McCall60d7b3a2010-08-24 06:29:42 +00001170StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001171Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001172 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001173 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001174
Douglas Gregor5656e142009-11-24 21:15:44 +00001175 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001176 if (CondVar) {
1177 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001178 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001179 if (CondResult.isInvalid())
1180 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001181 }
John McCall9ae2f072010-08-23 23:25:46 +00001182 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001183 if (!ConditionExpr)
1184 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001185
John McCall9ae2f072010-08-23 23:25:46 +00001186 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001188 if (isa<NullStmt>(Body))
1189 getCurCompoundScope().setHasEmptyLoopBodies();
1190
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001191 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001192 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001193}
1194
John McCall60d7b3a2010-08-24 06:29:42 +00001195StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001196Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001197 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001198 Expr *Cond, SourceLocation CondRParen) {
1199 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001200
John Wiegley429bb272011-04-08 18:41:53 +00001201 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001202 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001203 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001204 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001205
Richard Smith41956372013-01-14 22:39:08 +00001206 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001207 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001208 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001209 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001210
John McCall9ae2f072010-08-23 23:25:46 +00001211 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001212
John McCall9ae2f072010-08-23 23:25:46 +00001213 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001214}
1215
Richard Trieu694e7962012-04-30 18:01:30 +00001216namespace {
1217 // This visitor will traverse a conditional statement and store all
1218 // the evaluated decls into a vector. Simple is set to true if none
1219 // of the excluded constructs are used.
1220 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1221 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001222 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001223 bool Simple;
Richard Trieu923cada2013-05-31 22:46:45 +00001224 public:
1225 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001226
Richard Trieu923cada2013-05-31 22:46:45 +00001227 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1228 SmallVector<SourceRange, 10> &Ranges) :
1229 Inherited(S.Context),
1230 Decls(Decls),
1231 Ranges(Ranges),
1232 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001233
Richard Trieu923cada2013-05-31 22:46:45 +00001234 bool isSimple() { return Simple; }
Richard Trieu694e7962012-04-30 18:01:30 +00001235
Richard Trieu923cada2013-05-31 22:46:45 +00001236 // Replaces the method in EvaluatedExprVisitor.
1237 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001238 Simple = false;
Richard Trieu923cada2013-05-31 22:46:45 +00001239 }
1240
1241 // Any Stmt not whitelisted will cause the condition to be marked complex.
1242 void VisitStmt(Stmt *S) {
1243 Simple = false;
1244 }
1245
1246 void VisitBinaryOperator(BinaryOperator *E) {
1247 Visit(E->getLHS());
1248 Visit(E->getRHS());
1249 }
1250
1251 void VisitCastExpr(CastExpr *E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001252 Visit(E->getSubExpr());
Richard Trieu923cada2013-05-31 22:46:45 +00001253 }
Richard Trieu694e7962012-04-30 18:01:30 +00001254
Richard Trieu923cada2013-05-31 22:46:45 +00001255 void VisitUnaryOperator(UnaryOperator *E) {
1256 // Skip checking conditionals with derefernces.
1257 if (E->getOpcode() == UO_Deref)
1258 Simple = false;
1259 else
1260 Visit(E->getSubExpr());
1261 }
Richard Trieu694e7962012-04-30 18:01:30 +00001262
Richard Trieu923cada2013-05-31 22:46:45 +00001263 void VisitConditionalOperator(ConditionalOperator *E) {
1264 Visit(E->getCond());
1265 Visit(E->getTrueExpr());
1266 Visit(E->getFalseExpr());
1267 }
Richard Trieu694e7962012-04-30 18:01:30 +00001268
Richard Trieu923cada2013-05-31 22:46:45 +00001269 void VisitParenExpr(ParenExpr *E) {
1270 Visit(E->getSubExpr());
1271 }
Richard Trieu694e7962012-04-30 18:01:30 +00001272
Richard Trieu923cada2013-05-31 22:46:45 +00001273 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1274 Visit(E->getOpaqueValue()->getSourceExpr());
1275 Visit(E->getFalseExpr());
1276 }
Richard Trieu694e7962012-04-30 18:01:30 +00001277
Richard Trieu923cada2013-05-31 22:46:45 +00001278 void VisitIntegerLiteral(IntegerLiteral *E) { }
1279 void VisitFloatingLiteral(FloatingLiteral *E) { }
1280 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1281 void VisitCharacterLiteral(CharacterLiteral *E) { }
1282 void VisitGNUNullExpr(GNUNullExpr *E) { }
1283 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu694e7962012-04-30 18:01:30 +00001284
Richard Trieu923cada2013-05-31 22:46:45 +00001285 void VisitDeclRefExpr(DeclRefExpr *E) {
1286 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1287 if (!VD) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001288
Richard Trieu923cada2013-05-31 22:46:45 +00001289 Ranges.push_back(E->getSourceRange());
1290
1291 Decls.insert(VD);
1292 }
Richard Trieu694e7962012-04-30 18:01:30 +00001293
1294 }; // end class DeclExtractor
1295
1296 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001297 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001298 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1299 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1300 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001301
Richard Trieu923cada2013-05-31 22:46:45 +00001302 public:
1303 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001304
Richard Trieu923cada2013-05-31 22:46:45 +00001305 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1306 Stmt *Statement) :
1307 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1308 if (!Statement) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001309
Richard Trieu923cada2013-05-31 22:46:45 +00001310 Visit(Statement);
Richard Trieu694e7962012-04-30 18:01:30 +00001311 }
1312
Richard Trieu923cada2013-05-31 22:46:45 +00001313 void VisitReturnStmt(ReturnStmt *S) {
1314 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001315 }
1316
Richard Trieu923cada2013-05-31 22:46:45 +00001317 void VisitBreakStmt(BreakStmt *S) {
1318 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001319 }
1320
Richard Trieu923cada2013-05-31 22:46:45 +00001321 void VisitGotoStmt(GotoStmt *S) {
1322 FoundDecl = true;
1323 }
Richard Trieu694e7962012-04-30 18:01:30 +00001324
Richard Trieu923cada2013-05-31 22:46:45 +00001325 void VisitCastExpr(CastExpr *E) {
1326 if (E->getCastKind() == CK_LValueToRValue)
1327 CheckLValueToRValueCast(E->getSubExpr());
1328 else
1329 Visit(E->getSubExpr());
1330 }
Richard Trieu694e7962012-04-30 18:01:30 +00001331
Richard Trieu923cada2013-05-31 22:46:45 +00001332 void CheckLValueToRValueCast(Expr *E) {
1333 E = E->IgnoreParenImpCasts();
1334
1335 if (isa<DeclRefExpr>(E)) {
1336 return;
1337 }
1338
1339 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1340 Visit(CO->getCond());
1341 CheckLValueToRValueCast(CO->getTrueExpr());
1342 CheckLValueToRValueCast(CO->getFalseExpr());
1343 return;
1344 }
1345
1346 if (BinaryConditionalOperator *BCO =
1347 dyn_cast<BinaryConditionalOperator>(E)) {
1348 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1349 CheckLValueToRValueCast(BCO->getFalseExpr());
1350 return;
1351 }
1352
1353 Visit(E);
1354 }
1355
1356 void VisitDeclRefExpr(DeclRefExpr *E) {
1357 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1358 if (Decls.count(VD))
1359 FoundDecl = true;
1360 }
1361
1362 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu694e7962012-04-30 18:01:30 +00001363
1364 }; // end class DeclMatcher
1365
1366 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1367 Expr *Third, Stmt *Body) {
1368 // Condition is empty
1369 if (!Second) return;
1370
1371 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1372 Second->getLocStart())
1373 == DiagnosticsEngine::Ignored)
1374 return;
1375
1376 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1377 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001378 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001379 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001380 DE.Visit(Second);
1381
1382 // Don't analyze complex conditionals.
1383 if (!DE.isSimple()) return;
1384
1385 // No decls found.
1386 if (Decls.size() == 0) return;
1387
Richard Trieu90875992012-05-04 03:01:54 +00001388 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001389 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1390 E = Decls.end();
1391 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001392 if ((*I)->getType().isVolatileQualified() ||
1393 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001394
1395 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1396 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1397 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1398 return;
1399
1400 // Load decl names into diagnostic.
1401 if (Decls.size() > 4)
1402 PDiag << 0;
1403 else {
1404 PDiag << Decls.size();
1405 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1406 E = Decls.end();
1407 I != E; ++I)
1408 PDiag << (*I)->getDeclName();
1409 }
1410
1411 // Load SourceRanges into diagnostic if there is room.
1412 // Otherwise, load the SourceRange of the conditional expression.
1413 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001414 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1415 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001416 I != E; ++I)
1417 PDiag << *I;
1418 else
1419 PDiag << Second->getSourceRange();
1420
1421 S.Diag(Ranges.begin()->getBegin(), PDiag);
1422 }
1423
1424} // end namespace
1425
John McCall60d7b3a2010-08-24 06:29:42 +00001426StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001427Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001428 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001429 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001430 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001431 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001432 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001433 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1434 // declare identifiers for objects having storage class 'auto' or
1435 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001436 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1437 DI!=DE; ++DI) {
1438 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001439 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001440 VD = 0;
Douglas Gregor12849d02013-04-08 20:52:24 +00001441 if (VD == 0) {
1442 Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
1443 (*DI)->setInvalidDecl();
1444 }
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001445 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001446 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001448
Richard Trieu694e7962012-04-30 18:01:30 +00001449 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1450
John McCall60d7b3a2010-08-24 06:29:42 +00001451 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001452 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001453 if (secondVar) {
1454 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001455 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001456 if (SecondResult.isInvalid())
1457 return StmtError();
1458 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001459
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001460 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001461
Anders Carlsson3af708f2009-08-01 01:39:59 +00001462 DiagnoseUnusedExprResult(First);
1463 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001464 DiagnoseUnusedExprResult(Body);
1465
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001466 if (isa<NullStmt>(Body))
1467 getCurCompoundScope().setHasEmptyLoopBodies();
1468
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469 return Owned(new (Context) ForStmt(Context, First,
1470 SecondResult.take(), ConditionVar,
1471 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001472 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001473}
1474
John McCallf6a16482010-12-04 03:47:34 +00001475/// In an Objective C collection iteration statement:
1476/// for (x in y)
1477/// x can be an arbitrary l-value expression. Bind it up as a
1478/// full-expression.
1479StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001480 // Reduce placeholder expressions here. Note that this rejects the
1481 // use of pseudo-object l-values in this position.
1482 ExprResult result = CheckPlaceholderExpr(E);
1483 if (result.isInvalid()) return StmtError();
1484 E = result.take();
1485
Richard Smith41956372013-01-14 22:39:08 +00001486 ExprResult FullExpr = ActOnFinishFullExpr(E);
1487 if (FullExpr.isInvalid())
1488 return StmtError();
1489 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001490}
1491
John McCall990567c2011-07-27 01:07:15 +00001492ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001493Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1494 if (!collection)
1495 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001496
John McCall990567c2011-07-27 01:07:15 +00001497 // Bail out early if we've got a type-dependent expression.
1498 if (collection->isTypeDependent()) return Owned(collection);
1499
1500 // Perform normal l-value conversion.
1501 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1502 if (result.isInvalid())
1503 return ExprError();
1504 collection = result.take();
1505
1506 // The operand needs to have object-pointer type.
1507 // TODO: should we do a contextual conversion?
1508 const ObjCObjectPointerType *pointerType =
1509 collection->getType()->getAs<ObjCObjectPointerType>();
1510 if (!pointerType)
1511 return Diag(forLoc, diag::err_collection_expr_type)
1512 << collection->getType() << collection->getSourceRange();
1513
1514 // Check that the operand provides
1515 // - countByEnumeratingWithState:objects:count:
1516 const ObjCObjectType *objectType = pointerType->getObjectType();
1517 ObjCInterfaceDecl *iface = objectType->getInterface();
1518
1519 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001520 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001521 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001522 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001523 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001524 ? diag::err_arc_collection_forward
1525 : 0,
1526 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001527 // Otherwise, if we have any useful type information, check that
1528 // the type declares the appropriate method.
1529 } else if (iface || !objectType->qual_empty()) {
1530 IdentifierInfo *selectorIdents[] = {
1531 &Context.Idents.get("countByEnumeratingWithState"),
1532 &Context.Idents.get("objects"),
1533 &Context.Idents.get("count")
1534 };
1535 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1536
1537 ObjCMethodDecl *method = 0;
1538
1539 // If there's an interface, look in both the public and private APIs.
1540 if (iface) {
1541 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001542 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001543 }
1544
1545 // Also check protocol qualifiers.
1546 if (!method)
1547 method = LookupMethodInQualifiedType(selector, pointerType,
1548 /*instance*/ true);
1549
1550 // If we didn't find it anywhere, give up.
1551 if (!method) {
1552 Diag(forLoc, diag::warn_collection_expr_type)
1553 << collection->getType() << selector << collection->getSourceRange();
1554 }
1555
1556 // TODO: check for an incompatible signature?
1557 }
1558
1559 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001560 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001561}
1562
John McCall60d7b3a2010-08-24 06:29:42 +00001563StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001564Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001565 Stmt *First, Expr *collection,
1566 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001567
1568 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001569 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001570
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001571 if (First) {
1572 QualType FirstType;
1573 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001574 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001575 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1576 diag::err_toomany_element_decls));
1577
Douglas Gregor12849d02013-04-08 20:52:24 +00001578 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1579 if (!D || D->isInvalidDecl())
1580 return StmtError();
1581
John McCallf85e1932011-06-15 23:02:42 +00001582 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001583 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1584 // declare identifiers for objects having storage class 'auto' or
1585 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001586 if (!D->hasLocalStorage())
1587 return StmtError(Diag(D->getLocation(),
Douglas Gregor12849d02013-04-08 20:52:24 +00001588 diag::err_non_local_variable_decl_in_for));
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001589
1590 // If the type contained 'auto', deduce the 'auto' to 'id'.
1591 if (FirstType->getContainedAutoType()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001592 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1593 VK_RValue);
1594 Expr *DeducedInit = &OpaqueId;
Richard Smith9b131752013-04-30 21:23:01 +00001595 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1596 DAR_Failed)
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001597 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith9b131752013-04-30 21:23:01 +00001598 if (FirstType.isNull()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001599 D->setInvalidDecl();
1600 return StmtError();
1601 }
1602
Richard Smith9b131752013-04-30 21:23:01 +00001603 D->setType(FirstType);
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001604
1605 if (ActiveTemplateInstantiations.empty()) {
Richard Smith9b131752013-04-30 21:23:01 +00001606 SourceLocation Loc =
1607 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001608 Diag(Loc, diag::warn_auto_var_is_id)
1609 << D->getDeclName();
1610 }
1611 }
1612
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001613 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001614 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001615 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001616 return StmtError(Diag(First->getLocStart(),
1617 diag::err_selector_element_not_lvalue)
1618 << First->getSourceRange());
1619
Mike Stump1eb44332009-09-09 15:08:12 +00001620 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001621 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001622 if (!FirstType->isDependentType() &&
1623 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001624 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001625 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1626 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001627 }
Chad Rosier1093f492012-08-10 17:56:09 +00001628
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001629 if (CollectionExprResult.isInvalid())
1630 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001631
Richard Smith41956372013-01-14 22:39:08 +00001632 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1633 if (CollectionExprResult.isInvalid())
1634 return StmtError();
1635
Chad Rosier1093f492012-08-10 17:56:09 +00001636 return Owned(new (Context) ObjCForCollectionStmt(First,
1637 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001638 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001639}
Reid Spencer5f016e22007-07-11 17:01:13 +00001640
Richard Smithad762fc2011-04-14 22:09:26 +00001641/// Finish building a variable declaration for a for-range statement.
1642/// \return true if an error occurs.
1643static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith9b131752013-04-30 21:23:01 +00001644 SourceLocation Loc, int DiagID) {
Richard Smithad762fc2011-04-14 22:09:26 +00001645 // Deduce the type for the iterator variable now rather than leaving it to
1646 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith9b131752013-04-30 21:23:01 +00001647 QualType InitType;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001648 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith9b131752013-04-30 21:23:01 +00001649 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001650 Sema::DAR_Failed)
Richard Smith9b131752013-04-30 21:23:01 +00001651 SemaRef.Diag(Loc, DiagID) << Init->getType();
1652 if (InitType.isNull()) {
Richard Smithad762fc2011-04-14 22:09:26 +00001653 Decl->setInvalidDecl();
1654 return true;
1655 }
Richard Smith9b131752013-04-30 21:23:01 +00001656 Decl->setType(InitType);
Richard Smithad762fc2011-04-14 22:09:26 +00001657
John McCallf85e1932011-06-15 23:02:42 +00001658 // In ARC, infer lifetime.
1659 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1660 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001661 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001662 SemaRef.inferObjCARCLifetime(Decl))
1663 Decl->setInvalidDecl();
1664
Richard Smithad762fc2011-04-14 22:09:26 +00001665 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1666 /*TypeMayContainAuto=*/false);
1667 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001668 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001669 return false;
1670}
1671
Sam Panzere1715b62012-08-21 00:52:01 +00001672namespace {
1673
Richard Smithad762fc2011-04-14 22:09:26 +00001674/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001675/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001676/// nor from the diagnostics produced when analysing the implicit expressions
1677/// required in a for-range statement.
1678void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001679 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001680 CallExpr *CE = dyn_cast<CallExpr>(E);
1681 if (!CE)
1682 return;
1683 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1684 if (!D)
1685 return;
1686 SourceLocation Loc = D->getLocation();
1687
1688 std::string Description;
1689 bool IsTemplate = false;
1690 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1691 Description = SemaRef.getTemplateArgumentBindingsText(
1692 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1693 IsTemplate = true;
1694 }
1695
1696 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1697 << BEF << IsTemplate << Description << E->getType();
1698}
1699
Sam Panzere1715b62012-08-21 00:52:01 +00001700/// Build a variable declaration for a for-range statement.
1701VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1702 QualType Type, const char *Name) {
1703 DeclContext *DC = SemaRef.CurContext;
1704 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1705 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1706 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001707 TInfo, SC_None);
Sam Panzere1715b62012-08-21 00:52:01 +00001708 Decl->setImplicit();
1709 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001710}
1711
1712}
1713
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001714static bool ObjCEnumerationCollection(Expr *Collection) {
1715 return !Collection->isTypeDependent()
1716 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1717}
1718
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001719/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001720///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001721/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001722/// A range-based for statement is equivalent to
1723///
1724/// {
1725/// auto && __range = range-init;
1726/// for ( auto __begin = begin-expr,
1727/// __end = end-expr;
1728/// __begin != __end;
1729/// ++__begin ) {
1730/// for-range-declaration = *__begin;
1731/// statement
1732/// }
1733/// }
1734///
1735/// The body of the loop is not available yet, since it cannot be analysed until
1736/// we have determined the type of the for-range-declaration.
1737StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001738Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001739 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001740 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001741 if (!First || !Range)
1742 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001743
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001744 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001745 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001746
1747 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1748 assert(DS && "first part of for range not a decl stmt");
1749
1750 if (!DS->isSingleDecl()) {
1751 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1752 return StmtError();
1753 }
1754 if (DS->getSingleDecl()->isInvalidDecl())
1755 return StmtError();
1756
1757 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1758 return StmtError();
1759
1760 // Build auto && __range = range-init
1761 SourceLocation RangeLoc = Range->getLocStart();
1762 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1763 Context.getAutoRRefDeductType(),
1764 "__range");
1765 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1766 diag::err_for_range_deduction_failure))
1767 return StmtError();
1768
1769 // Claim the type doesn't contain auto: we've already done the checking.
1770 DeclGroupPtrTy RangeGroup =
1771 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1772 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1773 if (RangeDecl.isInvalid())
1774 return StmtError();
1775
1776 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1777 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001778 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001779}
1780
1781/// \brief Create the initialization, compare, and increment steps for
1782/// the range-based for loop expression.
1783/// This function does not handle array-based for loops,
1784/// which are created in Sema::BuildCXXForRangeStmt.
1785///
1786/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1787/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1788/// CandidateSet and BEF are set and some non-success value is returned on
1789/// failure.
1790static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1791 Expr *BeginRange, Expr *EndRange,
1792 QualType RangeType,
1793 VarDecl *BeginVar,
1794 VarDecl *EndVar,
1795 SourceLocation ColonLoc,
1796 OverloadCandidateSet *CandidateSet,
1797 ExprResult *BeginExpr,
1798 ExprResult *EndExpr,
1799 Sema::BeginEndFunction *BEF) {
1800 DeclarationNameInfo BeginNameInfo(
1801 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1802 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1803 ColonLoc);
1804
1805 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1806 Sema::LookupMemberName);
1807 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1808
1809 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1810 // - if _RangeT is a class type, the unqualified-ids begin and end are
1811 // looked up in the scope of class _RangeT as if by class member access
1812 // lookup (3.4.5), and if either (or both) finds at least one
1813 // declaration, begin-expr and end-expr are __range.begin() and
1814 // __range.end(), respectively;
1815 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1816 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1817
1818 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1819 SourceLocation RangeLoc = BeginVar->getLocation();
1820 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1821
1822 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1823 << RangeLoc << BeginRange->getType() << *BEF;
1824 return Sema::FRS_DiagnosticIssued;
1825 }
1826 } else {
1827 // - otherwise, begin-expr and end-expr are begin(__range) and
1828 // end(__range), respectively, where begin and end are looked up with
1829 // argument-dependent lookup (3.4.2). For the purposes of this name
1830 // lookup, namespace std is an associated namespace.
1831
1832 }
1833
1834 *BEF = Sema::BEF_begin;
1835 Sema::ForRangeStatus RangeStatus =
1836 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1837 Sema::BEF_begin, BeginNameInfo,
1838 BeginMemberLookup, CandidateSet,
1839 BeginRange, BeginExpr);
1840
1841 if (RangeStatus != Sema::FRS_Success)
1842 return RangeStatus;
1843 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1844 diag::err_for_range_iter_deduction_failure)) {
1845 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1846 return Sema::FRS_DiagnosticIssued;
1847 }
1848
1849 *BEF = Sema::BEF_end;
1850 RangeStatus =
1851 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1852 Sema::BEF_end, EndNameInfo,
1853 EndMemberLookup, CandidateSet,
1854 EndRange, EndExpr);
1855 if (RangeStatus != Sema::FRS_Success)
1856 return RangeStatus;
1857 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1858 diag::err_for_range_iter_deduction_failure)) {
1859 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1860 return Sema::FRS_DiagnosticIssued;
1861 }
1862 return Sema::FRS_Success;
1863}
1864
1865/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001866/// If the attempt fails, this function will return a valid, null StmtResult
1867/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001868static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1869 SourceLocation ForLoc,
1870 Stmt *LoopVarDecl,
1871 SourceLocation ColonLoc,
1872 Expr *Range,
1873 SourceLocation RangeLoc,
1874 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001875 // Determine whether we can rebuild the for-range statement with a
1876 // dereferenced range expression.
1877 ExprResult AdjustedRange;
1878 {
1879 Sema::SFINAETrap Trap(SemaRef);
1880
1881 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1882 if (AdjustedRange.isInvalid())
1883 return StmtResult();
1884
1885 StmtResult SR =
1886 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1887 AdjustedRange.get(), RParenLoc,
1888 Sema::BFRK_Check);
1889 if (SR.isInvalid())
1890 return StmtResult();
1891 }
1892
1893 // The attempt to dereference worked well enough that it could produce a valid
1894 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1895 // case there are any other (non-fatal) problems with it.
1896 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1897 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1898 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1899 AdjustedRange.get(), RParenLoc,
1900 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001901}
1902
Richard Smith8b533d92012-09-20 21:52:32 +00001903/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001904StmtResult
1905Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1906 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1907 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001908 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001909 Scope *S = getCurScope();
1910
1911 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1912 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1913 QualType RangeVarType = RangeVar->getType();
1914
1915 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1916 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1917
1918 StmtResult BeginEndDecl = BeginEnd;
1919 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1920
Richard Smithdc7a4f52013-04-30 13:56:41 +00001921 if (RangeVarType->isDependentType()) {
1922 // The range is implicitly used as a placeholder when it is dependent.
1923 RangeVar->setUsed();
1924
1925 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
1926 // them in properly when we instantiate the loop.
1927 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
1928 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
1929 } else if (!BeginEndDecl.get()) {
Richard Smithad762fc2011-04-14 22:09:26 +00001930 SourceLocation RangeLoc = RangeVar->getLocation();
1931
Ted Kremeneke50b0152011-10-10 22:36:28 +00001932 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1933
1934 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1935 VK_LValue, ColonLoc);
1936 if (BeginRangeRef.isInvalid())
1937 return StmtError();
1938
1939 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1940 VK_LValue, ColonLoc);
1941 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001942 return StmtError();
1943
1944 QualType AutoType = Context.getAutoDeductType();
1945 Expr *Range = RangeVar->getInit();
1946 if (!Range)
1947 return StmtError();
1948 QualType RangeType = Range->getType();
1949
1950 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001951 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001952 return StmtError();
1953
1954 // Build auto __begin = begin-expr, __end = end-expr.
1955 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1956 "__begin");
1957 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1958 "__end");
1959
1960 // Build begin-expr and end-expr and attach to __begin and __end variables.
1961 ExprResult BeginExpr, EndExpr;
1962 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1963 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1964 // __range + __bound, respectively, where __bound is the array bound. If
1965 // _RangeT is an array of unknown size or an array of incomplete type,
1966 // the program is ill-formed;
1967
1968 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001969 BeginExpr = BeginRangeRef;
1970 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001971 diag::err_for_range_iter_deduction_failure)) {
1972 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1973 return StmtError();
1974 }
1975
1976 // Find the array bound.
1977 ExprResult BoundExpr;
1978 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1979 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001980 Context.getPointerDiffType(),
1981 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001982 else if (const VariableArrayType *VAT =
1983 dyn_cast<VariableArrayType>(UnqAT))
Richard Smith39b0e262013-04-20 23:28:26 +00001984 // FIXME: Need to build an OpaqueValueExpr for this rather than
1985 // recomputing it!
Richard Smithad762fc2011-04-14 22:09:26 +00001986 BoundExpr = VAT->getSizeExpr();
1987 else {
1988 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1989 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001990 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001991 }
1992
1993 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001994 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001995 BoundExpr.get());
1996 if (EndExpr.isInvalid())
1997 return StmtError();
1998 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1999 diag::err_for_range_iter_deduction_failure)) {
2000 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2001 return StmtError();
2002 }
2003 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00002004 OverloadCandidateSet CandidateSet(RangeLoc);
2005 Sema::BeginEndFunction BEFFailure;
2006 ForRangeStatus RangeStatus =
2007 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2008 EndRangeRef.get(), RangeType,
2009 BeginVar, EndVar, ColonLoc, &CandidateSet,
2010 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00002011
Sam Panzere1715b62012-08-21 00:52:01 +00002012 // If building the range failed, try dereferencing the range expression
2013 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00002014 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00002015 BEFFailure == BEF_begin) {
2016 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2017 LoopVarDecl, ColonLoc,
2018 Range, RangeLoc,
2019 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00002020 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00002021 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00002022 }
2023
Sam Panzere1715b62012-08-21 00:52:01 +00002024 // Otherwise, emit diagnostics if we haven't already.
2025 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00002026 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00002027 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2028 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00002029 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00002030 }
2031 // Return an error if no fix was discovered.
2032 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00002033 return StmtError();
2034 }
2035
Sam Panzere1715b62012-08-21 00:52:01 +00002036 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2037 "invalid range expression in for loop");
2038
2039 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00002040 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2041 if (!Context.hasSameType(BeginType, EndType)) {
2042 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2043 << BeginType << EndType;
2044 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2045 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2046 }
2047
2048 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2049 // Claim the type doesn't contain auto: we've already done the checking.
2050 DeclGroupPtrTy BeginEndGroup =
2051 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
2052 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2053
Ted Kremeneke50b0152011-10-10 22:36:28 +00002054 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2055 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00002056 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002057 if (BeginRef.isInvalid())
2058 return StmtError();
2059
Richard Smithad762fc2011-04-14 22:09:26 +00002060 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2061 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002062 if (EndRef.isInvalid())
2063 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00002064
2065 // Build and check __begin != __end expression.
2066 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2067 BeginRef.get(), EndRef.get());
2068 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2069 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2070 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002071 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2072 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002073 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2074 if (!Context.hasSameType(BeginType, EndType))
2075 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2076 return StmtError();
2077 }
2078
2079 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002080 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2081 VK_LValue, ColonLoc);
2082 if (BeginRef.isInvalid())
2083 return StmtError();
2084
Richard Smithad762fc2011-04-14 22:09:26 +00002085 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2086 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2087 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002088 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2089 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002090 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2091 return StmtError();
2092 }
2093
2094 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002095 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2096 VK_LValue, ColonLoc);
2097 if (BeginRef.isInvalid())
2098 return StmtError();
2099
Richard Smithad762fc2011-04-14 22:09:26 +00002100 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2101 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002102 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2103 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002104 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2105 return StmtError();
2106 }
2107
Richard Smith8b533d92012-09-20 21:52:32 +00002108 // Attach *__begin as initializer for VD. Don't touch it if we're just
2109 // trying to determine whether this would be a valid range.
2110 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002111 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2112 /*TypeMayContainAuto=*/true);
2113 if (LoopVar->isInvalidDecl())
2114 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2115 }
2116 }
2117
Richard Smith8b533d92012-09-20 21:52:32 +00002118 // Don't bother to actually allocate the result if we're just trying to
2119 // determine whether it would be valid.
2120 if (Kind == BFRK_Check)
2121 return StmtResult();
2122
Richard Smithad762fc2011-04-14 22:09:26 +00002123 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2124 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2125 NotEqExpr.take(), IncrExpr.take(),
2126 LoopVarDS, /*Body=*/0, ForLoc,
2127 ColonLoc, RParenLoc));
2128}
2129
Chad Rosier1093f492012-08-10 17:56:09 +00002130/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002131/// statement.
2132StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2133 if (!S || !B)
2134 return StmtError();
2135 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002136
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002137 ForStmt->setBody(B);
2138 return S;
2139}
2140
Richard Smithad762fc2011-04-14 22:09:26 +00002141/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2142/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2143/// body cannot be performed until after the type of the range variable is
2144/// determined.
2145StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2146 if (!S || !B)
2147 return StmtError();
2148
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002149 if (isa<ObjCForCollectionStmt>(S))
2150 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002151
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002152 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2153 ForStmt->setBody(B);
2154
2155 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2156 diag::warn_empty_range_based_for_body);
2157
Richard Smithad762fc2011-04-14 22:09:26 +00002158 return S;
2159}
2160
Chris Lattner57ad3782011-02-17 20:34:02 +00002161StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2162 SourceLocation LabelLoc,
2163 LabelDecl *TheDecl) {
2164 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002165 TheDecl->setUsed();
2166 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002167}
2168
John McCall60d7b3a2010-08-24 06:29:42 +00002169StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002170Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002171 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002172 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002173 if (!E->isTypeDependent()) {
2174 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002175 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002176 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002177 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002178 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2179 if (ExprRes.isInvalid())
2180 return StmtError();
2181 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002182 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002183 return StmtError();
2184 }
John McCallb60a77e2010-08-01 00:26:45 +00002185
Richard Smith41956372013-01-14 22:39:08 +00002186 ExprResult ExprRes = ActOnFinishFullExpr(E);
2187 if (ExprRes.isInvalid())
2188 return StmtError();
2189 E = ExprRes.take();
2190
John McCall781472f2010-08-25 08:40:02 +00002191 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002192
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002193 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002194}
2195
John McCall60d7b3a2010-08-24 06:29:42 +00002196StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002197Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 Scope *S = CurScope->getContinueParent();
2199 if (!S) {
2200 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002201 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002203
Ted Kremenek8189cde2009-02-07 01:47:29 +00002204 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002205}
2206
John McCall60d7b3a2010-08-24 06:29:42 +00002207StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002208Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 Scope *S = CurScope->getBreakParent();
2210 if (!S) {
2211 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002212 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002214
Ted Kremenek8189cde2009-02-07 01:47:29 +00002215 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002216}
2217
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002219/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002220///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002221/// \param ReturnType If we're determining the copy elision candidate for
2222/// a return statement, this is the return type of the function. If we're
2223/// determining the copy elision candidate for a throw expression, this will
2224/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002225///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002226/// \param E The expression being returned from the function or block, or
2227/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002228///
Douglas Gregor4926d832011-05-20 15:00:53 +00002229/// \param AllowFunctionParameter Whether we allow function parameters to
2230/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2231/// we re-use this logic to determine whether we should try to move as part of
2232/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002233///
2234/// \returns The NRVO candidate variable, if the return statement may use the
2235/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002236const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2237 Expr *E,
2238 bool AllowFunctionParameter) {
2239 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002240 // - in a return statement in a function with ...
2241 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002242 if (!ReturnType.isNull()) {
2243 if (!ReturnType->isRecordType())
2244 return 0;
2245 // ... the same cv-unqualified type as the function return type ...
2246 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2247 return 0;
2248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002249
2250 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002251 // (other than a function or catch-clause parameter)) ...
2252 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002253 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002254 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002255 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2256 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002257 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002258
John McCall1cd76e82011-11-11 03:57:31 +00002259 // ...object (other than a function or catch-clause parameter)...
2260 if (VD->getKind() != Decl::Var &&
2261 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2262 return 0;
2263 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002264
John McCall1cd76e82011-11-11 03:57:31 +00002265 // ...automatic...
2266 if (!VD->hasLocalStorage()) return 0;
2267
2268 // ...non-volatile...
2269 if (VD->getType().isVolatileQualified()) return 0;
2270 if (VD->getType()->isReferenceType()) return 0;
2271
2272 // __block variables can't be allocated in a way that permits NRVO.
2273 if (VD->hasAttr<BlocksAttr>()) return 0;
2274
2275 // Variables with higher required alignment than their type's ABI
2276 // alignment cannot use NRVO.
2277 if (VD->hasAttr<AlignedAttr>() &&
2278 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2279 return 0;
2280
2281 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002282}
2283
Douglas Gregor07f402c2011-01-21 21:08:57 +00002284/// \brief Perform the initialization of a potentially-movable value, which
2285/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002286///
2287/// This routine implements C++0x [class.copy]p33, which attempts to treat
2288/// returned lvalues as rvalues in certain cases (to prefer move construction),
2289/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002290ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002291Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2292 const VarDecl *NRVOCandidate,
2293 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002294 Expr *Value,
2295 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002296 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002297 // When the criteria for elision of a copy operation are met or would
2298 // be met save for the fact that the source object is a function
2299 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002300 // overload resolution to select the constructor for the copy is first
2301 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002302 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002303 if (AllowNRVO &&
2304 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002305 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002306 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002307
Douglas Gregorcc15f012011-01-21 19:38:21 +00002308 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002309 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002310 = InitializationKind::CreateCopy(Value->getLocStart(),
2311 Value->getLocStart());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002312 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002313
2314 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002315 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002316 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002317 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002318 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002319 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2320 StepEnd = Seq.step_end();
2321 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002322 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002323 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002324
2325 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002326 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002327
Douglas Gregorcc15f012011-01-21 19:38:21 +00002328 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002329 = Constructor->getParamDecl(0)->getType()
2330 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002331
Douglas Gregorcc15f012011-01-21 19:38:21 +00002332 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002333 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002334 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2335 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002336 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002337
Douglas Gregorcc15f012011-01-21 19:38:21 +00002338 // Promote "AsRvalue" to the heap, since we now need this
2339 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002340 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002341 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002342
Douglas Gregorcc15f012011-01-21 19:38:21 +00002343 // Complete type-checking the initialization of the return type
2344 // using the constructor we found.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002345 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorcc15f012011-01-21 19:38:21 +00002346 }
2347 }
2348 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349
Douglas Gregorcc15f012011-01-21 19:38:21 +00002350 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002351 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002352 // (again) now with the return value expression as written.
2353 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002354 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002355
Douglas Gregorcc15f012011-01-21 19:38:21 +00002356 return Res;
2357}
2358
Eli Friedman84b007f2012-01-26 03:00:14 +00002359/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2360/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002361///
John McCall60d7b3a2010-08-24 06:29:42 +00002362StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002363Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2364 // If this is the first return we've seen, infer the return type.
Richard Smithf45c2992013-05-12 03:09:35 +00002365 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman84b007f2012-01-26 03:00:14 +00002366 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002367 QualType FnRetType = CurCap->ReturnType;
2368
2369 // For blocks/lambdas with implicit return types, we check each return
2370 // statement individually, and deduce the common return type when the block
2371 // or lambda is completed.
Richard Smithf45c2992013-05-12 03:09:35 +00002372 if (AutoType *AT =
2373 FnRetType.isNull() ? 0 : FnRetType->getContainedAutoType()) {
2374 // In C++1y, the return type may involve 'auto'.
2375 FunctionDecl *FD = cast<LambdaScopeInfo>(CurCap)->CallOperator;
2376 if (CurContext->isDependentContext()) {
2377 // C++1y [dcl.spec.auto]p12:
2378 // Return type deduction [...] occurs when the definition is
2379 // instantiated even if the function body contains a return
2380 // statement with a non-type-dependent operand.
2381 CurCap->ReturnType = FnRetType = Context.DependentTy;
2382 } else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2383 FD->setInvalidDecl();
2384 return StmtError();
2385 } else
2386 CurCap->ReturnType = FnRetType = FD->getResultType();
2387 } else if (CurCap->HasImplicitReturnType) {
2388 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregora0c2b212012-02-09 18:40:39 +00002389 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002390 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2391 if (Result.isInvalid())
2392 return StmtError();
2393 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002394
Richard Smithf45c2992013-05-12 03:09:35 +00002395 if (!CurContext->isDependentContext())
Jordan Rose7dd900e2012-07-02 21:19:23 +00002396 FnRetType = RetValExp->getType();
2397 else
2398 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002399 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002400 if (RetValExp) {
2401 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2402 // initializer list, because it is not an expression (even
2403 // though we represent it as one). We still deduce 'void'.
2404 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2405 << RetValExp->getSourceRange();
2406 }
2407
Jordan Rose7dd900e2012-07-02 21:19:23 +00002408 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002409 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002410
2411 // Although we'll properly infer the type of the block once it's completed,
2412 // make sure we provide a return type now for better error recovery.
2413 if (CurCap->ReturnType.isNull())
2414 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002415 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002416 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002417
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002418 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002419 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2420 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2421 return StmtError();
2422 }
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00002423 } else if (CapturedRegionScopeInfo *CurRegion =
2424 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2425 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2426 return StmtError();
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002427 } else {
2428 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2429 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2430 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2431 return StmtError();
2432 }
2433 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002434
Steve Naroff4eb206b2008-09-03 18:15:37 +00002435 // Otherwise, verify that this result type matches the previous one. We are
2436 // pickier with blocks than for normal functions because we don't have GCC
2437 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002438 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002439 if (FnRetType->isDependentType()) {
2440 // Delay processing for now. TODO: there are lots of dependent
2441 // types we can conclusively prove aren't void.
2442 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002443 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002444 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002445 (RetValExp->isTypeDependent() ||
2446 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002447 if (!getLangOpts().CPlusPlus &&
2448 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002449 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002450 else {
2451 Diag(ReturnLoc, diag::err_return_block_has_expr);
2452 RetValExp = 0;
2453 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002454 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002455 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002456 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2457 } else if (!RetValExp->isTypeDependent()) {
2458 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002459
John McCall0a7efe12011-08-17 22:09:46 +00002460 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2461 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2462 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002463
John McCall0a7efe12011-08-17 22:09:46 +00002464 // In C++ the return statement is handled via a copy initialization.
2465 // the C version of which boils down to CheckSingleAssignmentConstraints.
2466 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2467 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2468 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002469 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002470 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2471 FnRetType, RetValExp);
2472 if (Res.isInvalid()) {
2473 // FIXME: Cleanup temporaries here, anyway?
2474 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002475 }
John McCall0a7efe12011-08-17 22:09:46 +00002476 RetValExp = Res.take();
2477 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002478 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002479
John McCalld963c372011-08-17 21:34:14 +00002480 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002481 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2482 if (ER.isInvalid())
2483 return StmtError();
2484 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002485 }
John McCall0a7efe12011-08-17 22:09:46 +00002486 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2487 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002488
Jordan Rose7dd900e2012-07-02 21:19:23 +00002489 // If we need to check for the named return value optimization,
2490 // or if we need to infer the return type,
2491 // save the return statement in our scope for later processing.
2492 if (CurCap->HasImplicitReturnType ||
2493 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2494 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002495 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002496
Douglas Gregor5077c382010-05-15 06:01:05 +00002497 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002498}
Reid Spencer5f016e22007-07-11 17:01:13 +00002499
Richard Smith60e141e2013-05-04 07:00:32 +00002500/// Deduce the return type for a function from a returned expression, per
2501/// C++1y [dcl.spec.auto]p6.
2502bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2503 SourceLocation ReturnLoc,
2504 Expr *&RetExpr,
2505 AutoType *AT) {
2506 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
2507 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
2508 QualType Deduced;
2509
2510 if (RetExpr) {
2511 // If the deduction is for a return statement and the initializer is
2512 // a braced-init-list, the program is ill-formed.
2513 if (isa<InitListExpr>(RetExpr)) {
2514 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2515 return true;
2516 }
2517
2518 // Otherwise, [...] deduce a value for U using the rules of template
2519 // argument deduction.
2520 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2521
2522 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2523 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2524 << OrigResultType.getType() << RetExpr->getType();
2525
2526 if (DAR != DAR_Succeeded)
2527 return true;
2528 } else {
2529 // In the case of a return with no operand, the initializer is considered
2530 // to be void().
2531 //
2532 // Deduction here can only succeed if the return type is exactly 'cv auto'
2533 // or 'decltype(auto)', so just check for that case directly.
2534 if (!OrigResultType.getType()->getAs<AutoType>()) {
2535 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2536 << OrigResultType.getType();
2537 return true;
2538 }
2539 // We always deduce U = void in this case.
2540 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2541 if (Deduced.isNull())
2542 return true;
2543 }
2544
2545 // If a function with a declared return type that contains a placeholder type
2546 // has multiple return statements, the return type is deduced for each return
2547 // statement. [...] if the type deduced is not the same in each deduction,
2548 // the program is ill-formed.
2549 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2550 AutoType *NewAT = Deduced->getContainedAutoType();
2551 if (!Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2552 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2553 << (AT->isDecltypeAuto() ? 1 : 0)
2554 << NewAT->getDeducedType() << AT->getDeducedType();
2555 return true;
2556 }
2557 } else if (!FD->isInvalidDecl()) {
2558 // Update all declarations of the function to have the deduced return type.
2559 Context.adjustDeducedFunctionResultType(FD, Deduced);
2560 }
2561
2562 return false;
2563}
2564
John McCall60d7b3a2010-08-24 06:29:42 +00002565StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002566Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002567 // Check for unexpanded parameter packs.
2568 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2569 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002570
Eli Friedman84b007f2012-01-26 03:00:14 +00002571 if (isa<CapturingScopeInfo>(getCurFunction()))
2572 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002573
Chris Lattner371f2582008-12-04 23:50:19 +00002574 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002575 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002576 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002577 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002578 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002579 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002580 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002581 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002582 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002583 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2584 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002585 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002586 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002587 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2588 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002589 }
2590 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002591 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Richard Smith60e141e2013-05-04 07:00:32 +00002593 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2594 // deduction.
2595 bool HasDependentReturnType = FnRetType->isDependentType();
2596 if (getLangOpts().CPlusPlus1y) {
2597 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2598 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2599 if (CurContext->isDependentContext())
2600 HasDependentReturnType = true;
2601 else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2602 FD->setInvalidDecl();
2603 return StmtError();
2604 } else {
2605 FnRetType = FD->getResultType();
2606 }
2607 }
2608 }
2609
Douglas Gregor5077c382010-05-15 06:01:05 +00002610 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002611 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002612 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002613 if (isa<InitListExpr>(RetValExp)) {
2614 // We simply never allow init lists as the return value of void
2615 // functions. This is compatible because this was never allowed before,
2616 // so there's no legacy code to deal with.
2617 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2618 int FunctionKind = 0;
2619 if (isa<ObjCMethodDecl>(CurDecl))
2620 FunctionKind = 1;
2621 else if (isa<CXXConstructorDecl>(CurDecl))
2622 FunctionKind = 2;
2623 else if (isa<CXXDestructorDecl>(CurDecl))
2624 FunctionKind = 3;
2625
2626 Diag(ReturnLoc, diag::err_return_init_list)
2627 << CurDecl->getDeclName() << FunctionKind
2628 << RetValExp->getSourceRange();
2629
2630 // Drop the expression.
2631 RetValExp = 0;
2632 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002633 // C99 6.8.6.4p1 (ext_ since GCC warns)
2634 unsigned D = diag::ext_return_has_expr;
2635 if (RetValExp->getType()->isVoidType())
2636 D = diag::ext_return_has_void_expr;
2637 else {
2638 ExprResult Result = Owned(RetValExp);
2639 Result = IgnoredValueConversions(Result.take());
2640 if (Result.isInvalid())
2641 return StmtError();
2642 RetValExp = Result.take();
2643 RetValExp = ImpCastExprToType(RetValExp,
2644 Context.VoidTy, CK_ToVoid).take();
2645 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002646
Nick Lewycky8d794612011-06-01 07:44:31 +00002647 // return (some void expression); is legal in C++.
2648 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002649 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002650 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002651
2652 int FunctionKind = 0;
2653 if (isa<ObjCMethodDecl>(CurDecl))
2654 FunctionKind = 1;
2655 else if (isa<CXXConstructorDecl>(CurDecl))
2656 FunctionKind = 2;
2657 else if (isa<CXXDestructorDecl>(CurDecl))
2658 FunctionKind = 3;
2659
Nick Lewycky8d794612011-06-01 07:44:31 +00002660 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002661 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002662 << RetValExp->getSourceRange();
2663 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002664 }
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Sebastian Redl33deb352012-02-22 10:50:08 +00002666 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002667 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2668 if (ER.isInvalid())
2669 return StmtError();
2670 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002671 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002672 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002673
Douglas Gregor5077c382010-05-15 06:01:05 +00002674 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
Richard Smith60e141e2013-05-04 07:00:32 +00002675 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002676 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2677 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002678 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002679
2680 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002681 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002682 else
Chris Lattner08631c52008-11-23 21:45:46 +00002683 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002684 Result = new (Context) ReturnStmt(ReturnLoc);
2685 } else {
Richard Smith60e141e2013-05-04 07:00:32 +00002686 assert(RetValExp || HasDependentReturnType);
Douglas Gregor5077c382010-05-15 06:01:05 +00002687 const VarDecl *NRVOCandidate = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00002688 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor5077c382010-05-15 06:01:05 +00002689 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002690
John McCall7cca8212013-03-19 07:04:25 +00002691 QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
Eli Friedman38ac2432012-03-30 01:13:43 +00002692
Douglas Gregor5077c382010-05-15 06:01:05 +00002693 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2694 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2695 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002696
John McCall856d3792011-06-16 23:24:51 +00002697 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002698 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002699 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall7cca8212013-03-19 07:04:25 +00002701 RetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002702 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002703 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall7cca8212013-03-19 07:04:25 +00002704 RetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002705 if (Res.isInvalid()) {
John McCall7cca8212013-03-19 07:04:25 +00002706 // FIXME: Clean up temporaries here anyway?
Douglas Gregor5077c382010-05-15 06:01:05 +00002707 return StmtError();
2708 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002709 RetValExp = Res.takeAs<Expr>();
John McCall7cca8212013-03-19 07:04:25 +00002710
2711 // If we have a related result type, we need to implicitly
2712 // convert back to the formal result type. We can't pretend to
2713 // initialize the result again --- we might end double-retaining
2714 // --- so instead we initialize a notional temporary; this can
2715 // lead to less-than-great diagnostics, but this stage is much
2716 // less likely to fail than the previous stage.
2717 if (!RelatedRetType.isNull()) {
2718 Entity = InitializedEntity::InitializeTemporary(FnRetType);
2719 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
2720 if (Res.isInvalid()) {
2721 // FIXME: Clean up temporaries here anyway?
2722 return StmtError();
2723 }
2724 RetValExp = Res.takeAs<Expr>();
2725 }
2726
2727 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002728 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002729
John McCallb4eb64d2010-10-08 02:01:28 +00002730 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002731 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2732 if (ER.isInvalid())
2733 return StmtError();
2734 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002735 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002736 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002737 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002738
2739 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002740 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002741 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002742 !CurContext->isDependentContext())
2743 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002744
Douglas Gregor5077c382010-05-15 06:01:05 +00002745 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002746}
2747
John McCall60d7b3a2010-08-24 06:29:42 +00002748StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002749Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002750 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002751 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002752 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002753 if (Var && Var->isInvalidDecl())
2754 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002755
John McCall9ae2f072010-08-23 23:25:46 +00002756 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002757}
2758
John McCall60d7b3a2010-08-24 06:29:42 +00002759StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002760Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2761 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002762}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002763
John McCall60d7b3a2010-08-24 06:29:42 +00002764StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002765Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002766 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002767 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002768 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2769
John McCall781472f2010-08-25 08:40:02 +00002770 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002771 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002772 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002773 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002774 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002775 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002776}
2777
John McCalld1376ee2012-05-08 21:41:25 +00002778StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002779 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002780 ExprResult Result = DefaultLvalueConversion(Throw);
2781 if (Result.isInvalid())
2782 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002783
Richard Smith41956372013-01-14 22:39:08 +00002784 Result = ActOnFinishFullExpr(Result.take());
2785 if (Result.isInvalid())
2786 return StmtError();
2787 Throw = Result.take();
2788
Douglas Gregord1377b22010-04-22 21:44:01 +00002789 QualType ThrowType = Throw->getType();
2790 // Make sure the expression type is an ObjC pointer or "void *".
2791 if (!ThrowType->isDependentType() &&
2792 !ThrowType->isObjCObjectPointerType()) {
2793 const PointerType *PT = ThrowType->getAs<PointerType>();
2794 if (!PT || !PT->getPointeeType()->isVoidType())
2795 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2796 << Throw->getType() << Throw->getSourceRange());
2797 }
2798 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002799
John McCall9ae2f072010-08-23 23:25:46 +00002800 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002801}
2802
John McCall60d7b3a2010-08-24 06:29:42 +00002803StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002804Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002805 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002806 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002807 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2808
John McCall9ae2f072010-08-23 23:25:46 +00002809 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002810 // @throw without an expression designates a rethrow (which much occur
2811 // in the context of an @catch clause).
2812 Scope *AtCatchParent = CurScope;
2813 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2814 AtCatchParent = AtCatchParent->getParent();
2815 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002816 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002817 }
John McCall9ae2f072010-08-23 23:25:46 +00002818 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002819}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002820
John McCall07524032011-07-27 21:50:02 +00002821ExprResult
2822Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2823 ExprResult result = DefaultLvalueConversion(operand);
2824 if (result.isInvalid())
2825 return ExprError();
2826 operand = result.take();
2827
2828 // Make sure the expression type is an ObjC pointer or "void *".
2829 QualType type = operand->getType();
2830 if (!type->isDependentType() &&
2831 !type->isObjCObjectPointerType()) {
2832 const PointerType *pointerType = type->getAs<PointerType>();
2833 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2834 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2835 << type << operand->getSourceRange();
2836 }
2837
2838 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002839 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002840}
2841
John McCall60d7b3a2010-08-24 06:29:42 +00002842StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002843Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2844 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002845 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002846 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002847 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002848}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002849
2850/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2851/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002852StmtResult
John McCalld226f652010-08-21 09:40:31 +00002853Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002854 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002855 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002856 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002857 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002858 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002859}
Sebastian Redl8351da02008-12-22 21:35:02 +00002860
John McCallf85e1932011-06-15 23:02:42 +00002861StmtResult
2862Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2863 getCurFunction()->setHasBranchProtectedScope();
2864 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2865}
2866
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002867namespace {
2868
Sebastian Redlc447aba2009-07-29 17:15:45 +00002869class TypeWithHandler {
2870 QualType t;
2871 CXXCatchStmt *stmt;
2872public:
2873 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2874 : t(type), stmt(statement) {}
2875
John McCall0953e762009-09-24 19:53:00 +00002876 // An arbitrary order is fine as long as it places identical
2877 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002878 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002879 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002880 return true;
John McCall0953e762009-09-24 19:53:00 +00002881 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002882 return false;
2883 else
2884 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Sebastian Redlc447aba2009-07-29 17:15:45 +00002887 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002888 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002889 }
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Sebastian Redlc447aba2009-07-29 17:15:45 +00002891 CXXCatchStmt *getCatchStmt() const { return stmt; }
2892 SourceLocation getTypeSpecStartLoc() const {
2893 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2894 }
2895};
2896
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002897}
2898
Sebastian Redl8351da02008-12-22 21:35:02 +00002899/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2900/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002901StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002902Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002903 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002904 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002905 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002906 !getSourceManager().isInSystemHeader(TryLoc))
2907 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002908
Sebastian Redl8351da02008-12-22 21:35:02 +00002909 unsigned NumHandlers = RawHandlers.size();
2910 assert(NumHandlers > 0 &&
2911 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002912 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002913
Chris Lattner5f9e2722011-07-23 10:55:15 +00002914 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002915
2916 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002917 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002918 if (!Handler->getExceptionDecl()) {
2919 if (i < NumHandlers - 1)
2920 return StmtError(Diag(Handler->getLocStart(),
2921 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002922
Sebastian Redlc447aba2009-07-29 17:15:45 +00002923 continue;
2924 }
Mike Stump1eb44332009-09-09 15:08:12 +00002925
Sebastian Redlc447aba2009-07-29 17:15:45 +00002926 const QualType CaughtType = Handler->getCaughtType();
2927 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2928 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002929 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002930
2931 // Detect handlers for the same type as an earlier one.
2932 if (NumHandlers > 1) {
2933 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Sebastian Redlc447aba2009-07-29 17:15:45 +00002935 TypeWithHandler prev = TypesWithHandlers[0];
2936 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2937 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002938
Sebastian Redlc447aba2009-07-29 17:15:45 +00002939 if (curr == prev) {
2940 Diag(curr.getTypeSpecStartLoc(),
2941 diag::warn_exception_caught_by_earlier_handler)
2942 << curr.getCatchStmt()->getCaughtType().getAsString();
2943 Diag(prev.getTypeSpecStartLoc(),
2944 diag::note_previous_exception_handler)
2945 << prev.getCatchStmt()->getCaughtType().getAsString();
2946 }
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Sebastian Redlc447aba2009-07-29 17:15:45 +00002948 prev = curr;
2949 }
2950 }
Mike Stump1eb44332009-09-09 15:08:12 +00002951
John McCall781472f2010-08-25 08:40:02 +00002952 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002953
Sebastian Redl8351da02008-12-22 21:35:02 +00002954 // FIXME: We should detect handlers that cannot catch anything because an
2955 // earlier handler catches a superclass. Need to find a method that is not
2956 // quadratic for this.
2957 // Neither of these are explicitly forbidden, but every compiler detects them
2958 // and warns.
2959
John McCall9ae2f072010-08-23 23:25:46 +00002960 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002961 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002962}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002963
2964StmtResult
2965Sema::ActOnSEHTryBlock(bool IsCXXTry,
2966 SourceLocation TryLoc,
2967 Stmt *TryBlock,
2968 Stmt *Handler) {
2969 assert(TryBlock && Handler);
2970
2971 getCurFunction()->setHasBranchProtectedScope();
2972
2973 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2974}
2975
2976StmtResult
2977Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2978 Expr *FilterExpr,
2979 Stmt *Block) {
2980 assert(FilterExpr && Block);
2981
2982 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002983 return StmtError(Diag(FilterExpr->getExprLoc(),
2984 diag::err_filter_expression_integral)
2985 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002986 }
2987
2988 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2989}
2990
2991StmtResult
2992Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2993 Stmt *Block) {
2994 assert(Block);
2995 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2996}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002997
2998StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2999 bool IsIfExists,
3000 NestedNameSpecifierLoc QualifierLoc,
3001 DeclarationNameInfo NameInfo,
3002 Stmt *Nested)
3003{
3004 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003005 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003006 cast<CompoundStmt>(Nested));
3007}
3008
3009
Chad Rosier1093f492012-08-10 17:56:09 +00003010StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003011 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003012 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003013 UnqualifiedId &Name,
3014 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00003015 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003016 SS.getWithLocInContext(Context),
3017 GetNameFromUnqualifiedId(Name),
3018 Nested);
3019}
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003020
3021RecordDecl*
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003022Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3023 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003024 DeclContext *DC = CurContext;
3025 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3026 DC = DC->getParent();
3027
3028 RecordDecl *RD = 0;
3029 if (getLangOpts().CPlusPlus)
3030 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3031 else
3032 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3033
3034 DC->addDecl(RD);
3035 RD->setImplicit();
3036 RD->startDefinition();
3037
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003038 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003039 DC->addDecl(CD);
3040
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003041 // Build the context parameter
3042 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3043 DC = CapturedDecl::castToDeclContext(CD);
3044 IdentifierInfo *VarName = &Context.Idents.get("__context");
3045 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3046 ImplicitParamDecl *Param
3047 = ImplicitParamDecl::Create(Context, DC, Loc, VarName, ParamType);
3048 DC->addDecl(Param);
3049
3050 CD->setContextParam(Param);
3051
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003052 return RD;
3053}
3054
3055static void buildCapturedStmtCaptureList(
3056 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3057 SmallVectorImpl<Expr *> &CaptureInits,
3058 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3059
3060 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3061 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3062
3063 if (Cap->isThisCapture()) {
3064 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3065 CapturedStmt::VCK_This));
Richard Smith0d8e9642013-05-16 06:20:58 +00003066 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003067 continue;
3068 }
3069
3070 assert(Cap->isReferenceCapture() &&
3071 "non-reference capture not yet implemented");
3072
3073 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3074 CapturedStmt::VCK_ByRef,
3075 Cap->getVariable()));
Richard Smith0d8e9642013-05-16 06:20:58 +00003076 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003077 }
3078}
3079
3080void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003081 CapturedRegionKind Kind,
3082 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003083 CapturedDecl *CD = 0;
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003084 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003085
3086 // Enter the capturing scope for this captured region.
3087 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3088
3089 if (CurScope)
3090 PushDeclContext(CurScope, CD);
3091 else
3092 CurContext = CD;
3093
3094 PushExpressionEvaluationContext(PotentiallyEvaluated);
3095}
3096
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003097void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003098 DiscardCleanupsInEvaluationContext();
3099 PopExpressionEvaluationContext();
3100
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003101 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3102 RecordDecl *Record = RSI->TheRecordDecl;
3103 Record->setInvalidDecl();
3104
3105 SmallVector<Decl*, 4> Fields;
3106 for (RecordDecl::field_iterator I = Record->field_begin(),
3107 E = Record->field_end(); I != E; ++I)
3108 Fields.push_back(*I);
3109 ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
3110 SourceLocation(), SourceLocation(), /*AttributeList=*/0);
3111
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003112 PopDeclContext();
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003113 PopFunctionScopeInfo();
3114}
3115
3116StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3117 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3118
3119 SmallVector<CapturedStmt::Capture, 4> Captures;
3120 SmallVector<Expr *, 4> CaptureInits;
3121 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3122
3123 CapturedDecl *CD = RSI->TheCapturedDecl;
3124 RecordDecl *RD = RSI->TheRecordDecl;
3125
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003126 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3127 RSI->CapRegionKind, Captures,
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003128 CaptureInits, CD, RD);
3129
3130 CD->setBody(Res->getCapturedStmt());
3131 RD->completeDefinition();
3132
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003133 DiscardCleanupsInEvaluationContext();
3134 PopExpressionEvaluationContext();
3135
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003136 PopDeclContext();
3137 PopFunctionScopeInfo();
3138
3139 return Owned(Res);
3140}