blob: dcb86b780b193e8fbd44bc5aabbdff81fd458ee6 [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"
Anders Carlsson6fa90862007-11-25 00:25:21 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000031#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000038
Richard Smith41956372013-01-14 22:39:08 +000039StmtResult Sema::ActOnExprStmt(ExprResult FE) {
40 if (FE.isInvalid())
41 return StmtError();
42
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
45 if (FE.isInvalid())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000046 return StmtError();
47
Chris Lattner834a72a2008-07-25 23:18:17 +000048 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000051
Chris Lattner834a72a2008-07-25 23:18:17 +000052 // Same thing in for stmt first clause (when expr) and third clause.
Richard Smith41956372013-01-14 22:39:08 +000053 return Owned(static_cast<Stmt*>(FE.take()));
Reid Spencer5f016e22007-07-11 17:01:13 +000054}
55
56
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000057StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000058 bool HasLeadingEmptyMacro) {
59 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000060}
61
Chris Lattner337e5502011-02-18 01:27:55 +000062StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
63 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000064 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner20401692009-04-12 20:13:14 +000066 // If we have an invalid decl, just return an error.
67 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000068
Chris Lattner24e1e702009-03-04 04:23:07 +000069 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000070}
71
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000072void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
73 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000074
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000075 // If we have an invalid decl, just return.
76 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000077 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
78
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000079 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000080 var->setUsed();
81
John McCall7acddac2011-06-17 06:42:21 +000082 // foreach variables are never actually initialized in the way that
83 // the parser came up with.
84 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000085
John McCall7acddac2011-06-17 06:42:21 +000086 // In ARC, we don't need to retain the iteration variable of a fast
87 // enumeration loop. Rather than actually trying to catch that
88 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000089 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000090 QualType type = var->getType();
91
92 // Only do this if we inferred the lifetime. Inferred lifetime
93 // will show up as a local qualifier because explicit lifetime
94 // should have shown up as an AttributedType instead.
95 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
96 // Add 'const' and mark the variable as pseudo-strong.
97 var->setType(type.withConst());
98 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000099 }
100 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +0000101}
102
Chandler Carruthec8058f2011-08-17 09:34:37 +0000103/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000104///
105/// Adding a cast to void (or other expression wrappers) will prevent the
106/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000107static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000108 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000109 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110
111 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
112 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000113 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000114
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000115 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000116 IsNotEqual = Op->getOpcode() == BO_NE;
117 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
119 if (Op->getOperator() != OO_EqualEqual &&
120 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000121 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000122
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000123 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000124 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
125 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000126 } else {
127 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000128 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000129 }
130
131 // Suppress warnings when the operator, suspicious as it may be, comes from
132 // a macro expansion.
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +0000133 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthec8058f2011-08-17 09:34:37 +0000134 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000135
Chandler Carruthec8058f2011-08-17 09:34:37 +0000136 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000137 << (unsigned)IsNotEqual << E->getSourceRange();
138
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000139 // If the LHS is a plausible entity to assign to, provide a fixit hint to
140 // correct common typos.
141 if (CanAssign) {
142 if (IsNotEqual)
143 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
144 << FixItHint::CreateReplacement(Loc, "|=");
145 else
146 S.Diag(Loc, diag::note_equality_comparison_to_assign)
147 << FixItHint::CreateReplacement(Loc, "=");
148 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000149
150 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000151}
152
Anders Carlsson636463e2009-07-30 22:17:18 +0000153void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000154 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
155 return DiagnoseUnusedExprResult(Label->getSubStmt());
156
Anders Carlsson75443112009-07-30 22:39:03 +0000157 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000158 if (!E)
159 return;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000160 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
161 if (SourceMgr.isInSystemMacro(ExprLoc) ||
162 SourceMgr.isMacroBodyExpansion(ExprLoc))
163 return;
Anders Carlsson636463e2009-07-30 22:17:18 +0000164
Eli Friedmana6115062012-05-24 00:47:05 +0000165 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000166 SourceLocation Loc;
167 SourceRange R1, R2;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000168 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000169 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Chris Lattner06b3a062012-08-31 22:39:21 +0000171 // If this is a GNU statement expression expanded from a macro, it is probably
172 // unused because it is a function-like macro that can be used as either an
173 // expression or statement. Don't warn, because it is almost certainly a
174 // false positive.
175 if (isa<StmtExpr>(E) && Loc.isMacroID())
176 return;
177
Chris Lattner419cfb32009-08-16 16:57:27 +0000178 // Okay, we have an unused result. Depending on what the base expression is,
179 // we might want to make a more specific diagnostic. Check for one of these
180 // cases now.
181 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000182 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000183 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000184 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
185 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000186
Chandler Carruthec8058f2011-08-17 09:34:37 +0000187 if (DiagnoseUnusedComparison(*this, E))
188 return;
189
Eli Friedmana6115062012-05-24 00:47:05 +0000190 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000191 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000192 if (E->getType()->isVoidType())
193 return;
194
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000195 // If the callee has attribute pure, const, or warn_unused_result, warn with
196 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000197 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000198 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000199 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000200 return;
201 }
202 if (FD->getAttr<PureAttr>()) {
203 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
204 return;
205 }
206 if (FD->getAttr<ConstAttr>()) {
207 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
208 return;
209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000210 }
John McCall12f78a62010-12-02 01:19:52 +0000211 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000212 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000213 Diag(Loc, diag::err_arc_unused_init_message) << R1;
214 return;
215 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000216 const ObjCMethodDecl *MD = ME->getMethodDecl();
217 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000218 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000219 return;
220 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000221 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
222 const Expr *Source = POE->getSyntacticForm();
223 if (isa<ObjCSubscriptRefExpr>(Source))
224 DiagID = diag::warn_unused_container_subscript_expr;
225 else
226 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000227 } else if (const CXXFunctionalCastExpr *FC
228 = dyn_cast<CXXFunctionalCastExpr>(E)) {
229 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
230 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
231 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000232 }
John McCall209acbd2010-04-06 22:24:14 +0000233 // Diagnose "(void*) blah" as a typo for "(void) blah".
234 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
235 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
236 QualType T = TI->getType();
237
238 // We really do want to use the non-canonical type here.
239 if (T == Context.VoidPtrTy) {
240 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
241
242 Diag(Loc, diag::warn_unused_voidptr)
243 << FixItHint::CreateRemoval(TL.getStarLoc());
244 return;
245 }
246 }
247
Eli Friedmana6115062012-05-24 00:47:05 +0000248 if (E->isGLValue() && E->getType().isVolatileQualified()) {
249 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
250 return;
251 }
252
Ted Kremenek351ba912011-02-23 01:52:04 +0000253 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000254}
255
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000256void Sema::ActOnStartOfCompoundStmt() {
257 PushCompoundScope();
258}
259
260void Sema::ActOnFinishOfCompoundStmt() {
261 PopCompoundScope();
262}
263
264sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
265 return getCurFunction()->CompoundScopes.back();
266}
267
John McCall60d7b3a2010-08-24 06:29:42 +0000268StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000269Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000270 MultiStmtArg elts, bool isStmtExpr) {
271 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000272 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000273 // If we're in C89 mode, check that we don't have any decls after stmts. If
274 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000275 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000276 // Note that __extension__ can be around a decl.
277 unsigned i = 0;
278 // Skip over all declarations.
279 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
280 /*empty*/;
281
282 // We found the end of the list or a statement. Scan for another declstmt.
283 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
284 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000286 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000287 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000288 Diag(D->getLocation(), diag::ext_mixed_decls_code);
289 }
290 }
Chris Lattner98414c12007-08-31 21:49:55 +0000291 // Warn about unused expressions in statements.
292 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000293 // Ignore statements that are last in a statement expression.
294 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000295 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Anders Carlsson636463e2009-07-30 22:17:18 +0000297 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000298 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000299
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000300 // Check for suspicious empty body (null statement) in `for' and `while'
301 // statements. Don't do anything for template instantiations, this just adds
302 // noise.
303 if (NumElts != 0 && !CurrentInstantiationScope &&
304 getCurCompoundScope().HasEmptyLoopBodies) {
305 for (unsigned i = 0; i != NumElts - 1; ++i)
306 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
307 }
308
Nico Weberd36aa352012-12-29 20:03:39 +0000309 return Owned(new (Context) CompoundStmt(Context,
310 llvm::makeArrayRef(Elts, NumElts),
311 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000312}
313
John McCall60d7b3a2010-08-24 06:29:42 +0000314StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000315Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
316 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000317 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000318 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000319
John McCall781472f2010-08-25 08:40:02 +0000320 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000321 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000322 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000323 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000324
Richard Smith80ad52f2013-01-02 11:42:31 +0000325 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000326 // C99 6.8.4.2p3: The expression shall be an integer constant.
327 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000328 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
329 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
330 if (!LHSVal)
331 return StmtError();
332 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000333
334 // GCC extension: The expression shall be an integer constant.
335
Richard Smith282e7e62012-02-04 09:53:13 +0000336 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
337 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
338 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000339 }
340 }
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000341
342 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
343 getLangOpts().CPlusPlus11).take();
344 if (RHSVal)
345 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
346 getLangOpts().CPlusPlus11).take();
Richard Smith8ef7b202012-01-18 23:55:52 +0000347
Douglas Gregordbb26db2009-05-15 23:57:33 +0000348 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
349 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000350 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000351 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
Chris Lattner24e1e702009-03-04 04:23:07 +0000354/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000355void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000356 DiagnoseUnusedExprResult(SubStmt);
357
Chris Lattner24e1e702009-03-04 04:23:07 +0000358 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000359 CS->setSubStmt(SubStmt);
360}
361
John McCall60d7b3a2010-08-24 06:29:42 +0000362StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000363Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000364 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000365 DiagnoseUnusedExprResult(SubStmt);
366
John McCall781472f2010-08-25 08:40:02 +0000367 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000368 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000369 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000370 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000371
Douglas Gregordbb26db2009-05-15 23:57:33 +0000372 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000373 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000374 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000375}
376
John McCall60d7b3a2010-08-24 06:29:42 +0000377StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000378Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
379 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000380 // If the label was multiply defined, reject it now.
381 if (TheDecl->getStmt()) {
382 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
383 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000384 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 }
Sebastian Redlde307472009-01-11 00:38:46 +0000386
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000387 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000388 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
389 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000390 if (!TheDecl->isGnuLocal()) {
391 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000392 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000393 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000394 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000395}
396
Richard Smith534986f2012-04-14 00:33:13 +0000397StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000398 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000399 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000400 // Fill in the declaration and return it.
401 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000402 return Owned(LS);
403}
404
John McCall60d7b3a2010-08-24 06:29:42 +0000405StmtResult
John McCalld226f652010-08-21 09:40:31 +0000406Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000407 Stmt *thenStmt, SourceLocation ElseLoc,
408 Stmt *elseStmt) {
Argyrios Kyrtzidis820b23d2013-02-15 18:34:13 +0000409 // If the condition was invalid, discard the if statement. We could recover
410 // better by replacing it with a valid expr, but don't do that yet.
411 if (!CondVal.get() && !CondVar) {
412 getCurFunction()->setHasDroppedStmt();
413 return StmtError();
414 }
415
John McCall60d7b3a2010-08-24 06:29:42 +0000416 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000418 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000419 if (CondVar) {
420 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000421 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000422 if (CondResult.isInvalid())
423 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000424 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000425 Expr *ConditionExpr = CondResult.takeAs<Expr>();
426 if (!ConditionExpr)
427 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000428
Anders Carlsson75443112009-07-30 22:39:03 +0000429 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000430
John McCall9ae2f072010-08-23 23:25:46 +0000431 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000432 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
433 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000434 }
435
Anders Carlsson75443112009-07-30 22:39:03 +0000436 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000438 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000439 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000440}
441
Chris Lattnerf4021e72007-08-23 05:46:52 +0000442/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
443/// the specified width and sign. If an overflow occurs, detect it and emit
444/// the specified diagnostic.
445void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
446 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000447 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000448 unsigned DiagID) {
449 // Perform a conversion to the promoted condition type if needed.
450 if (NewWidth > Val.getBitWidth()) {
451 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000452 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000453 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000454
455 // If the input was signed and negative and the output is
456 // unsigned, don't bother to warn: this is implementation-defined
457 // behavior.
458 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000459 } else if (NewWidth < Val.getBitWidth()) {
460 // If this is a truncation, check for overflow.
461 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000462 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000463 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000464 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000465 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000466 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000467 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chris Lattnerf4021e72007-08-23 05:46:52 +0000469 // Regardless of whether a diagnostic was emitted, really do the
470 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000471 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000472 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000473 } else if (NewSign != Val.isSigned()) {
474 // Convert the sign to match the sign of the condition. This can cause
475 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000476 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000477 // behavior.
478 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000479 llvm::APSInt OldVal(Val);
480 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000481 }
482}
483
Chris Lattner0471f5b2007-08-23 18:29:20 +0000484namespace {
485 struct CaseCompareFunctor {
486 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
487 const llvm::APSInt &RHS) {
488 return LHS.first < RHS;
489 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000490 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
491 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
492 return LHS.first < RHS.first;
493 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000494 bool operator()(const llvm::APSInt &LHS,
495 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
496 return LHS < RHS.first;
497 }
498 };
499}
500
Chris Lattner764a7ce2007-09-21 18:15:22 +0000501/// CmpCaseVals - Comparison predicate for sorting case values.
502///
503static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
504 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
505 if (lhs.first < rhs.first)
506 return true;
507
508 if (lhs.first == rhs.first &&
509 lhs.second->getCaseLoc().getRawEncoding()
510 < rhs.second->getCaseLoc().getRawEncoding())
511 return true;
512 return false;
513}
514
Douglas Gregorba915af2010-02-08 22:24:16 +0000515/// CmpEnumVals - Comparison predicate for sorting enumeration values.
516///
517static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
518 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
519{
520 return lhs.first < rhs.first;
521}
522
523/// EqEnumVals - Comparison preficate for uniqing enumeration values.
524///
525static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
526 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
527{
528 return lhs.first == rhs.first;
529}
530
Chris Lattner5f048812009-10-16 16:45:22 +0000531/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
532/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000533static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
534 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
535 expr = cleanups->getSubExpr();
536 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
537 if (impcast->getCastKind() != CK_IntegralCast) break;
538 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000539 }
540 return expr->getType();
541}
542
John McCall60d7b3a2010-08-24 06:29:42 +0000543StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000545 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000546 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000547
Douglas Gregor586596f2010-05-06 17:25:47 +0000548 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000549 if (CondVar) {
550 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000551 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
552 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000553 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554
John McCall9ae2f072010-08-23 23:25:46 +0000555 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000556 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000557
John McCall9ae2f072010-08-23 23:25:46 +0000558 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000559 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000560
Douglas Gregorab41fe92012-05-04 22:38:52 +0000561 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
562 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000563
Douglas Gregorab41fe92012-05-04 22:38:52 +0000564 public:
565 SwitchConvertDiagnoser(Expr *Cond)
566 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000567
Douglas Gregorab41fe92012-05-04 22:38:52 +0000568 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
569 QualType T) {
570 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
571 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000572
Douglas Gregorab41fe92012-05-04 22:38:52 +0000573 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
574 QualType T) {
575 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
576 << T << Cond->getSourceRange();
577 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000578
Douglas Gregorab41fe92012-05-04 22:38:52 +0000579 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
580 QualType T,
581 QualType ConvTy) {
582 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
583 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000584
Douglas Gregorab41fe92012-05-04 22:38:52 +0000585 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
586 QualType ConvTy) {
587 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
588 << ConvTy->isEnumeralType() << ConvTy;
589 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000590
Douglas Gregorab41fe92012-05-04 22:38:52 +0000591 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
592 QualType T) {
593 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
594 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000595
Douglas Gregorab41fe92012-05-04 22:38:52 +0000596 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
597 QualType ConvTy) {
598 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
599 << ConvTy->isEnumeralType() << ConvTy;
600 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000601
Douglas Gregorab41fe92012-05-04 22:38:52 +0000602 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
603 QualType T,
604 QualType ConvTy) {
605 return DiagnosticBuilder::getEmpty();
606 }
607 } SwitchDiagnoser(Cond);
608
John McCall9ae2f072010-08-23 23:25:46 +0000609 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000610 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000611 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000612 if (CondResult.isInvalid()) return StmtError();
613 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000614
John McCalla8e0cd82011-08-06 07:30:58 +0000615 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
616 CondResult = UsualUnaryConversions(Cond);
617 if (CondResult.isInvalid()) return StmtError();
618 Cond = CondResult.take();
619
John McCalld226f652010-08-21 09:40:31 +0000620 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000621 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000622 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000623 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000624 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000625 }
John McCallb60a77e2010-08-01 00:26:45 +0000626
John McCall781472f2010-08-25 08:40:02 +0000627 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628
John McCall9ae2f072010-08-23 23:25:46 +0000629 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000630 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000631 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000632}
633
Gabor Greif28164ab2010-10-01 22:05:14 +0000634static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
635 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000636 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000637 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000638 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000639 Val.setIsSigned(IsSigned);
640}
641
John McCall60d7b3a2010-08-24 06:29:42 +0000642StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000643Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
644 Stmt *BodyStmt) {
645 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000646 assert(SS == getCurFunction()->SwitchStack.back() &&
647 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000648
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000649 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000650 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000651
Chris Lattnerf4021e72007-08-23 05:46:52 +0000652 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000653 if (!CondExpr) return StmtError();
654
655 QualType CondType = CondExpr->getType();
656
John McCall0fb97082010-05-18 03:19:21 +0000657 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000658 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000659 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000660
Chris Lattner5f048812009-10-16 16:45:22 +0000661 // C++ 6.4.2.p2:
662 // Integral promotions are performed (on the switch condition).
663 //
664 // A case value unrepresentable by the original switch condition
665 // type (before the promotion) doesn't make sense, even when it can
666 // be represented by the promoted type. Therefore we need to find
667 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000668 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000669 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000670 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000671 // appropriate type now, just return an error.
672 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000673 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000674
Chris Lattner2b334bb2010-04-16 23:34:13 +0000675 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000676 // switch(bool_expr) {...} is often a programmer error, e.g.
677 // switch(n && mask) { ... } // Doh - should be "n & mask".
678 // One can always use an if statement instead of switch(bool_expr).
679 Diag(SwitchLoc, diag::warn_bool_switch_condition)
680 << CondExpr->getSourceRange();
681 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000682 }
Sebastian Redlde307472009-01-11 00:38:46 +0000683
Chris Lattnerf4021e72007-08-23 05:46:52 +0000684 // Get the bitwidth of the switched-on value before promotions. We must
685 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000686 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000687 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000688 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000689 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000690 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000691 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattnerf4021e72007-08-23 05:46:52 +0000693 // Accumulate all of the case values in a vector so that we can sort them
694 // and detect duplicates. This vector contains the APInt for the case after
695 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000696 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000697 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattnerf4021e72007-08-23 05:46:52 +0000699 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000700 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
701 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerf4021e72007-08-23 05:46:52 +0000703 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000705 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Douglas Gregordbb26db2009-05-15 23:57:33 +0000707 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000708 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000710 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000711 if (TheDefaultStmt) {
712 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000713 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000714
Chris Lattnerf4021e72007-08-23 05:46:52 +0000715 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000716 // we'll return a valid AST. This requires recursing down the AST and
717 // finding it, not something we are set up to do right now. For now,
718 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000719 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000720 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000721 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chris Lattnerf4021e72007-08-23 05:46:52 +0000723 } else {
724 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattner1e0a3902008-01-16 19:17:22 +0000726 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000727
728 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
729 HasDependentValue = true;
730 break;
731 }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Richard Smith8ef7b202012-01-18 23:55:52 +0000733 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Richard Smith80ad52f2013-01-02 11:42:31 +0000735 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000736 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
737 // constant expression of the promoted type of the switch condition.
738 ExprResult ConvLo =
739 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
740 if (ConvLo.isInvalid()) {
741 CaseListIsErroneous = true;
742 continue;
743 }
744 Lo = ConvLo.take();
745 } else {
746 // We already verified that the expression has a i-c-e value (C99
747 // 6.8.4.2p3) - get that value now.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000748 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smith8ef7b202012-01-18 23:55:52 +0000749
750 // If the LHS is not the same type as the condition, insert an implicit
751 // cast.
752 Lo = DefaultLvalueConversion(Lo).take();
753 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
754 }
755
756 // Convert the value to the same width/sign as the condition had prior to
757 // integral promotions.
758 //
759 // FIXME: This causes us to reject valid code:
760 // switch ((char)c) { case 256: case 0: return 0; }
761 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000762 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000763 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000764 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000765
Chris Lattner1e0a3902008-01-16 19:17:22 +0000766 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000768 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000769 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000770 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000771 CS->getRHS()->isValueDependent()) {
772 HasDependentValue = true;
773 break;
774 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000775 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000776 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000777 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000778 }
779 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000780
781 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000782 // If we don't have a default statement, check whether the
783 // condition is constant.
784 llvm::APSInt ConstantCondValue;
785 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000786 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000787 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000788 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
789 Expr::SE_AllowSideEffects);
790 assert(!HasConstantCond ||
791 (ConstantCondValue.getBitWidth() == CondWidth &&
792 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000793 }
Richard Smith80d4b552011-12-28 19:48:30 +0000794 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000795
Douglas Gregordbb26db2009-05-15 23:57:33 +0000796 // Sort all the scalar case values so we can easily detect duplicates.
797 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
798
799 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000800 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
801 if (ShouldCheckConstantCond &&
802 CaseVals[i].first == ConstantCondValue)
803 ShouldCheckConstantCond = false;
804
805 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000806 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000807 // First, determine if either case value has a name
808 StringRef PrevString, CurrString;
809 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
810 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
811 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
812 PrevString = DeclRef->getDecl()->getName();
813 }
814 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
815 CurrString = DeclRef->getDecl()->getName();
816 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000817 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000818 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000819
820 if (PrevString == CurrString)
821 Diag(CaseVals[i].second->getLHS()->getLocStart(),
822 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000823 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000824 else
825 Diag(CaseVals[i].second->getLHS()->getLocStart(),
826 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000827 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
828 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000829 CaseValStr;
830
John McCall0fb97082010-05-18 03:19:21 +0000831 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000832 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000833 // FIXME: We really want to remove the bogus case stmt from the
834 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000835 CaseListIsErroneous = true;
836 }
837 }
838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregordbb26db2009-05-15 23:57:33 +0000840 // Detect duplicate case ranges, which usually don't exist at all in
841 // the first place.
842 if (!CaseRanges.empty()) {
843 // Sort all the case ranges by their low value so we can easily detect
844 // overlaps between ranges.
845 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Douglas Gregordbb26db2009-05-15 23:57:33 +0000847 // Scan the ranges, computing the high values and removing empty ranges.
848 std::vector<llvm::APSInt> HiVals;
849 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000850 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000851 CaseStmt *CR = CaseRanges[i].second;
852 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000853 llvm::APSInt HiVal;
854
Richard Smith80ad52f2013-01-02 11:42:31 +0000855 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000856 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
857 // constant expression of the promoted type of the switch condition.
858 ExprResult ConvHi =
859 CheckConvertedConstantExpression(Hi, CondType, HiVal,
860 CCEK_CaseValue);
861 if (ConvHi.isInvalid()) {
862 CaseListIsErroneous = true;
863 continue;
864 }
865 Hi = ConvHi.take();
866 } else {
867 HiVal = Hi->EvaluateKnownConstInt(Context);
868
869 // If the RHS is not the same type as the condition, insert an
870 // implicit cast.
871 Hi = DefaultLvalueConversion(Hi).take();
872 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Douglas Gregordbb26db2009-05-15 23:57:33 +0000875 // Convert the value to the same width/sign as the condition.
876 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000877 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000878 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Douglas Gregordbb26db2009-05-15 23:57:33 +0000880 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Douglas Gregordbb26db2009-05-15 23:57:33 +0000882 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000883 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000884 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
885 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000886 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000887 CaseRanges.erase(CaseRanges.begin()+i);
888 --i, --e;
889 continue;
890 }
John McCall0fb97082010-05-18 03:19:21 +0000891
892 if (ShouldCheckConstantCond &&
893 LoVal <= ConstantCondValue &&
894 ConstantCondValue <= HiVal)
895 ShouldCheckConstantCond = false;
896
Douglas Gregordbb26db2009-05-15 23:57:33 +0000897 HiVals.push_back(HiVal);
898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Douglas Gregordbb26db2009-05-15 23:57:33 +0000900 // Rescan the ranges, looking for overlap with singleton values and other
901 // ranges. Since the range list is sorted, we only need to compare case
902 // ranges with their neighbors.
903 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
904 llvm::APSInt &CRLo = CaseRanges[i].first;
905 llvm::APSInt &CRHi = HiVals[i];
906 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Douglas Gregordbb26db2009-05-15 23:57:33 +0000908 // Check to see whether the case range overlaps with any
909 // singleton cases.
910 CaseStmt *OverlapStmt = 0;
911 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Douglas Gregordbb26db2009-05-15 23:57:33 +0000913 // Find the smallest value >= the lower bound. If I is in the
914 // case range, then we have overlap.
915 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
916 CaseVals.end(), CRLo,
917 CaseCompareFunctor());
918 if (I != CaseVals.end() && I->first < CRHi) {
919 OverlapVal = I->first; // Found overlap with scalar.
920 OverlapStmt = I->second;
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregordbb26db2009-05-15 23:57:33 +0000923 // Find the smallest value bigger than the upper bound.
924 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
925 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
926 OverlapVal = (I-1)->first; // Found overlap with scalar.
927 OverlapStmt = (I-1)->second;
928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Douglas Gregordbb26db2009-05-15 23:57:33 +0000930 // Check to see if this case stmt overlaps with the subsequent
931 // case range.
932 if (i && CRLo <= HiVals[i-1]) {
933 OverlapVal = HiVals[i-1]; // Found overlap with range.
934 OverlapStmt = CaseRanges[i-1].second;
935 }
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregordbb26db2009-05-15 23:57:33 +0000937 if (OverlapStmt) {
938 // If we have a duplicate, report it.
939 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
940 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000941 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000942 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000943 // FIXME: We really want to remove the bogus case stmt from the
944 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000945 CaseListIsErroneous = true;
946 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000947 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000948 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000949
John McCall0fb97082010-05-18 03:19:21 +0000950 // Complain if we have a constant condition and we didn't find a match.
951 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
952 // TODO: it would be nice if we printed enums as enums, chars as
953 // chars, etc.
954 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
955 << ConstantCondValue.toString(10)
956 << CondExpr->getSourceRange();
957 }
958
959 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000960 // values. We only issue a warning if there is not 'default:', but
961 // we still do the analysis to preserve this information in the AST
962 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000963 //
Chris Lattnerce784612010-09-16 17:09:42 +0000964 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000965
Douglas Gregorba915af2010-02-08 22:24:16 +0000966 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000967 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000968 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000969 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000970 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000971 EnumValsTy EnumVals;
972
John McCall0fb97082010-05-18 03:19:21 +0000973 // Gather all enum values, set their type and sort them,
974 // allowing easier comparison with CaseVals.
975 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000976 EDI != ED->enumerator_end(); ++EDI) {
977 llvm::APSInt Val = EDI->getInitVal();
978 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000979 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000980 }
981 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000982 EnumValsTy::iterator EIend =
983 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000984
985 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000986 EnumValsTy::const_iterator EI = EnumVals.begin();
987 for (CaseValsTy::const_iterator CI = CaseVals.begin();
988 CI != CaseVals.end(); CI++) {
989 while (EI != EIend && EI->first < CI->first)
990 EI++;
991 if (EI == EIend || EI->first > CI->first)
992 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000993 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000994 }
995 // See which of case ranges aren't in enum
996 EI = EnumVals.begin();
997 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
998 RI != CaseRanges.end() && EI != EIend; RI++) {
999 while (EI != EIend && EI->first < RI->first)
1000 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001001
David Blaikie93667502012-01-22 02:31:55 +00001002 if (EI == EIend || EI->first != RI->first) {
1003 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001004 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001005 }
David Blaikie93667502012-01-22 02:31:55 +00001006
Chad Rosier1093f492012-08-10 17:56:09 +00001007 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001008 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1009 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1010 while (EI != EIend && EI->first < Hi)
1011 EI++;
1012 if (EI == EIend || EI->first != Hi)
1013 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001014 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001015 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001016
Ted Kremenek559fb552010-09-09 00:05:53 +00001017 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001018 CaseValsTy::const_iterator CI = CaseVals.begin();
1019 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001020 bool hasCasesNotInSwitch = false;
1021
Chris Lattner5f9e2722011-07-23 10:55:15 +00001022 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001023
David Blaikie93667502012-01-22 02:31:55 +00001024 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001025 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001026 llvm::APSInt CIVal;
1027 while (CI != CaseVals.end() && CI->first < EI->first)
1028 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001029
Douglas Gregorba915af2010-02-08 22:24:16 +00001030 if (CI != CaseVals.end() && CI->first == EI->first)
1031 continue;
1032
Ted Kremenek559fb552010-09-09 00:05:53 +00001033 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001034 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001035 llvm::APSInt Hi =
1036 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001037 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001038 if (EI->first <= Hi)
1039 break;
1040 }
1041
Ted Kremenek559fb552010-09-09 00:05:53 +00001042 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001043 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001044 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001045 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001046 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001047
David Blaikie585d7792012-01-23 04:46:12 +00001048 if (TheDefaultStmt && UnhandledNames.empty())
1049 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001050
Chris Lattnerce784612010-09-16 17:09:42 +00001051 // Produce a nice diagnostic if multiple values aren't handled.
1052 switch (UnhandledNames.size()) {
1053 case 0: break;
1054 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001055 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001056 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001057 << UnhandledNames[0];
1058 break;
1059 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001060 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001061 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001062 << UnhandledNames[0] << UnhandledNames[1];
1063 break;
1064 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001065 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1066 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001067 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1068 break;
1069 default:
David Blaikie585d7792012-01-23 04:46:12 +00001070 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1071 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001072 << (unsigned)UnhandledNames.size()
1073 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1074 break;
1075 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001076
1077 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001078 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001079 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001080 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001081
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001082 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1083 diag::warn_empty_switch_body);
1084
Mike Stump390b4cc2009-05-16 07:39:55 +00001085 // FIXME: If the case list was broken is some way, we don't have a good system
1086 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001087 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001088 return StmtError();
1089
Sebastian Redlde307472009-01-11 00:38:46 +00001090 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001091}
1092
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001093void
1094Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1095 Expr *SrcExpr) {
1096 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001097 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001098 == DiagnosticsEngine::Ignored)
1099 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001100
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001101 if (const EnumType *ET = DstType->getAs<EnumType>())
1102 if (!Context.hasSameType(SrcType, DstType) &&
1103 SrcType->isIntegerType()) {
1104 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1105 SrcExpr->isIntegerConstantExpr(Context)) {
1106 // Get the bitwidth of the enum value before promotions.
1107 unsigned DstWith = Context.getIntWidth(DstType);
1108 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1109
1110 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1111 const EnumDecl *ED = ET->getDecl();
1112 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1113 EnumValsTy;
1114 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001115
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001116 // Gather all enum values, set their type and sort them,
1117 // allowing easier comparison with rhs constant.
1118 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1119 EDI != ED->enumerator_end(); ++EDI) {
1120 llvm::APSInt Val = EDI->getInitVal();
1121 AdjustAPSInt(Val, DstWith, DstIsSigned);
1122 EnumVals.push_back(std::make_pair(Val, *EDI));
1123 }
1124 if (EnumVals.empty())
1125 return;
1126 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1127 EnumValsTy::iterator EIend =
1128 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001129
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001130 // See which case values aren't in enum.
1131 EnumValsTy::const_iterator EI = EnumVals.begin();
1132 while (EI != EIend && EI->first < RhsVal)
1133 EI++;
1134 if (EI == EIend || EI->first != RhsVal) {
1135 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1136 << DstType;
1137 }
1138 }
1139 }
1140}
1141
John McCall60d7b3a2010-08-24 06:29:42 +00001142StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001143Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001144 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001145 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001146
Douglas Gregor5656e142009-11-24 21:15:44 +00001147 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001148 if (CondVar) {
1149 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001150 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001151 if (CondResult.isInvalid())
1152 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001153 }
John McCall9ae2f072010-08-23 23:25:46 +00001154 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001155 if (!ConditionExpr)
1156 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001157
John McCall9ae2f072010-08-23 23:25:46 +00001158 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001160 if (isa<NullStmt>(Body))
1161 getCurCompoundScope().setHasEmptyLoopBodies();
1162
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001163 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001164 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001165}
1166
John McCall60d7b3a2010-08-24 06:29:42 +00001167StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001168Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001169 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001170 Expr *Cond, SourceLocation CondRParen) {
1171 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001172
John Wiegley429bb272011-04-08 18:41:53 +00001173 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001174 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001175 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001176 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001177
Richard Smith41956372013-01-14 22:39:08 +00001178 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001179 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001180 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001181 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001182
John McCall9ae2f072010-08-23 23:25:46 +00001183 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001184
John McCall9ae2f072010-08-23 23:25:46 +00001185 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001186}
1187
Richard Trieu694e7962012-04-30 18:01:30 +00001188namespace {
1189 // This visitor will traverse a conditional statement and store all
1190 // the evaluated decls into a vector. Simple is set to true if none
1191 // of the excluded constructs are used.
1192 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1193 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001194 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001195 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001196public:
1197 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1198
1199 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001200 SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001201 Inherited(S.Context),
1202 Decls(Decls),
1203 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001204 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001205
1206 bool isSimple() { return Simple; }
1207
1208 // Replaces the method in EvaluatedExprVisitor.
1209 void VisitMemberExpr(MemberExpr* E) {
1210 Simple = false;
1211 }
1212
1213 // Any Stmt not whitelisted will cause the condition to be marked complex.
1214 void VisitStmt(Stmt *S) {
1215 Simple = false;
1216 }
1217
1218 void VisitBinaryOperator(BinaryOperator *E) {
1219 Visit(E->getLHS());
1220 Visit(E->getRHS());
1221 }
1222
1223 void VisitCastExpr(CastExpr *E) {
1224 Visit(E->getSubExpr());
1225 }
1226
1227 void VisitUnaryOperator(UnaryOperator *E) {
1228 // Skip checking conditionals with derefernces.
1229 if (E->getOpcode() == UO_Deref)
1230 Simple = false;
1231 else
1232 Visit(E->getSubExpr());
1233 }
1234
1235 void VisitConditionalOperator(ConditionalOperator *E) {
1236 Visit(E->getCond());
1237 Visit(E->getTrueExpr());
1238 Visit(E->getFalseExpr());
1239 }
1240
1241 void VisitParenExpr(ParenExpr *E) {
1242 Visit(E->getSubExpr());
1243 }
1244
1245 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1246 Visit(E->getOpaqueValue()->getSourceExpr());
1247 Visit(E->getFalseExpr());
1248 }
1249
1250 void VisitIntegerLiteral(IntegerLiteral *E) { }
1251 void VisitFloatingLiteral(FloatingLiteral *E) { }
1252 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1253 void VisitCharacterLiteral(CharacterLiteral *E) { }
1254 void VisitGNUNullExpr(GNUNullExpr *E) { }
1255 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1256
1257 void VisitDeclRefExpr(DeclRefExpr *E) {
1258 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1259 if (!VD) return;
1260
1261 Ranges.push_back(E->getSourceRange());
1262
1263 Decls.insert(VD);
1264 }
1265
1266 }; // end class DeclExtractor
1267
1268 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001269 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001270 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1271 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1272 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001273
1274public:
1275 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1276
1277 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1278 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1279 if (!Statement) return;
1280
1281 Visit(Statement);
1282 }
1283
1284 void VisitReturnStmt(ReturnStmt *S) {
1285 FoundDecl = true;
1286 }
1287
1288 void VisitBreakStmt(BreakStmt *S) {
1289 FoundDecl = true;
1290 }
1291
1292 void VisitGotoStmt(GotoStmt *S) {
1293 FoundDecl = true;
1294 }
1295
1296 void VisitCastExpr(CastExpr *E) {
1297 if (E->getCastKind() == CK_LValueToRValue)
1298 CheckLValueToRValueCast(E->getSubExpr());
1299 else
1300 Visit(E->getSubExpr());
1301 }
1302
1303 void CheckLValueToRValueCast(Expr *E) {
1304 E = E->IgnoreParenImpCasts();
1305
1306 if (isa<DeclRefExpr>(E)) {
1307 return;
1308 }
1309
1310 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1311 Visit(CO->getCond());
1312 CheckLValueToRValueCast(CO->getTrueExpr());
1313 CheckLValueToRValueCast(CO->getFalseExpr());
1314 return;
1315 }
1316
1317 if (BinaryConditionalOperator *BCO =
1318 dyn_cast<BinaryConditionalOperator>(E)) {
1319 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1320 CheckLValueToRValueCast(BCO->getFalseExpr());
1321 return;
1322 }
1323
1324 Visit(E);
1325 }
1326
1327 void VisitDeclRefExpr(DeclRefExpr *E) {
1328 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1329 if (Decls.count(VD))
1330 FoundDecl = true;
1331 }
1332
1333 bool FoundDeclInUse() { return FoundDecl; }
1334
1335 }; // end class DeclMatcher
1336
1337 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1338 Expr *Third, Stmt *Body) {
1339 // Condition is empty
1340 if (!Second) return;
1341
1342 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1343 Second->getLocStart())
1344 == DiagnosticsEngine::Ignored)
1345 return;
1346
1347 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1348 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001349 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001350 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001351 DE.Visit(Second);
1352
1353 // Don't analyze complex conditionals.
1354 if (!DE.isSimple()) return;
1355
1356 // No decls found.
1357 if (Decls.size() == 0) return;
1358
Richard Trieu90875992012-05-04 03:01:54 +00001359 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001360 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1361 E = Decls.end();
1362 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001363 if ((*I)->getType().isVolatileQualified() ||
1364 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001365
1366 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1367 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1368 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1369 return;
1370
1371 // Load decl names into diagnostic.
1372 if (Decls.size() > 4)
1373 PDiag << 0;
1374 else {
1375 PDiag << Decls.size();
1376 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1377 E = Decls.end();
1378 I != E; ++I)
1379 PDiag << (*I)->getDeclName();
1380 }
1381
1382 // Load SourceRanges into diagnostic if there is room.
1383 // Otherwise, load the SourceRange of the conditional expression.
1384 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001385 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1386 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001387 I != E; ++I)
1388 PDiag << *I;
1389 else
1390 PDiag << Second->getSourceRange();
1391
1392 S.Diag(Ranges.begin()->getBegin(), PDiag);
1393 }
1394
1395} // end namespace
1396
John McCall60d7b3a2010-08-24 06:29:42 +00001397StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001398Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001399 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001400 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001401 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001402 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001403 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001404 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1405 // declare identifiers for objects having storage class 'auto' or
1406 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001407 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1408 DI!=DE; ++DI) {
1409 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001410 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001411 VD = 0;
1412 if (VD == 0)
1413 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1414 // FIXME: mark decl erroneous!
1415 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001416 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001418
Richard Trieu694e7962012-04-30 18:01:30 +00001419 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1420
John McCall60d7b3a2010-08-24 06:29:42 +00001421 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001422 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001423 if (secondVar) {
1424 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001425 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001426 if (SecondResult.isInvalid())
1427 return StmtError();
1428 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001429
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001430 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001431
Anders Carlsson3af708f2009-08-01 01:39:59 +00001432 DiagnoseUnusedExprResult(First);
1433 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001434 DiagnoseUnusedExprResult(Body);
1435
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001436 if (isa<NullStmt>(Body))
1437 getCurCompoundScope().setHasEmptyLoopBodies();
1438
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001439 return Owned(new (Context) ForStmt(Context, First,
1440 SecondResult.take(), ConditionVar,
1441 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001442 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001443}
1444
John McCallf6a16482010-12-04 03:47:34 +00001445/// In an Objective C collection iteration statement:
1446/// for (x in y)
1447/// x can be an arbitrary l-value expression. Bind it up as a
1448/// full-expression.
1449StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001450 // Reduce placeholder expressions here. Note that this rejects the
1451 // use of pseudo-object l-values in this position.
1452 ExprResult result = CheckPlaceholderExpr(E);
1453 if (result.isInvalid()) return StmtError();
1454 E = result.take();
1455
Richard Smith41956372013-01-14 22:39:08 +00001456 ExprResult FullExpr = ActOnFinishFullExpr(E);
1457 if (FullExpr.isInvalid())
1458 return StmtError();
1459 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001460}
1461
John McCall990567c2011-07-27 01:07:15 +00001462ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001463Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1464 if (!collection)
1465 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001466
John McCall990567c2011-07-27 01:07:15 +00001467 // Bail out early if we've got a type-dependent expression.
1468 if (collection->isTypeDependent()) return Owned(collection);
1469
1470 // Perform normal l-value conversion.
1471 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1472 if (result.isInvalid())
1473 return ExprError();
1474 collection = result.take();
1475
1476 // The operand needs to have object-pointer type.
1477 // TODO: should we do a contextual conversion?
1478 const ObjCObjectPointerType *pointerType =
1479 collection->getType()->getAs<ObjCObjectPointerType>();
1480 if (!pointerType)
1481 return Diag(forLoc, diag::err_collection_expr_type)
1482 << collection->getType() << collection->getSourceRange();
1483
1484 // Check that the operand provides
1485 // - countByEnumeratingWithState:objects:count:
1486 const ObjCObjectType *objectType = pointerType->getObjectType();
1487 ObjCInterfaceDecl *iface = objectType->getInterface();
1488
1489 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001490 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001491 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001492 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001493 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001494 ? diag::err_arc_collection_forward
1495 : 0,
1496 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001497 // Otherwise, if we have any useful type information, check that
1498 // the type declares the appropriate method.
1499 } else if (iface || !objectType->qual_empty()) {
1500 IdentifierInfo *selectorIdents[] = {
1501 &Context.Idents.get("countByEnumeratingWithState"),
1502 &Context.Idents.get("objects"),
1503 &Context.Idents.get("count")
1504 };
1505 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1506
1507 ObjCMethodDecl *method = 0;
1508
1509 // If there's an interface, look in both the public and private APIs.
1510 if (iface) {
1511 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001512 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001513 }
1514
1515 // Also check protocol qualifiers.
1516 if (!method)
1517 method = LookupMethodInQualifiedType(selector, pointerType,
1518 /*instance*/ true);
1519
1520 // If we didn't find it anywhere, give up.
1521 if (!method) {
1522 Diag(forLoc, diag::warn_collection_expr_type)
1523 << collection->getType() << selector << collection->getSourceRange();
1524 }
1525
1526 // TODO: check for an incompatible signature?
1527 }
1528
1529 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001530 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001531}
1532
John McCall60d7b3a2010-08-24 06:29:42 +00001533StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001534Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001535 Stmt *First, Expr *collection,
1536 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001537
1538 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001539 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001540
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001541 if (First) {
1542 QualType FirstType;
1543 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001544 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001545 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1546 diag::err_toomany_element_decls));
1547
John McCallf85e1932011-06-15 23:02:42 +00001548 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1549 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001550 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1551 // declare identifiers for objects having storage class 'auto' or
1552 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001553 if (!D->hasLocalStorage())
1554 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001555 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001556 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001557 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001558 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001559 return StmtError(Diag(First->getLocStart(),
1560 diag::err_selector_element_not_lvalue)
1561 << First->getSourceRange());
1562
Mike Stump1eb44332009-09-09 15:08:12 +00001563 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001564 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001565 if (!FirstType->isDependentType() &&
1566 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001567 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001568 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1569 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001570 }
Chad Rosier1093f492012-08-10 17:56:09 +00001571
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001572 if (CollectionExprResult.isInvalid())
1573 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001574
Richard Smith41956372013-01-14 22:39:08 +00001575 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1576 if (CollectionExprResult.isInvalid())
1577 return StmtError();
1578
Chad Rosier1093f492012-08-10 17:56:09 +00001579 return Owned(new (Context) ObjCForCollectionStmt(First,
1580 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001581 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001582}
Reid Spencer5f016e22007-07-11 17:01:13 +00001583
Richard Smithad762fc2011-04-14 22:09:26 +00001584/// Finish building a variable declaration for a for-range statement.
1585/// \return true if an error occurs.
1586static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1587 SourceLocation Loc, int diag) {
1588 // Deduce the type for the iterator variable now rather than leaving it to
1589 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1590 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001591 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001592 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1593 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001594 SemaRef.Diag(Loc, diag) << Init->getType();
1595 if (!InitTSI) {
1596 Decl->setInvalidDecl();
1597 return true;
1598 }
1599 Decl->setTypeSourceInfo(InitTSI);
1600 Decl->setType(InitTSI->getType());
1601
John McCallf85e1932011-06-15 23:02:42 +00001602 // In ARC, infer lifetime.
1603 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1604 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001605 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001606 SemaRef.inferObjCARCLifetime(Decl))
1607 Decl->setInvalidDecl();
1608
Richard Smithad762fc2011-04-14 22:09:26 +00001609 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1610 /*TypeMayContainAuto=*/false);
1611 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001612 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001613 return false;
1614}
1615
Sam Panzere1715b62012-08-21 00:52:01 +00001616namespace {
1617
Richard Smithad762fc2011-04-14 22:09:26 +00001618/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001619/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001620/// nor from the diagnostics produced when analysing the implicit expressions
1621/// required in a for-range statement.
1622void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001623 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001624 CallExpr *CE = dyn_cast<CallExpr>(E);
1625 if (!CE)
1626 return;
1627 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1628 if (!D)
1629 return;
1630 SourceLocation Loc = D->getLocation();
1631
1632 std::string Description;
1633 bool IsTemplate = false;
1634 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1635 Description = SemaRef.getTemplateArgumentBindingsText(
1636 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1637 IsTemplate = true;
1638 }
1639
1640 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1641 << BEF << IsTemplate << Description << E->getType();
1642}
1643
Sam Panzere1715b62012-08-21 00:52:01 +00001644/// Build a variable declaration for a for-range statement.
1645VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1646 QualType Type, const char *Name) {
1647 DeclContext *DC = SemaRef.CurContext;
1648 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1649 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1650 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1651 TInfo, SC_Auto, SC_None);
1652 Decl->setImplicit();
1653 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001654}
1655
1656}
1657
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001658static bool ObjCEnumerationCollection(Expr *Collection) {
1659 return !Collection->isTypeDependent()
1660 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1661}
1662
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001663/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001664///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001665/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001666/// A range-based for statement is equivalent to
1667///
1668/// {
1669/// auto && __range = range-init;
1670/// for ( auto __begin = begin-expr,
1671/// __end = end-expr;
1672/// __begin != __end;
1673/// ++__begin ) {
1674/// for-range-declaration = *__begin;
1675/// statement
1676/// }
1677/// }
1678///
1679/// The body of the loop is not available yet, since it cannot be analysed until
1680/// we have determined the type of the for-range-declaration.
1681StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001682Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001683 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001684 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001685 if (!First || !Range)
1686 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001687
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001688 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001689 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001690
1691 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1692 assert(DS && "first part of for range not a decl stmt");
1693
1694 if (!DS->isSingleDecl()) {
1695 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1696 return StmtError();
1697 }
1698 if (DS->getSingleDecl()->isInvalidDecl())
1699 return StmtError();
1700
1701 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1702 return StmtError();
1703
1704 // Build auto && __range = range-init
1705 SourceLocation RangeLoc = Range->getLocStart();
1706 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1707 Context.getAutoRRefDeductType(),
1708 "__range");
1709 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1710 diag::err_for_range_deduction_failure))
1711 return StmtError();
1712
1713 // Claim the type doesn't contain auto: we've already done the checking.
1714 DeclGroupPtrTy RangeGroup =
1715 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1716 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1717 if (RangeDecl.isInvalid())
1718 return StmtError();
1719
1720 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1721 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001722 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001723}
1724
1725/// \brief Create the initialization, compare, and increment steps for
1726/// the range-based for loop expression.
1727/// This function does not handle array-based for loops,
1728/// which are created in Sema::BuildCXXForRangeStmt.
1729///
1730/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1731/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1732/// CandidateSet and BEF are set and some non-success value is returned on
1733/// failure.
1734static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1735 Expr *BeginRange, Expr *EndRange,
1736 QualType RangeType,
1737 VarDecl *BeginVar,
1738 VarDecl *EndVar,
1739 SourceLocation ColonLoc,
1740 OverloadCandidateSet *CandidateSet,
1741 ExprResult *BeginExpr,
1742 ExprResult *EndExpr,
1743 Sema::BeginEndFunction *BEF) {
1744 DeclarationNameInfo BeginNameInfo(
1745 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1746 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1747 ColonLoc);
1748
1749 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1750 Sema::LookupMemberName);
1751 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1752
1753 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1754 // - if _RangeT is a class type, the unqualified-ids begin and end are
1755 // looked up in the scope of class _RangeT as if by class member access
1756 // lookup (3.4.5), and if either (or both) finds at least one
1757 // declaration, begin-expr and end-expr are __range.begin() and
1758 // __range.end(), respectively;
1759 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1760 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1761
1762 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1763 SourceLocation RangeLoc = BeginVar->getLocation();
1764 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1765
1766 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1767 << RangeLoc << BeginRange->getType() << *BEF;
1768 return Sema::FRS_DiagnosticIssued;
1769 }
1770 } else {
1771 // - otherwise, begin-expr and end-expr are begin(__range) and
1772 // end(__range), respectively, where begin and end are looked up with
1773 // argument-dependent lookup (3.4.2). For the purposes of this name
1774 // lookup, namespace std is an associated namespace.
1775
1776 }
1777
1778 *BEF = Sema::BEF_begin;
1779 Sema::ForRangeStatus RangeStatus =
1780 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1781 Sema::BEF_begin, BeginNameInfo,
1782 BeginMemberLookup, CandidateSet,
1783 BeginRange, BeginExpr);
1784
1785 if (RangeStatus != Sema::FRS_Success)
1786 return RangeStatus;
1787 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1788 diag::err_for_range_iter_deduction_failure)) {
1789 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1790 return Sema::FRS_DiagnosticIssued;
1791 }
1792
1793 *BEF = Sema::BEF_end;
1794 RangeStatus =
1795 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1796 Sema::BEF_end, EndNameInfo,
1797 EndMemberLookup, CandidateSet,
1798 EndRange, EndExpr);
1799 if (RangeStatus != Sema::FRS_Success)
1800 return RangeStatus;
1801 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1802 diag::err_for_range_iter_deduction_failure)) {
1803 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1804 return Sema::FRS_DiagnosticIssued;
1805 }
1806 return Sema::FRS_Success;
1807}
1808
1809/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001810/// If the attempt fails, this function will return a valid, null StmtResult
1811/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001812static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1813 SourceLocation ForLoc,
1814 Stmt *LoopVarDecl,
1815 SourceLocation ColonLoc,
1816 Expr *Range,
1817 SourceLocation RangeLoc,
1818 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001819 // Determine whether we can rebuild the for-range statement with a
1820 // dereferenced range expression.
1821 ExprResult AdjustedRange;
1822 {
1823 Sema::SFINAETrap Trap(SemaRef);
1824
1825 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1826 if (AdjustedRange.isInvalid())
1827 return StmtResult();
1828
1829 StmtResult SR =
1830 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1831 AdjustedRange.get(), RParenLoc,
1832 Sema::BFRK_Check);
1833 if (SR.isInvalid())
1834 return StmtResult();
1835 }
1836
1837 // The attempt to dereference worked well enough that it could produce a valid
1838 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1839 // case there are any other (non-fatal) problems with it.
1840 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1841 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1842 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1843 AdjustedRange.get(), RParenLoc,
1844 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001845}
1846
Richard Smith8b533d92012-09-20 21:52:32 +00001847/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001848StmtResult
1849Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1850 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1851 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001852 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001853 Scope *S = getCurScope();
1854
1855 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1856 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1857 QualType RangeVarType = RangeVar->getType();
1858
1859 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1860 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1861
1862 StmtResult BeginEndDecl = BeginEnd;
1863 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1864
1865 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1866 SourceLocation RangeLoc = RangeVar->getLocation();
1867
Ted Kremeneke50b0152011-10-10 22:36:28 +00001868 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1869
1870 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1871 VK_LValue, ColonLoc);
1872 if (BeginRangeRef.isInvalid())
1873 return StmtError();
1874
1875 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1876 VK_LValue, ColonLoc);
1877 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001878 return StmtError();
1879
1880 QualType AutoType = Context.getAutoDeductType();
1881 Expr *Range = RangeVar->getInit();
1882 if (!Range)
1883 return StmtError();
1884 QualType RangeType = Range->getType();
1885
1886 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001887 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001888 return StmtError();
1889
1890 // Build auto __begin = begin-expr, __end = end-expr.
1891 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1892 "__begin");
1893 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1894 "__end");
1895
1896 // Build begin-expr and end-expr and attach to __begin and __end variables.
1897 ExprResult BeginExpr, EndExpr;
1898 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1899 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1900 // __range + __bound, respectively, where __bound is the array bound. If
1901 // _RangeT is an array of unknown size or an array of incomplete type,
1902 // the program is ill-formed;
1903
1904 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001905 BeginExpr = BeginRangeRef;
1906 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001907 diag::err_for_range_iter_deduction_failure)) {
1908 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1909 return StmtError();
1910 }
1911
1912 // Find the array bound.
1913 ExprResult BoundExpr;
1914 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1915 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001916 Context.getPointerDiffType(),
1917 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001918 else if (const VariableArrayType *VAT =
1919 dyn_cast<VariableArrayType>(UnqAT))
1920 BoundExpr = VAT->getSizeExpr();
1921 else {
1922 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1923 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001924 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001925 }
1926
1927 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001928 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001929 BoundExpr.get());
1930 if (EndExpr.isInvalid())
1931 return StmtError();
1932 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1933 diag::err_for_range_iter_deduction_failure)) {
1934 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1935 return StmtError();
1936 }
1937 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001938 OverloadCandidateSet CandidateSet(RangeLoc);
1939 Sema::BeginEndFunction BEFFailure;
1940 ForRangeStatus RangeStatus =
1941 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1942 EndRangeRef.get(), RangeType,
1943 BeginVar, EndVar, ColonLoc, &CandidateSet,
1944 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00001945
Sam Panzere1715b62012-08-21 00:52:01 +00001946 // If building the range failed, try dereferencing the range expression
1947 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00001948 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00001949 BEFFailure == BEF_begin) {
1950 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1951 LoopVarDecl, ColonLoc,
1952 Range, RangeLoc,
1953 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00001954 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00001955 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00001956 }
1957
Sam Panzere1715b62012-08-21 00:52:01 +00001958 // Otherwise, emit diagnostics if we haven't already.
1959 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00001960 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00001961 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1962 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00001963 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00001964 }
1965 // Return an error if no fix was discovered.
1966 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00001967 return StmtError();
1968 }
1969
Sam Panzere1715b62012-08-21 00:52:01 +00001970 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1971 "invalid range expression in for loop");
1972
1973 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00001974 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1975 if (!Context.hasSameType(BeginType, EndType)) {
1976 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1977 << BeginType << EndType;
1978 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1979 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1980 }
1981
1982 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1983 // Claim the type doesn't contain auto: we've already done the checking.
1984 DeclGroupPtrTy BeginEndGroup =
1985 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1986 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1987
Ted Kremeneke50b0152011-10-10 22:36:28 +00001988 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1989 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001990 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001991 if (BeginRef.isInvalid())
1992 return StmtError();
1993
Richard Smithad762fc2011-04-14 22:09:26 +00001994 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1995 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001996 if (EndRef.isInvalid())
1997 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001998
1999 // Build and check __begin != __end expression.
2000 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2001 BeginRef.get(), EndRef.get());
2002 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2003 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2004 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002005 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2006 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002007 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2008 if (!Context.hasSameType(BeginType, EndType))
2009 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2010 return StmtError();
2011 }
2012
2013 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002014 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2015 VK_LValue, ColonLoc);
2016 if (BeginRef.isInvalid())
2017 return StmtError();
2018
Richard Smithad762fc2011-04-14 22:09:26 +00002019 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2020 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2021 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002022 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2023 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002024 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2025 return StmtError();
2026 }
2027
2028 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002029 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2030 VK_LValue, ColonLoc);
2031 if (BeginRef.isInvalid())
2032 return StmtError();
2033
Richard Smithad762fc2011-04-14 22:09:26 +00002034 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2035 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002036 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2037 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002038 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2039 return StmtError();
2040 }
2041
Richard Smith8b533d92012-09-20 21:52:32 +00002042 // Attach *__begin as initializer for VD. Don't touch it if we're just
2043 // trying to determine whether this would be a valid range.
2044 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002045 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2046 /*TypeMayContainAuto=*/true);
2047 if (LoopVar->isInvalidDecl())
2048 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2049 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002050 } else {
2051 // The range is implicitly used as a placeholder when it is dependent.
2052 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002053 }
2054
Richard Smith8b533d92012-09-20 21:52:32 +00002055 // Don't bother to actually allocate the result if we're just trying to
2056 // determine whether it would be valid.
2057 if (Kind == BFRK_Check)
2058 return StmtResult();
2059
Richard Smithad762fc2011-04-14 22:09:26 +00002060 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2061 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2062 NotEqExpr.take(), IncrExpr.take(),
2063 LoopVarDS, /*Body=*/0, ForLoc,
2064 ColonLoc, RParenLoc));
2065}
2066
Chad Rosier1093f492012-08-10 17:56:09 +00002067/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002068/// statement.
2069StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2070 if (!S || !B)
2071 return StmtError();
2072 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002073
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002074 ForStmt->setBody(B);
2075 return S;
2076}
2077
Richard Smithad762fc2011-04-14 22:09:26 +00002078/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2079/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2080/// body cannot be performed until after the type of the range variable is
2081/// determined.
2082StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2083 if (!S || !B)
2084 return StmtError();
2085
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002086 if (isa<ObjCForCollectionStmt>(S))
2087 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002088
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002089 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2090 ForStmt->setBody(B);
2091
2092 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2093 diag::warn_empty_range_based_for_body);
2094
Richard Smithad762fc2011-04-14 22:09:26 +00002095 return S;
2096}
2097
Chris Lattner57ad3782011-02-17 20:34:02 +00002098StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2099 SourceLocation LabelLoc,
2100 LabelDecl *TheDecl) {
2101 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002102 TheDecl->setUsed();
2103 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002104}
2105
John McCall60d7b3a2010-08-24 06:29:42 +00002106StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002107Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002108 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002109 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002110 if (!E->isTypeDependent()) {
2111 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002112 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002113 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002114 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002115 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2116 if (ExprRes.isInvalid())
2117 return StmtError();
2118 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002119 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002120 return StmtError();
2121 }
John McCallb60a77e2010-08-01 00:26:45 +00002122
Richard Smith41956372013-01-14 22:39:08 +00002123 ExprResult ExprRes = ActOnFinishFullExpr(E);
2124 if (ExprRes.isInvalid())
2125 return StmtError();
2126 E = ExprRes.take();
2127
John McCall781472f2010-08-25 08:40:02 +00002128 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002129
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002130 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002131}
2132
John McCall60d7b3a2010-08-24 06:29:42 +00002133StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002134Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 Scope *S = CurScope->getContinueParent();
2136 if (!S) {
2137 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002138 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002140
Ted Kremenek8189cde2009-02-07 01:47:29 +00002141 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002142}
2143
John McCall60d7b3a2010-08-24 06:29:42 +00002144StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002145Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 Scope *S = CurScope->getBreakParent();
2147 if (!S) {
2148 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002149 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002151
Ted Kremenek8189cde2009-02-07 01:47:29 +00002152 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002153}
2154
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002155/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002156/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002157///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002158/// \param ReturnType If we're determining the copy elision candidate for
2159/// a return statement, this is the return type of the function. If we're
2160/// determining the copy elision candidate for a throw expression, this will
2161/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002162///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002163/// \param E The expression being returned from the function or block, or
2164/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002165///
Douglas Gregor4926d832011-05-20 15:00:53 +00002166/// \param AllowFunctionParameter Whether we allow function parameters to
2167/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2168/// we re-use this logic to determine whether we should try to move as part of
2169/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002170///
2171/// \returns The NRVO candidate variable, if the return statement may use the
2172/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002173const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2174 Expr *E,
2175 bool AllowFunctionParameter) {
2176 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002177 // - in a return statement in a function with ...
2178 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002179 if (!ReturnType.isNull()) {
2180 if (!ReturnType->isRecordType())
2181 return 0;
2182 // ... the same cv-unqualified type as the function return type ...
2183 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2184 return 0;
2185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002186
2187 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002188 // (other than a function or catch-clause parameter)) ...
2189 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002190 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002191 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002192 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2193 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002194 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002195
John McCall1cd76e82011-11-11 03:57:31 +00002196 // ...object (other than a function or catch-clause parameter)...
2197 if (VD->getKind() != Decl::Var &&
2198 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2199 return 0;
2200 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201
John McCall1cd76e82011-11-11 03:57:31 +00002202 // ...automatic...
2203 if (!VD->hasLocalStorage()) return 0;
2204
2205 // ...non-volatile...
2206 if (VD->getType().isVolatileQualified()) return 0;
2207 if (VD->getType()->isReferenceType()) return 0;
2208
2209 // __block variables can't be allocated in a way that permits NRVO.
2210 if (VD->hasAttr<BlocksAttr>()) return 0;
2211
2212 // Variables with higher required alignment than their type's ABI
2213 // alignment cannot use NRVO.
2214 if (VD->hasAttr<AlignedAttr>() &&
2215 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2216 return 0;
2217
2218 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002219}
2220
Douglas Gregor07f402c2011-01-21 21:08:57 +00002221/// \brief Perform the initialization of a potentially-movable value, which
2222/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002223///
2224/// This routine implements C++0x [class.copy]p33, which attempts to treat
2225/// returned lvalues as rvalues in certain cases (to prefer move construction),
2226/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002227ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002228Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2229 const VarDecl *NRVOCandidate,
2230 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002231 Expr *Value,
2232 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002233 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002234 // When the criteria for elision of a copy operation are met or would
2235 // be met save for the fact that the source object is a function
2236 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002237 // overload resolution to select the constructor for the copy is first
2238 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002239 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002240 if (AllowNRVO &&
2241 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002242 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002243 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
Douglas Gregorcc15f012011-01-21 19:38:21 +00002245 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002246 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002247 = InitializationKind::CreateCopy(Value->getLocStart(),
2248 Value->getLocStart());
2249 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002250
2251 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002252 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002253 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002254 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002255 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002256 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2257 StepEnd = Seq.step_end();
2258 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002259 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002260 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002261
2262 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002263 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002264
Douglas Gregorcc15f012011-01-21 19:38:21 +00002265 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002266 = Constructor->getParamDecl(0)->getType()
2267 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002268
Douglas Gregorcc15f012011-01-21 19:38:21 +00002269 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002270 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002271 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2272 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002273 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002274
Douglas Gregorcc15f012011-01-21 19:38:21 +00002275 // Promote "AsRvalue" to the heap, since we now need this
2276 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002277 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002278 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002279
Douglas Gregorcc15f012011-01-21 19:38:21 +00002280 // Complete type-checking the initialization of the return type
2281 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002282 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002283 }
2284 }
2285 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002286
Douglas Gregorcc15f012011-01-21 19:38:21 +00002287 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002288 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002289 // (again) now with the return value expression as written.
2290 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002291 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002292
Douglas Gregorcc15f012011-01-21 19:38:21 +00002293 return Res;
2294}
2295
Eli Friedman84b007f2012-01-26 03:00:14 +00002296/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2297/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002298///
John McCall60d7b3a2010-08-24 06:29:42 +00002299StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002300Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2301 // If this is the first return we've seen, infer the return type.
2302 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2303 // rules which allows multiple return statements.
2304 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002305 QualType FnRetType = CurCap->ReturnType;
2306
2307 // For blocks/lambdas with implicit return types, we check each return
2308 // statement individually, and deduce the common return type when the block
2309 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002310 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002311 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002312 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2313 if (Result.isInvalid())
2314 return StmtError();
2315 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002316
Jordan Rose7dd900e2012-07-02 21:19:23 +00002317 if (!RetValExp->isTypeDependent())
2318 FnRetType = RetValExp->getType();
2319 else
2320 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002321 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002322 if (RetValExp) {
2323 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2324 // initializer list, because it is not an expression (even
2325 // though we represent it as one). We still deduce 'void'.
2326 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2327 << RetValExp->getSourceRange();
2328 }
2329
Jordan Rose7dd900e2012-07-02 21:19:23 +00002330 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002331 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002332
2333 // Although we'll properly infer the type of the block once it's completed,
2334 // make sure we provide a return type now for better error recovery.
2335 if (CurCap->ReturnType.isNull())
2336 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002337 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002338 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002339
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002340 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002341 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2342 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2343 return StmtError();
2344 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002345 } else {
2346 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2347 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2348 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2349 return StmtError();
2350 }
2351 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002352
Steve Naroff4eb206b2008-09-03 18:15:37 +00002353 // Otherwise, verify that this result type matches the previous one. We are
2354 // pickier with blocks than for normal functions because we don't have GCC
2355 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002356 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002357 if (FnRetType->isDependentType()) {
2358 // Delay processing for now. TODO: there are lots of dependent
2359 // types we can conclusively prove aren't void.
2360 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002361 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002362 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002363 (RetValExp->isTypeDependent() ||
2364 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002365 if (!getLangOpts().CPlusPlus &&
2366 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002367 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002368 else {
2369 Diag(ReturnLoc, diag::err_return_block_has_expr);
2370 RetValExp = 0;
2371 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002372 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002373 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002374 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2375 } else if (!RetValExp->isTypeDependent()) {
2376 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002377
John McCall0a7efe12011-08-17 22:09:46 +00002378 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2379 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2380 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002381
John McCall0a7efe12011-08-17 22:09:46 +00002382 // In C++ the return statement is handled via a copy initialization.
2383 // the C version of which boils down to CheckSingleAssignmentConstraints.
2384 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2385 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2386 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002387 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002388 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2389 FnRetType, RetValExp);
2390 if (Res.isInvalid()) {
2391 // FIXME: Cleanup temporaries here, anyway?
2392 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002393 }
John McCall0a7efe12011-08-17 22:09:46 +00002394 RetValExp = Res.take();
2395 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002396 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002397
John McCalld963c372011-08-17 21:34:14 +00002398 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002399 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2400 if (ER.isInvalid())
2401 return StmtError();
2402 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002403 }
John McCall0a7efe12011-08-17 22:09:46 +00002404 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2405 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002406
Jordan Rose7dd900e2012-07-02 21:19:23 +00002407 // If we need to check for the named return value optimization,
2408 // or if we need to infer the return type,
2409 // save the return statement in our scope for later processing.
2410 if (CurCap->HasImplicitReturnType ||
2411 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2412 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002413 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002414
Douglas Gregor5077c382010-05-15 06:01:05 +00002415 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002416}
Reid Spencer5f016e22007-07-11 17:01:13 +00002417
John McCall60d7b3a2010-08-24 06:29:42 +00002418StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002419Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002420 // Check for unexpanded parameter packs.
2421 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2422 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002423
Eli Friedman84b007f2012-01-26 03:00:14 +00002424 if (isa<CapturingScopeInfo>(getCurFunction()))
2425 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002426
Chris Lattner371f2582008-12-04 23:50:19 +00002427 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002428 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002429 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002430 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002431 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002432 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002433 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002434 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002435 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002436 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2437 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002438 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002439 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002440 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2441 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002442 }
2443 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002444 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Douglas Gregor5077c382010-05-15 06:01:05 +00002446 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002447 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002448 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002449 if (isa<InitListExpr>(RetValExp)) {
2450 // We simply never allow init lists as the return value of void
2451 // functions. This is compatible because this was never allowed before,
2452 // so there's no legacy code to deal with.
2453 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2454 int FunctionKind = 0;
2455 if (isa<ObjCMethodDecl>(CurDecl))
2456 FunctionKind = 1;
2457 else if (isa<CXXConstructorDecl>(CurDecl))
2458 FunctionKind = 2;
2459 else if (isa<CXXDestructorDecl>(CurDecl))
2460 FunctionKind = 3;
2461
2462 Diag(ReturnLoc, diag::err_return_init_list)
2463 << CurDecl->getDeclName() << FunctionKind
2464 << RetValExp->getSourceRange();
2465
2466 // Drop the expression.
2467 RetValExp = 0;
2468 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002469 // C99 6.8.6.4p1 (ext_ since GCC warns)
2470 unsigned D = diag::ext_return_has_expr;
2471 if (RetValExp->getType()->isVoidType())
2472 D = diag::ext_return_has_void_expr;
2473 else {
2474 ExprResult Result = Owned(RetValExp);
2475 Result = IgnoredValueConversions(Result.take());
2476 if (Result.isInvalid())
2477 return StmtError();
2478 RetValExp = Result.take();
2479 RetValExp = ImpCastExprToType(RetValExp,
2480 Context.VoidTy, CK_ToVoid).take();
2481 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002482
Nick Lewycky8d794612011-06-01 07:44:31 +00002483 // return (some void expression); is legal in C++.
2484 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002485 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002486 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002487
2488 int FunctionKind = 0;
2489 if (isa<ObjCMethodDecl>(CurDecl))
2490 FunctionKind = 1;
2491 else if (isa<CXXConstructorDecl>(CurDecl))
2492 FunctionKind = 2;
2493 else if (isa<CXXDestructorDecl>(CurDecl))
2494 FunctionKind = 3;
2495
Nick Lewycky8d794612011-06-01 07:44:31 +00002496 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002497 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002498 << RetValExp->getSourceRange();
2499 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002500 }
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Sebastian Redl33deb352012-02-22 10:50:08 +00002502 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002503 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2504 if (ER.isInvalid())
2505 return StmtError();
2506 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002507 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002508 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002509
Douglas Gregor5077c382010-05-15 06:01:05 +00002510 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2511 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002512 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2513 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002514 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002515
2516 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002517 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002518 else
Chris Lattner08631c52008-11-23 21:45:46 +00002519 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002520 Result = new (Context) ReturnStmt(ReturnLoc);
2521 } else {
2522 const VarDecl *NRVOCandidate = 0;
2523 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2524 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002525
Eli Friedman38ac2432012-03-30 01:13:43 +00002526 if (!RelatedRetType.isNull()) {
2527 // If we have a related result type, perform an extra conversion here.
2528 // FIXME: The diagnostics here don't really describe what is happening.
2529 InitializedEntity Entity =
2530 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002531
Eli Friedman38ac2432012-03-30 01:13:43 +00002532 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2533 RetValExp);
2534 if (Res.isInvalid()) {
2535 // FIXME: Cleanup temporaries here, anyway?
2536 return StmtError();
2537 }
2538 RetValExp = Res.takeAs<Expr>();
2539 }
2540
Douglas Gregor5077c382010-05-15 06:01:05 +00002541 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2542 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2543 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002544
John McCall856d3792011-06-16 23:24:51 +00002545 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002546 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002547 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002548 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002549 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002550 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002552 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002553 if (Res.isInvalid()) {
2554 // FIXME: Cleanup temporaries here, anyway?
2555 return StmtError();
2556 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002557
Douglas Gregor5077c382010-05-15 06:01:05 +00002558 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002559 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002560 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002561 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002562
John McCallb4eb64d2010-10-08 02:01:28 +00002563 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002564 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2565 if (ER.isInvalid())
2566 return StmtError();
2567 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002568 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002569 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002570 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002571
2572 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002573 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002574 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002575 !CurContext->isDependentContext())
2576 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002577
Douglas Gregor5077c382010-05-15 06:01:05 +00002578 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002579}
2580
John McCall60d7b3a2010-08-24 06:29:42 +00002581StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002582Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002583 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002584 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002585 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002586 if (Var && Var->isInvalidDecl())
2587 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002588
John McCall9ae2f072010-08-23 23:25:46 +00002589 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002590}
2591
John McCall60d7b3a2010-08-24 06:29:42 +00002592StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002593Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2594 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002595}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002596
John McCall60d7b3a2010-08-24 06:29:42 +00002597StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002598Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002599 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002600 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002601 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2602
John McCall781472f2010-08-25 08:40:02 +00002603 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002604 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002605 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002606 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002607 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002608 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002609}
2610
John McCalld1376ee2012-05-08 21:41:25 +00002611StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002612 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002613 ExprResult Result = DefaultLvalueConversion(Throw);
2614 if (Result.isInvalid())
2615 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002616
Richard Smith41956372013-01-14 22:39:08 +00002617 Result = ActOnFinishFullExpr(Result.take());
2618 if (Result.isInvalid())
2619 return StmtError();
2620 Throw = Result.take();
2621
Douglas Gregord1377b22010-04-22 21:44:01 +00002622 QualType ThrowType = Throw->getType();
2623 // Make sure the expression type is an ObjC pointer or "void *".
2624 if (!ThrowType->isDependentType() &&
2625 !ThrowType->isObjCObjectPointerType()) {
2626 const PointerType *PT = ThrowType->getAs<PointerType>();
2627 if (!PT || !PT->getPointeeType()->isVoidType())
2628 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2629 << Throw->getType() << Throw->getSourceRange());
2630 }
2631 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002632
John McCall9ae2f072010-08-23 23:25:46 +00002633 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002634}
2635
John McCall60d7b3a2010-08-24 06:29:42 +00002636StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002637Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002638 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002639 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002640 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2641
John McCall9ae2f072010-08-23 23:25:46 +00002642 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002643 // @throw without an expression designates a rethrow (which much occur
2644 // in the context of an @catch clause).
2645 Scope *AtCatchParent = CurScope;
2646 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2647 AtCatchParent = AtCatchParent->getParent();
2648 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002649 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002650 }
John McCall9ae2f072010-08-23 23:25:46 +00002651 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002652}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002653
John McCall07524032011-07-27 21:50:02 +00002654ExprResult
2655Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2656 ExprResult result = DefaultLvalueConversion(operand);
2657 if (result.isInvalid())
2658 return ExprError();
2659 operand = result.take();
2660
2661 // Make sure the expression type is an ObjC pointer or "void *".
2662 QualType type = operand->getType();
2663 if (!type->isDependentType() &&
2664 !type->isObjCObjectPointerType()) {
2665 const PointerType *pointerType = type->getAs<PointerType>();
2666 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2667 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2668 << type << operand->getSourceRange();
2669 }
2670
2671 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002672 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002673}
2674
John McCall60d7b3a2010-08-24 06:29:42 +00002675StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002676Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2677 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002678 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002679 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002680 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002681}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002682
2683/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2684/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002685StmtResult
John McCalld226f652010-08-21 09:40:31 +00002686Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002687 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002688 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002689 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002690 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002691 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002692}
Sebastian Redl8351da02008-12-22 21:35:02 +00002693
John McCallf85e1932011-06-15 23:02:42 +00002694StmtResult
2695Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2696 getCurFunction()->setHasBranchProtectedScope();
2697 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2698}
2699
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002700namespace {
2701
Sebastian Redlc447aba2009-07-29 17:15:45 +00002702class TypeWithHandler {
2703 QualType t;
2704 CXXCatchStmt *stmt;
2705public:
2706 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2707 : t(type), stmt(statement) {}
2708
John McCall0953e762009-09-24 19:53:00 +00002709 // An arbitrary order is fine as long as it places identical
2710 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002711 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002712 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002713 return true;
John McCall0953e762009-09-24 19:53:00 +00002714 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002715 return false;
2716 else
2717 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2718 }
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Sebastian Redlc447aba2009-07-29 17:15:45 +00002720 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002721 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002722 }
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Sebastian Redlc447aba2009-07-29 17:15:45 +00002724 CXXCatchStmt *getCatchStmt() const { return stmt; }
2725 SourceLocation getTypeSpecStartLoc() const {
2726 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2727 }
2728};
2729
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002730}
2731
Sebastian Redl8351da02008-12-22 21:35:02 +00002732/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2733/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002734StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002735Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002736 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002737 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002738 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002739 !getSourceManager().isInSystemHeader(TryLoc))
2740 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002741
Sebastian Redl8351da02008-12-22 21:35:02 +00002742 unsigned NumHandlers = RawHandlers.size();
2743 assert(NumHandlers > 0 &&
2744 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002745 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002746
Chris Lattner5f9e2722011-07-23 10:55:15 +00002747 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002748
2749 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002750 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002751 if (!Handler->getExceptionDecl()) {
2752 if (i < NumHandlers - 1)
2753 return StmtError(Diag(Handler->getLocStart(),
2754 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Sebastian Redlc447aba2009-07-29 17:15:45 +00002756 continue;
2757 }
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Sebastian Redlc447aba2009-07-29 17:15:45 +00002759 const QualType CaughtType = Handler->getCaughtType();
2760 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2761 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002762 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002763
2764 // Detect handlers for the same type as an earlier one.
2765 if (NumHandlers > 1) {
2766 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Sebastian Redlc447aba2009-07-29 17:15:45 +00002768 TypeWithHandler prev = TypesWithHandlers[0];
2769 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2770 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Sebastian Redlc447aba2009-07-29 17:15:45 +00002772 if (curr == prev) {
2773 Diag(curr.getTypeSpecStartLoc(),
2774 diag::warn_exception_caught_by_earlier_handler)
2775 << curr.getCatchStmt()->getCaughtType().getAsString();
2776 Diag(prev.getTypeSpecStartLoc(),
2777 diag::note_previous_exception_handler)
2778 << prev.getCatchStmt()->getCaughtType().getAsString();
2779 }
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Sebastian Redlc447aba2009-07-29 17:15:45 +00002781 prev = curr;
2782 }
2783 }
Mike Stump1eb44332009-09-09 15:08:12 +00002784
John McCall781472f2010-08-25 08:40:02 +00002785 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002786
Sebastian Redl8351da02008-12-22 21:35:02 +00002787 // FIXME: We should detect handlers that cannot catch anything because an
2788 // earlier handler catches a superclass. Need to find a method that is not
2789 // quadratic for this.
2790 // Neither of these are explicitly forbidden, but every compiler detects them
2791 // and warns.
2792
John McCall9ae2f072010-08-23 23:25:46 +00002793 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002794 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002795}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002796
2797StmtResult
2798Sema::ActOnSEHTryBlock(bool IsCXXTry,
2799 SourceLocation TryLoc,
2800 Stmt *TryBlock,
2801 Stmt *Handler) {
2802 assert(TryBlock && Handler);
2803
2804 getCurFunction()->setHasBranchProtectedScope();
2805
2806 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2807}
2808
2809StmtResult
2810Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2811 Expr *FilterExpr,
2812 Stmt *Block) {
2813 assert(FilterExpr && Block);
2814
2815 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002816 return StmtError(Diag(FilterExpr->getExprLoc(),
2817 diag::err_filter_expression_integral)
2818 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002819 }
2820
2821 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2822}
2823
2824StmtResult
2825Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2826 Stmt *Block) {
2827 assert(Block);
2828 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2829}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002830
2831StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2832 bool IsIfExists,
2833 NestedNameSpecifierLoc QualifierLoc,
2834 DeclarationNameInfo NameInfo,
2835 Stmt *Nested)
2836{
2837 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002838 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002839 cast<CompoundStmt>(Nested));
2840}
2841
2842
Chad Rosier1093f492012-08-10 17:56:09 +00002843StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002844 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002845 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002846 UnqualifiedId &Name,
2847 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002848 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002849 SS.getWithLocInContext(Context),
2850 GetNameFromUnqualifiedId(Name),
2851 Nested);
2852}