blob: fd3ee0d9f56c65cda4f8e0d5da49efb75fdf0ceb [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) {
John McCall60d7b3a2010-08-24 06:29:42 +0000409 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000411 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000412 if (CondVar) {
413 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000414 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000415 if (CondResult.isInvalid())
416 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000417 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000418 Expr *ConditionExpr = CondResult.takeAs<Expr>();
419 if (!ConditionExpr)
420 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000421
Anders Carlsson75443112009-07-30 22:39:03 +0000422 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000423
John McCall9ae2f072010-08-23 23:25:46 +0000424 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000425 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
426 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000427 }
428
Anders Carlsson75443112009-07-30 22:39:03 +0000429 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000430
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000432 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000433}
434
Chris Lattnerf4021e72007-08-23 05:46:52 +0000435/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
436/// the specified width and sign. If an overflow occurs, detect it and emit
437/// the specified diagnostic.
438void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
439 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000440 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000441 unsigned DiagID) {
442 // Perform a conversion to the promoted condition type if needed.
443 if (NewWidth > Val.getBitWidth()) {
444 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000445 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000446 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000447
448 // If the input was signed and negative and the output is
449 // unsigned, don't bother to warn: this is implementation-defined
450 // behavior.
451 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000452 } else if (NewWidth < Val.getBitWidth()) {
453 // If this is a truncation, check for overflow.
454 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000455 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000456 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000457 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000458 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000459 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000460 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattnerf4021e72007-08-23 05:46:52 +0000462 // Regardless of whether a diagnostic was emitted, really do the
463 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000464 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000465 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000466 } else if (NewSign != Val.isSigned()) {
467 // Convert the sign to match the sign of the condition. This can cause
468 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000469 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000470 // behavior.
471 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000472 llvm::APSInt OldVal(Val);
473 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000474 }
475}
476
Chris Lattner0471f5b2007-08-23 18:29:20 +0000477namespace {
478 struct CaseCompareFunctor {
479 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
480 const llvm::APSInt &RHS) {
481 return LHS.first < RHS;
482 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000483 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
484 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
485 return LHS.first < RHS.first;
486 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000487 bool operator()(const llvm::APSInt &LHS,
488 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
489 return LHS < RHS.first;
490 }
491 };
492}
493
Chris Lattner764a7ce2007-09-21 18:15:22 +0000494/// CmpCaseVals - Comparison predicate for sorting case values.
495///
496static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
497 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
498 if (lhs.first < rhs.first)
499 return true;
500
501 if (lhs.first == rhs.first &&
502 lhs.second->getCaseLoc().getRawEncoding()
503 < rhs.second->getCaseLoc().getRawEncoding())
504 return true;
505 return false;
506}
507
Douglas Gregorba915af2010-02-08 22:24:16 +0000508/// CmpEnumVals - Comparison predicate for sorting enumeration values.
509///
510static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
511 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
512{
513 return lhs.first < rhs.first;
514}
515
516/// EqEnumVals - Comparison preficate for uniqing enumeration values.
517///
518static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
519 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
520{
521 return lhs.first == rhs.first;
522}
523
Chris Lattner5f048812009-10-16 16:45:22 +0000524/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
525/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000526static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
527 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
528 expr = cleanups->getSubExpr();
529 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
530 if (impcast->getCastKind() != CK_IntegralCast) break;
531 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000532 }
533 return expr->getType();
534}
535
John McCall60d7b3a2010-08-24 06:29:42 +0000536StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000537Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000538 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000539 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000540
Douglas Gregor586596f2010-05-06 17:25:47 +0000541 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000542 if (CondVar) {
543 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000544 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
545 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000546 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000547
John McCall9ae2f072010-08-23 23:25:46 +0000548 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000549 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550
John McCall9ae2f072010-08-23 23:25:46 +0000551 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000552 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553
Douglas Gregorab41fe92012-05-04 22:38:52 +0000554 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
555 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000556
Douglas Gregorab41fe92012-05-04 22:38:52 +0000557 public:
558 SwitchConvertDiagnoser(Expr *Cond)
559 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000560
Douglas Gregorab41fe92012-05-04 22:38:52 +0000561 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
562 QualType T) {
563 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
564 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000565
Douglas Gregorab41fe92012-05-04 22:38:52 +0000566 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
567 QualType T) {
568 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
569 << T << Cond->getSourceRange();
570 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000571
Douglas Gregorab41fe92012-05-04 22:38:52 +0000572 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
573 QualType T,
574 QualType ConvTy) {
575 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
576 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000577
Douglas Gregorab41fe92012-05-04 22:38:52 +0000578 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
579 QualType ConvTy) {
580 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
581 << ConvTy->isEnumeralType() << ConvTy;
582 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000583
Douglas Gregorab41fe92012-05-04 22:38:52 +0000584 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
585 QualType T) {
586 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
587 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000588
Douglas Gregorab41fe92012-05-04 22:38:52 +0000589 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
590 QualType ConvTy) {
591 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
592 << ConvTy->isEnumeralType() << ConvTy;
593 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000594
Douglas Gregorab41fe92012-05-04 22:38:52 +0000595 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
596 QualType T,
597 QualType ConvTy) {
598 return DiagnosticBuilder::getEmpty();
599 }
600 } SwitchDiagnoser(Cond);
601
John McCall9ae2f072010-08-23 23:25:46 +0000602 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000603 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000604 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000605 if (CondResult.isInvalid()) return StmtError();
606 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
John McCalla8e0cd82011-08-06 07:30:58 +0000608 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
609 CondResult = UsualUnaryConversions(Cond);
610 if (CondResult.isInvalid()) return StmtError();
611 Cond = CondResult.take();
612
John McCalld226f652010-08-21 09:40:31 +0000613 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000614 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000615 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000616 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000617 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000618 }
John McCallb60a77e2010-08-01 00:26:45 +0000619
John McCall781472f2010-08-25 08:40:02 +0000620 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000621
John McCall9ae2f072010-08-23 23:25:46 +0000622 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000623 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000624 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000625}
626
Gabor Greif28164ab2010-10-01 22:05:14 +0000627static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
628 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000629 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000630 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000631 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000632 Val.setIsSigned(IsSigned);
633}
634
John McCall60d7b3a2010-08-24 06:29:42 +0000635StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000636Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
637 Stmt *BodyStmt) {
638 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000639 assert(SS == getCurFunction()->SwitchStack.back() &&
640 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000641
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000642 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000643 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000644
Chris Lattnerf4021e72007-08-23 05:46:52 +0000645 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000646 if (!CondExpr) return StmtError();
647
648 QualType CondType = CondExpr->getType();
649
John McCall0fb97082010-05-18 03:19:21 +0000650 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000651 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000652 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000653
Chris Lattner5f048812009-10-16 16:45:22 +0000654 // C++ 6.4.2.p2:
655 // Integral promotions are performed (on the switch condition).
656 //
657 // A case value unrepresentable by the original switch condition
658 // type (before the promotion) doesn't make sense, even when it can
659 // be represented by the promoted type. Therefore we need to find
660 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000661 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000662 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000663 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000664 // appropriate type now, just return an error.
665 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000666 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000667
Chris Lattner2b334bb2010-04-16 23:34:13 +0000668 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000669 // switch(bool_expr) {...} is often a programmer error, e.g.
670 // switch(n && mask) { ... } // Doh - should be "n & mask".
671 // One can always use an if statement instead of switch(bool_expr).
672 Diag(SwitchLoc, diag::warn_bool_switch_condition)
673 << CondExpr->getSourceRange();
674 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000675 }
Sebastian Redlde307472009-01-11 00:38:46 +0000676
Chris Lattnerf4021e72007-08-23 05:46:52 +0000677 // Get the bitwidth of the switched-on value before promotions. We must
678 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000679 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000680 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000681 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000682 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000683 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000684 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattnerf4021e72007-08-23 05:46:52 +0000686 // Accumulate all of the case values in a vector so that we can sort them
687 // and detect duplicates. This vector contains the APInt for the case after
688 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000689 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000690 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattnerf4021e72007-08-23 05:46:52 +0000692 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000693 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
694 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattnerf4021e72007-08-23 05:46:52 +0000696 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000698 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Douglas Gregordbb26db2009-05-15 23:57:33 +0000700 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000701 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000703 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000704 if (TheDefaultStmt) {
705 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000706 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000707
Chris Lattnerf4021e72007-08-23 05:46:52 +0000708 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000709 // we'll return a valid AST. This requires recursing down the AST and
710 // finding it, not something we are set up to do right now. For now,
711 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000712 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000713 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000714 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattnerf4021e72007-08-23 05:46:52 +0000716 } else {
717 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Chris Lattner1e0a3902008-01-16 19:17:22 +0000719 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000720
721 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
722 HasDependentValue = true;
723 break;
724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Richard Smith8ef7b202012-01-18 23:55:52 +0000726 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Richard Smith80ad52f2013-01-02 11:42:31 +0000728 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000729 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
730 // constant expression of the promoted type of the switch condition.
731 ExprResult ConvLo =
732 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
733 if (ConvLo.isInvalid()) {
734 CaseListIsErroneous = true;
735 continue;
736 }
737 Lo = ConvLo.take();
738 } else {
739 // We already verified that the expression has a i-c-e value (C99
740 // 6.8.4.2p3) - get that value now.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000741 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smith8ef7b202012-01-18 23:55:52 +0000742
743 // If the LHS is not the same type as the condition, insert an implicit
744 // cast.
745 Lo = DefaultLvalueConversion(Lo).take();
746 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
747 }
748
749 // Convert the value to the same width/sign as the condition had prior to
750 // integral promotions.
751 //
752 // FIXME: This causes us to reject valid code:
753 // switch ((char)c) { case 256: case 0: return 0; }
754 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000755 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000756 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000757 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000758
Chris Lattner1e0a3902008-01-16 19:17:22 +0000759 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000761 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000762 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000763 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000764 CS->getRHS()->isValueDependent()) {
765 HasDependentValue = true;
766 break;
767 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000768 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000769 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000770 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000771 }
772 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000773
774 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000775 // If we don't have a default statement, check whether the
776 // condition is constant.
777 llvm::APSInt ConstantCondValue;
778 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000779 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000780 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000781 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
782 Expr::SE_AllowSideEffects);
783 assert(!HasConstantCond ||
784 (ConstantCondValue.getBitWidth() == CondWidth &&
785 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000786 }
Richard Smith80d4b552011-12-28 19:48:30 +0000787 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000788
Douglas Gregordbb26db2009-05-15 23:57:33 +0000789 // Sort all the scalar case values so we can easily detect duplicates.
790 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
791
792 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000793 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
794 if (ShouldCheckConstantCond &&
795 CaseVals[i].first == ConstantCondValue)
796 ShouldCheckConstantCond = false;
797
798 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000799 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000800 // First, determine if either case value has a name
801 StringRef PrevString, CurrString;
802 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
803 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
804 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
805 PrevString = DeclRef->getDecl()->getName();
806 }
807 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
808 CurrString = DeclRef->getDecl()->getName();
809 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000810 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000811 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000812
813 if (PrevString == CurrString)
814 Diag(CaseVals[i].second->getLHS()->getLocStart(),
815 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000816 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000817 else
818 Diag(CaseVals[i].second->getLHS()->getLocStart(),
819 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000820 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
821 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000822 CaseValStr;
823
John McCall0fb97082010-05-18 03:19:21 +0000824 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000825 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000826 // FIXME: We really want to remove the bogus case stmt from the
827 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000828 CaseListIsErroneous = true;
829 }
830 }
831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Douglas Gregordbb26db2009-05-15 23:57:33 +0000833 // Detect duplicate case ranges, which usually don't exist at all in
834 // the first place.
835 if (!CaseRanges.empty()) {
836 // Sort all the case ranges by their low value so we can easily detect
837 // overlaps between ranges.
838 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregordbb26db2009-05-15 23:57:33 +0000840 // Scan the ranges, computing the high values and removing empty ranges.
841 std::vector<llvm::APSInt> HiVals;
842 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000843 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000844 CaseStmt *CR = CaseRanges[i].second;
845 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000846 llvm::APSInt HiVal;
847
Richard Smith80ad52f2013-01-02 11:42:31 +0000848 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000849 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
850 // constant expression of the promoted type of the switch condition.
851 ExprResult ConvHi =
852 CheckConvertedConstantExpression(Hi, CondType, HiVal,
853 CCEK_CaseValue);
854 if (ConvHi.isInvalid()) {
855 CaseListIsErroneous = true;
856 continue;
857 }
858 Hi = ConvHi.take();
859 } else {
860 HiVal = Hi->EvaluateKnownConstInt(Context);
861
862 // If the RHS is not the same type as the condition, insert an
863 // implicit cast.
864 Hi = DefaultLvalueConversion(Hi).take();
865 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
866 }
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Douglas Gregordbb26db2009-05-15 23:57:33 +0000868 // Convert the value to the same width/sign as the condition.
869 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000870 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000871 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Douglas Gregordbb26db2009-05-15 23:57:33 +0000873 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Douglas Gregordbb26db2009-05-15 23:57:33 +0000875 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000876 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000877 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
878 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000879 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000880 CaseRanges.erase(CaseRanges.begin()+i);
881 --i, --e;
882 continue;
883 }
John McCall0fb97082010-05-18 03:19:21 +0000884
885 if (ShouldCheckConstantCond &&
886 LoVal <= ConstantCondValue &&
887 ConstantCondValue <= HiVal)
888 ShouldCheckConstantCond = false;
889
Douglas Gregordbb26db2009-05-15 23:57:33 +0000890 HiVals.push_back(HiVal);
891 }
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Douglas Gregordbb26db2009-05-15 23:57:33 +0000893 // Rescan the ranges, looking for overlap with singleton values and other
894 // ranges. Since the range list is sorted, we only need to compare case
895 // ranges with their neighbors.
896 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
897 llvm::APSInt &CRLo = CaseRanges[i].first;
898 llvm::APSInt &CRHi = HiVals[i];
899 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Douglas Gregordbb26db2009-05-15 23:57:33 +0000901 // Check to see whether the case range overlaps with any
902 // singleton cases.
903 CaseStmt *OverlapStmt = 0;
904 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregordbb26db2009-05-15 23:57:33 +0000906 // Find the smallest value >= the lower bound. If I is in the
907 // case range, then we have overlap.
908 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
909 CaseVals.end(), CRLo,
910 CaseCompareFunctor());
911 if (I != CaseVals.end() && I->first < CRHi) {
912 OverlapVal = I->first; // Found overlap with scalar.
913 OverlapStmt = I->second;
914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregordbb26db2009-05-15 23:57:33 +0000916 // Find the smallest value bigger than the upper bound.
917 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
918 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
919 OverlapVal = (I-1)->first; // Found overlap with scalar.
920 OverlapStmt = (I-1)->second;
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregordbb26db2009-05-15 23:57:33 +0000923 // Check to see if this case stmt overlaps with the subsequent
924 // case range.
925 if (i && CRLo <= HiVals[i-1]) {
926 OverlapVal = HiVals[i-1]; // Found overlap with range.
927 OverlapStmt = CaseRanges[i-1].second;
928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Douglas Gregordbb26db2009-05-15 23:57:33 +0000930 if (OverlapStmt) {
931 // If we have a duplicate, report it.
932 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
933 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000934 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000935 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000936 // FIXME: We really want to remove the bogus case stmt from the
937 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000938 CaseListIsErroneous = true;
939 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000940 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000941 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000942
John McCall0fb97082010-05-18 03:19:21 +0000943 // Complain if we have a constant condition and we didn't find a match.
944 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
945 // TODO: it would be nice if we printed enums as enums, chars as
946 // chars, etc.
947 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
948 << ConstantCondValue.toString(10)
949 << CondExpr->getSourceRange();
950 }
951
952 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000953 // values. We only issue a warning if there is not 'default:', but
954 // we still do the analysis to preserve this information in the AST
955 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000956 //
Chris Lattnerce784612010-09-16 17:09:42 +0000957 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000958
Douglas Gregorba915af2010-02-08 22:24:16 +0000959 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000960 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000961 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000962 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000963 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000964 EnumValsTy EnumVals;
965
John McCall0fb97082010-05-18 03:19:21 +0000966 // Gather all enum values, set their type and sort them,
967 // allowing easier comparison with CaseVals.
968 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000969 EDI != ED->enumerator_end(); ++EDI) {
970 llvm::APSInt Val = EDI->getInitVal();
971 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000972 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000973 }
974 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000975 EnumValsTy::iterator EIend =
976 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000977
978 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000979 EnumValsTy::const_iterator EI = EnumVals.begin();
980 for (CaseValsTy::const_iterator CI = CaseVals.begin();
981 CI != CaseVals.end(); CI++) {
982 while (EI != EIend && EI->first < CI->first)
983 EI++;
984 if (EI == EIend || EI->first > CI->first)
985 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000986 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000987 }
988 // See which of case ranges aren't in enum
989 EI = EnumVals.begin();
990 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
991 RI != CaseRanges.end() && EI != EIend; RI++) {
992 while (EI != EIend && EI->first < RI->first)
993 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000994
David Blaikie93667502012-01-22 02:31:55 +0000995 if (EI == EIend || EI->first != RI->first) {
996 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000997 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000998 }
David Blaikie93667502012-01-22 02:31:55 +0000999
Chad Rosier1093f492012-08-10 17:56:09 +00001000 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001001 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1002 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1003 while (EI != EIend && EI->first < Hi)
1004 EI++;
1005 if (EI == EIend || EI->first != Hi)
1006 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001007 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001008 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001009
Ted Kremenek559fb552010-09-09 00:05:53 +00001010 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001011 CaseValsTy::const_iterator CI = CaseVals.begin();
1012 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001013 bool hasCasesNotInSwitch = false;
1014
Chris Lattner5f9e2722011-07-23 10:55:15 +00001015 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001016
David Blaikie93667502012-01-22 02:31:55 +00001017 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001018 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001019 llvm::APSInt CIVal;
1020 while (CI != CaseVals.end() && CI->first < EI->first)
1021 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001022
Douglas Gregorba915af2010-02-08 22:24:16 +00001023 if (CI != CaseVals.end() && CI->first == EI->first)
1024 continue;
1025
Ted Kremenek559fb552010-09-09 00:05:53 +00001026 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001027 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001028 llvm::APSInt Hi =
1029 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001030 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001031 if (EI->first <= Hi)
1032 break;
1033 }
1034
Ted Kremenek559fb552010-09-09 00:05:53 +00001035 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001036 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001037 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001038 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040
David Blaikie585d7792012-01-23 04:46:12 +00001041 if (TheDefaultStmt && UnhandledNames.empty())
1042 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001043
Chris Lattnerce784612010-09-16 17:09:42 +00001044 // Produce a nice diagnostic if multiple values aren't handled.
1045 switch (UnhandledNames.size()) {
1046 case 0: break;
1047 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001048 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001049 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001050 << UnhandledNames[0];
1051 break;
1052 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001053 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001054 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001055 << UnhandledNames[0] << UnhandledNames[1];
1056 break;
1057 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001058 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1059 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001060 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1061 break;
1062 default:
David Blaikie585d7792012-01-23 04:46:12 +00001063 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1064 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001065 << (unsigned)UnhandledNames.size()
1066 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1067 break;
1068 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001069
1070 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001071 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001072 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001073 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001074
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001075 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1076 diag::warn_empty_switch_body);
1077
Mike Stump390b4cc2009-05-16 07:39:55 +00001078 // FIXME: If the case list was broken is some way, we don't have a good system
1079 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001080 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001081 return StmtError();
1082
Sebastian Redlde307472009-01-11 00:38:46 +00001083 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001084}
1085
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001086void
1087Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1088 Expr *SrcExpr) {
1089 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001090 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001091 == DiagnosticsEngine::Ignored)
1092 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001093
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001094 if (const EnumType *ET = DstType->getAs<EnumType>())
1095 if (!Context.hasSameType(SrcType, DstType) &&
1096 SrcType->isIntegerType()) {
1097 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1098 SrcExpr->isIntegerConstantExpr(Context)) {
1099 // Get the bitwidth of the enum value before promotions.
1100 unsigned DstWith = Context.getIntWidth(DstType);
1101 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1102
1103 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1104 const EnumDecl *ED = ET->getDecl();
1105 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1106 EnumValsTy;
1107 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001108
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001109 // Gather all enum values, set their type and sort them,
1110 // allowing easier comparison with rhs constant.
1111 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1112 EDI != ED->enumerator_end(); ++EDI) {
1113 llvm::APSInt Val = EDI->getInitVal();
1114 AdjustAPSInt(Val, DstWith, DstIsSigned);
1115 EnumVals.push_back(std::make_pair(Val, *EDI));
1116 }
1117 if (EnumVals.empty())
1118 return;
1119 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1120 EnumValsTy::iterator EIend =
1121 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001122
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001123 // See which case values aren't in enum.
1124 EnumValsTy::const_iterator EI = EnumVals.begin();
1125 while (EI != EIend && EI->first < RhsVal)
1126 EI++;
1127 if (EI == EIend || EI->first != RhsVal) {
1128 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1129 << DstType;
1130 }
1131 }
1132 }
1133}
1134
John McCall60d7b3a2010-08-24 06:29:42 +00001135StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001136Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001137 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001138 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001139
Douglas Gregor5656e142009-11-24 21:15:44 +00001140 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001141 if (CondVar) {
1142 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001143 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001144 if (CondResult.isInvalid())
1145 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001146 }
John McCall9ae2f072010-08-23 23:25:46 +00001147 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001148 if (!ConditionExpr)
1149 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001150
John McCall9ae2f072010-08-23 23:25:46 +00001151 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001153 if (isa<NullStmt>(Body))
1154 getCurCompoundScope().setHasEmptyLoopBodies();
1155
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001156 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001157 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001158}
1159
John McCall60d7b3a2010-08-24 06:29:42 +00001160StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001161Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001162 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001163 Expr *Cond, SourceLocation CondRParen) {
1164 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001165
John Wiegley429bb272011-04-08 18:41:53 +00001166 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001167 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001168 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001169 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001170
Richard Smith41956372013-01-14 22:39:08 +00001171 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001172 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001173 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001174 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001175
John McCall9ae2f072010-08-23 23:25:46 +00001176 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001177
John McCall9ae2f072010-08-23 23:25:46 +00001178 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001179}
1180
Richard Trieu694e7962012-04-30 18:01:30 +00001181namespace {
1182 // This visitor will traverse a conditional statement and store all
1183 // the evaluated decls into a vector. Simple is set to true if none
1184 // of the excluded constructs are used.
1185 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1186 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001187 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001188 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001189public:
1190 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1191
1192 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001193 SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001194 Inherited(S.Context),
1195 Decls(Decls),
1196 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001197 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001198
1199 bool isSimple() { return Simple; }
1200
1201 // Replaces the method in EvaluatedExprVisitor.
1202 void VisitMemberExpr(MemberExpr* E) {
1203 Simple = false;
1204 }
1205
1206 // Any Stmt not whitelisted will cause the condition to be marked complex.
1207 void VisitStmt(Stmt *S) {
1208 Simple = false;
1209 }
1210
1211 void VisitBinaryOperator(BinaryOperator *E) {
1212 Visit(E->getLHS());
1213 Visit(E->getRHS());
1214 }
1215
1216 void VisitCastExpr(CastExpr *E) {
1217 Visit(E->getSubExpr());
1218 }
1219
1220 void VisitUnaryOperator(UnaryOperator *E) {
1221 // Skip checking conditionals with derefernces.
1222 if (E->getOpcode() == UO_Deref)
1223 Simple = false;
1224 else
1225 Visit(E->getSubExpr());
1226 }
1227
1228 void VisitConditionalOperator(ConditionalOperator *E) {
1229 Visit(E->getCond());
1230 Visit(E->getTrueExpr());
1231 Visit(E->getFalseExpr());
1232 }
1233
1234 void VisitParenExpr(ParenExpr *E) {
1235 Visit(E->getSubExpr());
1236 }
1237
1238 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1239 Visit(E->getOpaqueValue()->getSourceExpr());
1240 Visit(E->getFalseExpr());
1241 }
1242
1243 void VisitIntegerLiteral(IntegerLiteral *E) { }
1244 void VisitFloatingLiteral(FloatingLiteral *E) { }
1245 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1246 void VisitCharacterLiteral(CharacterLiteral *E) { }
1247 void VisitGNUNullExpr(GNUNullExpr *E) { }
1248 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1249
1250 void VisitDeclRefExpr(DeclRefExpr *E) {
1251 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1252 if (!VD) return;
1253
1254 Ranges.push_back(E->getSourceRange());
1255
1256 Decls.insert(VD);
1257 }
1258
1259 }; // end class DeclExtractor
1260
1261 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001262 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001263 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1264 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1265 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001266
1267public:
1268 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1269
1270 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1271 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1272 if (!Statement) return;
1273
1274 Visit(Statement);
1275 }
1276
1277 void VisitReturnStmt(ReturnStmt *S) {
1278 FoundDecl = true;
1279 }
1280
1281 void VisitBreakStmt(BreakStmt *S) {
1282 FoundDecl = true;
1283 }
1284
1285 void VisitGotoStmt(GotoStmt *S) {
1286 FoundDecl = true;
1287 }
1288
1289 void VisitCastExpr(CastExpr *E) {
1290 if (E->getCastKind() == CK_LValueToRValue)
1291 CheckLValueToRValueCast(E->getSubExpr());
1292 else
1293 Visit(E->getSubExpr());
1294 }
1295
1296 void CheckLValueToRValueCast(Expr *E) {
1297 E = E->IgnoreParenImpCasts();
1298
1299 if (isa<DeclRefExpr>(E)) {
1300 return;
1301 }
1302
1303 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1304 Visit(CO->getCond());
1305 CheckLValueToRValueCast(CO->getTrueExpr());
1306 CheckLValueToRValueCast(CO->getFalseExpr());
1307 return;
1308 }
1309
1310 if (BinaryConditionalOperator *BCO =
1311 dyn_cast<BinaryConditionalOperator>(E)) {
1312 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1313 CheckLValueToRValueCast(BCO->getFalseExpr());
1314 return;
1315 }
1316
1317 Visit(E);
1318 }
1319
1320 void VisitDeclRefExpr(DeclRefExpr *E) {
1321 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1322 if (Decls.count(VD))
1323 FoundDecl = true;
1324 }
1325
1326 bool FoundDeclInUse() { return FoundDecl; }
1327
1328 }; // end class DeclMatcher
1329
1330 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1331 Expr *Third, Stmt *Body) {
1332 // Condition is empty
1333 if (!Second) return;
1334
1335 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1336 Second->getLocStart())
1337 == DiagnosticsEngine::Ignored)
1338 return;
1339
1340 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1341 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001342 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001343 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001344 DE.Visit(Second);
1345
1346 // Don't analyze complex conditionals.
1347 if (!DE.isSimple()) return;
1348
1349 // No decls found.
1350 if (Decls.size() == 0) return;
1351
Richard Trieu90875992012-05-04 03:01:54 +00001352 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001353 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1354 E = Decls.end();
1355 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001356 if ((*I)->getType().isVolatileQualified() ||
1357 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001358
1359 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1360 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1361 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1362 return;
1363
1364 // Load decl names into diagnostic.
1365 if (Decls.size() > 4)
1366 PDiag << 0;
1367 else {
1368 PDiag << Decls.size();
1369 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1370 E = Decls.end();
1371 I != E; ++I)
1372 PDiag << (*I)->getDeclName();
1373 }
1374
1375 // Load SourceRanges into diagnostic if there is room.
1376 // Otherwise, load the SourceRange of the conditional expression.
1377 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001378 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1379 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001380 I != E; ++I)
1381 PDiag << *I;
1382 else
1383 PDiag << Second->getSourceRange();
1384
1385 S.Diag(Ranges.begin()->getBegin(), PDiag);
1386 }
1387
1388} // end namespace
1389
John McCall60d7b3a2010-08-24 06:29:42 +00001390StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001391Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001392 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001393 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001394 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001395 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001396 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001397 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1398 // declare identifiers for objects having storage class 'auto' or
1399 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001400 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1401 DI!=DE; ++DI) {
1402 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001403 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001404 VD = 0;
1405 if (VD == 0)
1406 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1407 // FIXME: mark decl erroneous!
1408 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001409 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001411
Richard Trieu694e7962012-04-30 18:01:30 +00001412 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1413
John McCall60d7b3a2010-08-24 06:29:42 +00001414 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001415 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001416 if (secondVar) {
1417 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001418 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001419 if (SecondResult.isInvalid())
1420 return StmtError();
1421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001422
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001423 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001424
Anders Carlsson3af708f2009-08-01 01:39:59 +00001425 DiagnoseUnusedExprResult(First);
1426 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001427 DiagnoseUnusedExprResult(Body);
1428
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001429 if (isa<NullStmt>(Body))
1430 getCurCompoundScope().setHasEmptyLoopBodies();
1431
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001432 return Owned(new (Context) ForStmt(Context, First,
1433 SecondResult.take(), ConditionVar,
1434 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001435 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001436}
1437
John McCallf6a16482010-12-04 03:47:34 +00001438/// In an Objective C collection iteration statement:
1439/// for (x in y)
1440/// x can be an arbitrary l-value expression. Bind it up as a
1441/// full-expression.
1442StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001443 // Reduce placeholder expressions here. Note that this rejects the
1444 // use of pseudo-object l-values in this position.
1445 ExprResult result = CheckPlaceholderExpr(E);
1446 if (result.isInvalid()) return StmtError();
1447 E = result.take();
1448
Richard Smith41956372013-01-14 22:39:08 +00001449 ExprResult FullExpr = ActOnFinishFullExpr(E);
1450 if (FullExpr.isInvalid())
1451 return StmtError();
1452 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001453}
1454
John McCall990567c2011-07-27 01:07:15 +00001455ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001456Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1457 if (!collection)
1458 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001459
John McCall990567c2011-07-27 01:07:15 +00001460 // Bail out early if we've got a type-dependent expression.
1461 if (collection->isTypeDependent()) return Owned(collection);
1462
1463 // Perform normal l-value conversion.
1464 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1465 if (result.isInvalid())
1466 return ExprError();
1467 collection = result.take();
1468
1469 // The operand needs to have object-pointer type.
1470 // TODO: should we do a contextual conversion?
1471 const ObjCObjectPointerType *pointerType =
1472 collection->getType()->getAs<ObjCObjectPointerType>();
1473 if (!pointerType)
1474 return Diag(forLoc, diag::err_collection_expr_type)
1475 << collection->getType() << collection->getSourceRange();
1476
1477 // Check that the operand provides
1478 // - countByEnumeratingWithState:objects:count:
1479 const ObjCObjectType *objectType = pointerType->getObjectType();
1480 ObjCInterfaceDecl *iface = objectType->getInterface();
1481
1482 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001483 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001484 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001485 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001486 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001487 ? diag::err_arc_collection_forward
1488 : 0,
1489 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001490 // Otherwise, if we have any useful type information, check that
1491 // the type declares the appropriate method.
1492 } else if (iface || !objectType->qual_empty()) {
1493 IdentifierInfo *selectorIdents[] = {
1494 &Context.Idents.get("countByEnumeratingWithState"),
1495 &Context.Idents.get("objects"),
1496 &Context.Idents.get("count")
1497 };
1498 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1499
1500 ObjCMethodDecl *method = 0;
1501
1502 // If there's an interface, look in both the public and private APIs.
1503 if (iface) {
1504 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001505 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001506 }
1507
1508 // Also check protocol qualifiers.
1509 if (!method)
1510 method = LookupMethodInQualifiedType(selector, pointerType,
1511 /*instance*/ true);
1512
1513 // If we didn't find it anywhere, give up.
1514 if (!method) {
1515 Diag(forLoc, diag::warn_collection_expr_type)
1516 << collection->getType() << selector << collection->getSourceRange();
1517 }
1518
1519 // TODO: check for an incompatible signature?
1520 }
1521
1522 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001523 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001524}
1525
John McCall60d7b3a2010-08-24 06:29:42 +00001526StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001527Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001528 Stmt *First, Expr *collection,
1529 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001530
1531 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001532 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001533
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001534 if (First) {
1535 QualType FirstType;
1536 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001537 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001538 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1539 diag::err_toomany_element_decls));
1540
John McCallf85e1932011-06-15 23:02:42 +00001541 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1542 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001543 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1544 // declare identifiers for objects having storage class 'auto' or
1545 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001546 if (!D->hasLocalStorage())
1547 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001548 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001549 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001550 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001551 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001552 return StmtError(Diag(First->getLocStart(),
1553 diag::err_selector_element_not_lvalue)
1554 << First->getSourceRange());
1555
Mike Stump1eb44332009-09-09 15:08:12 +00001556 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001557 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001558 if (!FirstType->isDependentType() &&
1559 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001560 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001561 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1562 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001563 }
Chad Rosier1093f492012-08-10 17:56:09 +00001564
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001565 if (CollectionExprResult.isInvalid())
1566 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001567
Richard Smith41956372013-01-14 22:39:08 +00001568 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1569 if (CollectionExprResult.isInvalid())
1570 return StmtError();
1571
Chad Rosier1093f492012-08-10 17:56:09 +00001572 return Owned(new (Context) ObjCForCollectionStmt(First,
1573 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001574 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001575}
Reid Spencer5f016e22007-07-11 17:01:13 +00001576
Richard Smithad762fc2011-04-14 22:09:26 +00001577/// Finish building a variable declaration for a for-range statement.
1578/// \return true if an error occurs.
1579static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1580 SourceLocation Loc, int diag) {
1581 // Deduce the type for the iterator variable now rather than leaving it to
1582 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1583 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001584 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001585 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1586 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001587 SemaRef.Diag(Loc, diag) << Init->getType();
1588 if (!InitTSI) {
1589 Decl->setInvalidDecl();
1590 return true;
1591 }
1592 Decl->setTypeSourceInfo(InitTSI);
1593 Decl->setType(InitTSI->getType());
1594
John McCallf85e1932011-06-15 23:02:42 +00001595 // In ARC, infer lifetime.
1596 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1597 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001598 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001599 SemaRef.inferObjCARCLifetime(Decl))
1600 Decl->setInvalidDecl();
1601
Richard Smithad762fc2011-04-14 22:09:26 +00001602 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1603 /*TypeMayContainAuto=*/false);
1604 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001605 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001606 return false;
1607}
1608
Sam Panzere1715b62012-08-21 00:52:01 +00001609namespace {
1610
Richard Smithad762fc2011-04-14 22:09:26 +00001611/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001612/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001613/// nor from the diagnostics produced when analysing the implicit expressions
1614/// required in a for-range statement.
1615void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001616 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001617 CallExpr *CE = dyn_cast<CallExpr>(E);
1618 if (!CE)
1619 return;
1620 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1621 if (!D)
1622 return;
1623 SourceLocation Loc = D->getLocation();
1624
1625 std::string Description;
1626 bool IsTemplate = false;
1627 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1628 Description = SemaRef.getTemplateArgumentBindingsText(
1629 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1630 IsTemplate = true;
1631 }
1632
1633 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1634 << BEF << IsTemplate << Description << E->getType();
1635}
1636
Sam Panzere1715b62012-08-21 00:52:01 +00001637/// Build a variable declaration for a for-range statement.
1638VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1639 QualType Type, const char *Name) {
1640 DeclContext *DC = SemaRef.CurContext;
1641 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1642 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1643 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1644 TInfo, SC_Auto, SC_None);
1645 Decl->setImplicit();
1646 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001647}
1648
1649}
1650
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001651static bool ObjCEnumerationCollection(Expr *Collection) {
1652 return !Collection->isTypeDependent()
1653 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1654}
1655
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001656/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001657///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001658/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001659/// A range-based for statement is equivalent to
1660///
1661/// {
1662/// auto && __range = range-init;
1663/// for ( auto __begin = begin-expr,
1664/// __end = end-expr;
1665/// __begin != __end;
1666/// ++__begin ) {
1667/// for-range-declaration = *__begin;
1668/// statement
1669/// }
1670/// }
1671///
1672/// The body of the loop is not available yet, since it cannot be analysed until
1673/// we have determined the type of the for-range-declaration.
1674StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001675Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001676 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001677 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001678 if (!First || !Range)
1679 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001680
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001681 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001682 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001683
1684 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1685 assert(DS && "first part of for range not a decl stmt");
1686
1687 if (!DS->isSingleDecl()) {
1688 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1689 return StmtError();
1690 }
1691 if (DS->getSingleDecl()->isInvalidDecl())
1692 return StmtError();
1693
1694 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1695 return StmtError();
1696
1697 // Build auto && __range = range-init
1698 SourceLocation RangeLoc = Range->getLocStart();
1699 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1700 Context.getAutoRRefDeductType(),
1701 "__range");
1702 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1703 diag::err_for_range_deduction_failure))
1704 return StmtError();
1705
1706 // Claim the type doesn't contain auto: we've already done the checking.
1707 DeclGroupPtrTy RangeGroup =
1708 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1709 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1710 if (RangeDecl.isInvalid())
1711 return StmtError();
1712
1713 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1714 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001715 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001716}
1717
1718/// \brief Create the initialization, compare, and increment steps for
1719/// the range-based for loop expression.
1720/// This function does not handle array-based for loops,
1721/// which are created in Sema::BuildCXXForRangeStmt.
1722///
1723/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1724/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1725/// CandidateSet and BEF are set and some non-success value is returned on
1726/// failure.
1727static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1728 Expr *BeginRange, Expr *EndRange,
1729 QualType RangeType,
1730 VarDecl *BeginVar,
1731 VarDecl *EndVar,
1732 SourceLocation ColonLoc,
1733 OverloadCandidateSet *CandidateSet,
1734 ExprResult *BeginExpr,
1735 ExprResult *EndExpr,
1736 Sema::BeginEndFunction *BEF) {
1737 DeclarationNameInfo BeginNameInfo(
1738 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1739 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1740 ColonLoc);
1741
1742 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1743 Sema::LookupMemberName);
1744 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1745
1746 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1747 // - if _RangeT is a class type, the unqualified-ids begin and end are
1748 // looked up in the scope of class _RangeT as if by class member access
1749 // lookup (3.4.5), and if either (or both) finds at least one
1750 // declaration, begin-expr and end-expr are __range.begin() and
1751 // __range.end(), respectively;
1752 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1753 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1754
1755 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1756 SourceLocation RangeLoc = BeginVar->getLocation();
1757 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1758
1759 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1760 << RangeLoc << BeginRange->getType() << *BEF;
1761 return Sema::FRS_DiagnosticIssued;
1762 }
1763 } else {
1764 // - otherwise, begin-expr and end-expr are begin(__range) and
1765 // end(__range), respectively, where begin and end are looked up with
1766 // argument-dependent lookup (3.4.2). For the purposes of this name
1767 // lookup, namespace std is an associated namespace.
1768
1769 }
1770
1771 *BEF = Sema::BEF_begin;
1772 Sema::ForRangeStatus RangeStatus =
1773 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1774 Sema::BEF_begin, BeginNameInfo,
1775 BeginMemberLookup, CandidateSet,
1776 BeginRange, BeginExpr);
1777
1778 if (RangeStatus != Sema::FRS_Success)
1779 return RangeStatus;
1780 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1781 diag::err_for_range_iter_deduction_failure)) {
1782 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1783 return Sema::FRS_DiagnosticIssued;
1784 }
1785
1786 *BEF = Sema::BEF_end;
1787 RangeStatus =
1788 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1789 Sema::BEF_end, EndNameInfo,
1790 EndMemberLookup, CandidateSet,
1791 EndRange, EndExpr);
1792 if (RangeStatus != Sema::FRS_Success)
1793 return RangeStatus;
1794 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1795 diag::err_for_range_iter_deduction_failure)) {
1796 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1797 return Sema::FRS_DiagnosticIssued;
1798 }
1799 return Sema::FRS_Success;
1800}
1801
1802/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001803/// If the attempt fails, this function will return a valid, null StmtResult
1804/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001805static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1806 SourceLocation ForLoc,
1807 Stmt *LoopVarDecl,
1808 SourceLocation ColonLoc,
1809 Expr *Range,
1810 SourceLocation RangeLoc,
1811 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001812 // Determine whether we can rebuild the for-range statement with a
1813 // dereferenced range expression.
1814 ExprResult AdjustedRange;
1815 {
1816 Sema::SFINAETrap Trap(SemaRef);
1817
1818 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1819 if (AdjustedRange.isInvalid())
1820 return StmtResult();
1821
1822 StmtResult SR =
1823 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1824 AdjustedRange.get(), RParenLoc,
1825 Sema::BFRK_Check);
1826 if (SR.isInvalid())
1827 return StmtResult();
1828 }
1829
1830 // The attempt to dereference worked well enough that it could produce a valid
1831 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1832 // case there are any other (non-fatal) problems with it.
1833 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1834 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1835 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1836 AdjustedRange.get(), RParenLoc,
1837 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001838}
1839
Richard Smith8b533d92012-09-20 21:52:32 +00001840/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001841StmtResult
1842Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1843 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1844 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001845 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001846 Scope *S = getCurScope();
1847
1848 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1849 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1850 QualType RangeVarType = RangeVar->getType();
1851
1852 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1853 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1854
1855 StmtResult BeginEndDecl = BeginEnd;
1856 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1857
1858 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1859 SourceLocation RangeLoc = RangeVar->getLocation();
1860
Ted Kremeneke50b0152011-10-10 22:36:28 +00001861 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1862
1863 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1864 VK_LValue, ColonLoc);
1865 if (BeginRangeRef.isInvalid())
1866 return StmtError();
1867
1868 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1869 VK_LValue, ColonLoc);
1870 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001871 return StmtError();
1872
1873 QualType AutoType = Context.getAutoDeductType();
1874 Expr *Range = RangeVar->getInit();
1875 if (!Range)
1876 return StmtError();
1877 QualType RangeType = Range->getType();
1878
1879 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001880 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001881 return StmtError();
1882
1883 // Build auto __begin = begin-expr, __end = end-expr.
1884 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1885 "__begin");
1886 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1887 "__end");
1888
1889 // Build begin-expr and end-expr and attach to __begin and __end variables.
1890 ExprResult BeginExpr, EndExpr;
1891 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1892 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1893 // __range + __bound, respectively, where __bound is the array bound. If
1894 // _RangeT is an array of unknown size or an array of incomplete type,
1895 // the program is ill-formed;
1896
1897 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001898 BeginExpr = BeginRangeRef;
1899 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001900 diag::err_for_range_iter_deduction_failure)) {
1901 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1902 return StmtError();
1903 }
1904
1905 // Find the array bound.
1906 ExprResult BoundExpr;
1907 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1908 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001909 Context.getPointerDiffType(),
1910 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001911 else if (const VariableArrayType *VAT =
1912 dyn_cast<VariableArrayType>(UnqAT))
1913 BoundExpr = VAT->getSizeExpr();
1914 else {
1915 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1916 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001917 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001918 }
1919
1920 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001921 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001922 BoundExpr.get());
1923 if (EndExpr.isInvalid())
1924 return StmtError();
1925 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1926 diag::err_for_range_iter_deduction_failure)) {
1927 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1928 return StmtError();
1929 }
1930 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001931 OverloadCandidateSet CandidateSet(RangeLoc);
1932 Sema::BeginEndFunction BEFFailure;
1933 ForRangeStatus RangeStatus =
1934 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1935 EndRangeRef.get(), RangeType,
1936 BeginVar, EndVar, ColonLoc, &CandidateSet,
1937 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00001938
Sam Panzere1715b62012-08-21 00:52:01 +00001939 // If building the range failed, try dereferencing the range expression
1940 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00001941 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00001942 BEFFailure == BEF_begin) {
1943 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1944 LoopVarDecl, ColonLoc,
1945 Range, RangeLoc,
1946 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00001947 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00001948 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00001949 }
1950
Sam Panzere1715b62012-08-21 00:52:01 +00001951 // Otherwise, emit diagnostics if we haven't already.
1952 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00001953 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00001954 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1955 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00001956 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00001957 }
1958 // Return an error if no fix was discovered.
1959 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00001960 return StmtError();
1961 }
1962
Sam Panzere1715b62012-08-21 00:52:01 +00001963 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1964 "invalid range expression in for loop");
1965
1966 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00001967 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1968 if (!Context.hasSameType(BeginType, EndType)) {
1969 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1970 << BeginType << EndType;
1971 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1972 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1973 }
1974
1975 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1976 // Claim the type doesn't contain auto: we've already done the checking.
1977 DeclGroupPtrTy BeginEndGroup =
1978 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1979 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1980
Ted Kremeneke50b0152011-10-10 22:36:28 +00001981 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1982 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001983 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001984 if (BeginRef.isInvalid())
1985 return StmtError();
1986
Richard Smithad762fc2011-04-14 22:09:26 +00001987 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1988 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001989 if (EndRef.isInvalid())
1990 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001991
1992 // Build and check __begin != __end expression.
1993 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1994 BeginRef.get(), EndRef.get());
1995 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1996 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1997 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00001998 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
1999 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002000 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2001 if (!Context.hasSameType(BeginType, EndType))
2002 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2003 return StmtError();
2004 }
2005
2006 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002007 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2008 VK_LValue, ColonLoc);
2009 if (BeginRef.isInvalid())
2010 return StmtError();
2011
Richard Smithad762fc2011-04-14 22:09:26 +00002012 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2013 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2014 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002015 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2016 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002017 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2018 return StmtError();
2019 }
2020
2021 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002022 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2023 VK_LValue, ColonLoc);
2024 if (BeginRef.isInvalid())
2025 return StmtError();
2026
Richard Smithad762fc2011-04-14 22:09:26 +00002027 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2028 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002029 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2030 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002031 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2032 return StmtError();
2033 }
2034
Richard Smith8b533d92012-09-20 21:52:32 +00002035 // Attach *__begin as initializer for VD. Don't touch it if we're just
2036 // trying to determine whether this would be a valid range.
2037 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002038 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2039 /*TypeMayContainAuto=*/true);
2040 if (LoopVar->isInvalidDecl())
2041 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2042 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002043 } else {
2044 // The range is implicitly used as a placeholder when it is dependent.
2045 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002046 }
2047
Richard Smith8b533d92012-09-20 21:52:32 +00002048 // Don't bother to actually allocate the result if we're just trying to
2049 // determine whether it would be valid.
2050 if (Kind == BFRK_Check)
2051 return StmtResult();
2052
Richard Smithad762fc2011-04-14 22:09:26 +00002053 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2054 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2055 NotEqExpr.take(), IncrExpr.take(),
2056 LoopVarDS, /*Body=*/0, ForLoc,
2057 ColonLoc, RParenLoc));
2058}
2059
Chad Rosier1093f492012-08-10 17:56:09 +00002060/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002061/// statement.
2062StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2063 if (!S || !B)
2064 return StmtError();
2065 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002066
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002067 ForStmt->setBody(B);
2068 return S;
2069}
2070
Richard Smithad762fc2011-04-14 22:09:26 +00002071/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2072/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2073/// body cannot be performed until after the type of the range variable is
2074/// determined.
2075StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2076 if (!S || !B)
2077 return StmtError();
2078
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002079 if (isa<ObjCForCollectionStmt>(S))
2080 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002081
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002082 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2083 ForStmt->setBody(B);
2084
2085 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2086 diag::warn_empty_range_based_for_body);
2087
Richard Smithad762fc2011-04-14 22:09:26 +00002088 return S;
2089}
2090
Chris Lattner57ad3782011-02-17 20:34:02 +00002091StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2092 SourceLocation LabelLoc,
2093 LabelDecl *TheDecl) {
2094 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002095 TheDecl->setUsed();
2096 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002097}
2098
John McCall60d7b3a2010-08-24 06:29:42 +00002099StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002100Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002101 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002102 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002103 if (!E->isTypeDependent()) {
2104 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002105 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002106 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002107 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002108 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2109 if (ExprRes.isInvalid())
2110 return StmtError();
2111 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002112 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002113 return StmtError();
2114 }
John McCallb60a77e2010-08-01 00:26:45 +00002115
Richard Smith41956372013-01-14 22:39:08 +00002116 ExprResult ExprRes = ActOnFinishFullExpr(E);
2117 if (ExprRes.isInvalid())
2118 return StmtError();
2119 E = ExprRes.take();
2120
John McCall781472f2010-08-25 08:40:02 +00002121 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002122
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002123 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002124}
2125
John McCall60d7b3a2010-08-24 06:29:42 +00002126StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002127Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 Scope *S = CurScope->getContinueParent();
2129 if (!S) {
2130 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002131 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002133
Ted Kremenek8189cde2009-02-07 01:47:29 +00002134 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002135}
2136
John McCall60d7b3a2010-08-24 06:29:42 +00002137StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002138Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 Scope *S = CurScope->getBreakParent();
2140 if (!S) {
2141 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002142 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002144
Ted Kremenek8189cde2009-02-07 01:47:29 +00002145 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002146}
2147
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002148/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002149/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002150///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002151/// \param ReturnType If we're determining the copy elision candidate for
2152/// a return statement, this is the return type of the function. If we're
2153/// determining the copy elision candidate for a throw expression, this will
2154/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002155///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002156/// \param E The expression being returned from the function or block, or
2157/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002158///
Douglas Gregor4926d832011-05-20 15:00:53 +00002159/// \param AllowFunctionParameter Whether we allow function parameters to
2160/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2161/// we re-use this logic to determine whether we should try to move as part of
2162/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002163///
2164/// \returns The NRVO candidate variable, if the return statement may use the
2165/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002166const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2167 Expr *E,
2168 bool AllowFunctionParameter) {
2169 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002170 // - in a return statement in a function with ...
2171 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002172 if (!ReturnType.isNull()) {
2173 if (!ReturnType->isRecordType())
2174 return 0;
2175 // ... the same cv-unqualified type as the function return type ...
2176 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2177 return 0;
2178 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002179
2180 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002181 // (other than a function or catch-clause parameter)) ...
2182 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002183 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002184 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002185 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2186 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002187 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002188
John McCall1cd76e82011-11-11 03:57:31 +00002189 // ...object (other than a function or catch-clause parameter)...
2190 if (VD->getKind() != Decl::Var &&
2191 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2192 return 0;
2193 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002194
John McCall1cd76e82011-11-11 03:57:31 +00002195 // ...automatic...
2196 if (!VD->hasLocalStorage()) return 0;
2197
2198 // ...non-volatile...
2199 if (VD->getType().isVolatileQualified()) return 0;
2200 if (VD->getType()->isReferenceType()) return 0;
2201
2202 // __block variables can't be allocated in a way that permits NRVO.
2203 if (VD->hasAttr<BlocksAttr>()) return 0;
2204
2205 // Variables with higher required alignment than their type's ABI
2206 // alignment cannot use NRVO.
2207 if (VD->hasAttr<AlignedAttr>() &&
2208 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2209 return 0;
2210
2211 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002212}
2213
Douglas Gregor07f402c2011-01-21 21:08:57 +00002214/// \brief Perform the initialization of a potentially-movable value, which
2215/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002216///
2217/// This routine implements C++0x [class.copy]p33, which attempts to treat
2218/// returned lvalues as rvalues in certain cases (to prefer move construction),
2219/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002220ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002221Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2222 const VarDecl *NRVOCandidate,
2223 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002224 Expr *Value,
2225 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002226 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002227 // When the criteria for elision of a copy operation are met or would
2228 // be met save for the fact that the source object is a function
2229 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002230 // overload resolution to select the constructor for the copy is first
2231 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002232 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002233 if (AllowNRVO &&
2234 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002235 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002236 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002237
Douglas Gregorcc15f012011-01-21 19:38:21 +00002238 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002239 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002240 = InitializationKind::CreateCopy(Value->getLocStart(),
2241 Value->getLocStart());
2242 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002243
2244 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002245 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002246 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002247 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002248 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002249 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2250 StepEnd = Seq.step_end();
2251 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002252 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002253 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002254
2255 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002256 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002257
Douglas Gregorcc15f012011-01-21 19:38:21 +00002258 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002259 = Constructor->getParamDecl(0)->getType()
2260 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002261
Douglas Gregorcc15f012011-01-21 19:38:21 +00002262 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002264 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2265 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002267
Douglas Gregorcc15f012011-01-21 19:38:21 +00002268 // Promote "AsRvalue" to the heap, since we now need this
2269 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002270 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002271 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002272
Douglas Gregorcc15f012011-01-21 19:38:21 +00002273 // Complete type-checking the initialization of the return type
2274 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002275 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002276 }
2277 }
2278 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002279
Douglas Gregorcc15f012011-01-21 19:38:21 +00002280 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002281 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002282 // (again) now with the return value expression as written.
2283 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002284 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002285
Douglas Gregorcc15f012011-01-21 19:38:21 +00002286 return Res;
2287}
2288
Eli Friedman84b007f2012-01-26 03:00:14 +00002289/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2290/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002291///
John McCall60d7b3a2010-08-24 06:29:42 +00002292StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002293Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2294 // If this is the first return we've seen, infer the return type.
2295 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2296 // rules which allows multiple return statements.
2297 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002298 QualType FnRetType = CurCap->ReturnType;
2299
2300 // For blocks/lambdas with implicit return types, we check each return
2301 // statement individually, and deduce the common return type when the block
2302 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002303 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002304 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002305 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2306 if (Result.isInvalid())
2307 return StmtError();
2308 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002309
Jordan Rose7dd900e2012-07-02 21:19:23 +00002310 if (!RetValExp->isTypeDependent())
2311 FnRetType = RetValExp->getType();
2312 else
2313 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002314 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002315 if (RetValExp) {
2316 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2317 // initializer list, because it is not an expression (even
2318 // though we represent it as one). We still deduce 'void'.
2319 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2320 << RetValExp->getSourceRange();
2321 }
2322
Jordan Rose7dd900e2012-07-02 21:19:23 +00002323 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002324 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002325
2326 // Although we'll properly infer the type of the block once it's completed,
2327 // make sure we provide a return type now for better error recovery.
2328 if (CurCap->ReturnType.isNull())
2329 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002330 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002331 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002332
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002333 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002334 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2335 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2336 return StmtError();
2337 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002338 } else {
2339 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2340 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2341 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2342 return StmtError();
2343 }
2344 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002345
Steve Naroff4eb206b2008-09-03 18:15:37 +00002346 // Otherwise, verify that this result type matches the previous one. We are
2347 // pickier with blocks than for normal functions because we don't have GCC
2348 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002349 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002350 if (FnRetType->isDependentType()) {
2351 // Delay processing for now. TODO: there are lots of dependent
2352 // types we can conclusively prove aren't void.
2353 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002354 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002355 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002356 (RetValExp->isTypeDependent() ||
2357 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002358 if (!getLangOpts().CPlusPlus &&
2359 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002360 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002361 else {
2362 Diag(ReturnLoc, diag::err_return_block_has_expr);
2363 RetValExp = 0;
2364 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002365 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002366 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002367 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2368 } else if (!RetValExp->isTypeDependent()) {
2369 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002370
John McCall0a7efe12011-08-17 22:09:46 +00002371 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2372 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2373 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002374
John McCall0a7efe12011-08-17 22:09:46 +00002375 // In C++ the return statement is handled via a copy initialization.
2376 // the C version of which boils down to CheckSingleAssignmentConstraints.
2377 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2378 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2379 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002380 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002381 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2382 FnRetType, RetValExp);
2383 if (Res.isInvalid()) {
2384 // FIXME: Cleanup temporaries here, anyway?
2385 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002386 }
John McCall0a7efe12011-08-17 22:09:46 +00002387 RetValExp = Res.take();
2388 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002389 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002390
John McCalld963c372011-08-17 21:34:14 +00002391 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002392 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2393 if (ER.isInvalid())
2394 return StmtError();
2395 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002396 }
John McCall0a7efe12011-08-17 22:09:46 +00002397 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2398 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002399
Jordan Rose7dd900e2012-07-02 21:19:23 +00002400 // If we need to check for the named return value optimization,
2401 // or if we need to infer the return type,
2402 // save the return statement in our scope for later processing.
2403 if (CurCap->HasImplicitReturnType ||
2404 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2405 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002406 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002407
Douglas Gregor5077c382010-05-15 06:01:05 +00002408 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002409}
Reid Spencer5f016e22007-07-11 17:01:13 +00002410
John McCall60d7b3a2010-08-24 06:29:42 +00002411StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002412Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002413 // Check for unexpanded parameter packs.
2414 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2415 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002416
Eli Friedman84b007f2012-01-26 03:00:14 +00002417 if (isa<CapturingScopeInfo>(getCurFunction()))
2418 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002419
Chris Lattner371f2582008-12-04 23:50:19 +00002420 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002421 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002422 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002423 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002424 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002425 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002426 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002427 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002428 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002429 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2430 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002431 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002432 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002433 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2434 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002435 }
2436 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002437 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Douglas Gregor5077c382010-05-15 06:01:05 +00002439 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002440 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002441 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002442 if (isa<InitListExpr>(RetValExp)) {
2443 // We simply never allow init lists as the return value of void
2444 // functions. This is compatible because this was never allowed before,
2445 // so there's no legacy code to deal with.
2446 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2447 int FunctionKind = 0;
2448 if (isa<ObjCMethodDecl>(CurDecl))
2449 FunctionKind = 1;
2450 else if (isa<CXXConstructorDecl>(CurDecl))
2451 FunctionKind = 2;
2452 else if (isa<CXXDestructorDecl>(CurDecl))
2453 FunctionKind = 3;
2454
2455 Diag(ReturnLoc, diag::err_return_init_list)
2456 << CurDecl->getDeclName() << FunctionKind
2457 << RetValExp->getSourceRange();
2458
2459 // Drop the expression.
2460 RetValExp = 0;
2461 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002462 // C99 6.8.6.4p1 (ext_ since GCC warns)
2463 unsigned D = diag::ext_return_has_expr;
2464 if (RetValExp->getType()->isVoidType())
2465 D = diag::ext_return_has_void_expr;
2466 else {
2467 ExprResult Result = Owned(RetValExp);
2468 Result = IgnoredValueConversions(Result.take());
2469 if (Result.isInvalid())
2470 return StmtError();
2471 RetValExp = Result.take();
2472 RetValExp = ImpCastExprToType(RetValExp,
2473 Context.VoidTy, CK_ToVoid).take();
2474 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002475
Nick Lewycky8d794612011-06-01 07:44:31 +00002476 // return (some void expression); is legal in C++.
2477 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002478 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002479 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002480
2481 int FunctionKind = 0;
2482 if (isa<ObjCMethodDecl>(CurDecl))
2483 FunctionKind = 1;
2484 else if (isa<CXXConstructorDecl>(CurDecl))
2485 FunctionKind = 2;
2486 else if (isa<CXXDestructorDecl>(CurDecl))
2487 FunctionKind = 3;
2488
Nick Lewycky8d794612011-06-01 07:44:31 +00002489 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002490 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002491 << RetValExp->getSourceRange();
2492 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002493 }
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Sebastian Redl33deb352012-02-22 10:50:08 +00002495 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002496 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2497 if (ER.isInvalid())
2498 return StmtError();
2499 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002500 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002502
Douglas Gregor5077c382010-05-15 06:01:05 +00002503 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2504 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002505 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2506 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002507 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002508
2509 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002510 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002511 else
Chris Lattner08631c52008-11-23 21:45:46 +00002512 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002513 Result = new (Context) ReturnStmt(ReturnLoc);
2514 } else {
2515 const VarDecl *NRVOCandidate = 0;
2516 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2517 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002518
Eli Friedman38ac2432012-03-30 01:13:43 +00002519 if (!RelatedRetType.isNull()) {
2520 // If we have a related result type, perform an extra conversion here.
2521 // FIXME: The diagnostics here don't really describe what is happening.
2522 InitializedEntity Entity =
2523 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002524
Eli Friedman38ac2432012-03-30 01:13:43 +00002525 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2526 RetValExp);
2527 if (Res.isInvalid()) {
2528 // FIXME: Cleanup temporaries here, anyway?
2529 return StmtError();
2530 }
2531 RetValExp = Res.takeAs<Expr>();
2532 }
2533
Douglas Gregor5077c382010-05-15 06:01:05 +00002534 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2535 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2536 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002537
John McCall856d3792011-06-16 23:24:51 +00002538 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002539 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002540 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002542 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002543 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002544 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002545 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002546 if (Res.isInvalid()) {
2547 // FIXME: Cleanup temporaries here, anyway?
2548 return StmtError();
2549 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002550
Douglas Gregor5077c382010-05-15 06:01:05 +00002551 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002552 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002553 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002554 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002555
John McCallb4eb64d2010-10-08 02:01:28 +00002556 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002557 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2558 if (ER.isInvalid())
2559 return StmtError();
2560 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002561 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002562 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002563 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002564
2565 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002566 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002567 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002568 !CurContext->isDependentContext())
2569 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002570
Douglas Gregor5077c382010-05-15 06:01:05 +00002571 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002572}
2573
John McCall60d7b3a2010-08-24 06:29:42 +00002574StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002575Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002576 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002577 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002578 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002579 if (Var && Var->isInvalidDecl())
2580 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002581
John McCall9ae2f072010-08-23 23:25:46 +00002582 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002583}
2584
John McCall60d7b3a2010-08-24 06:29:42 +00002585StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002586Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2587 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002588}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002589
John McCall60d7b3a2010-08-24 06:29:42 +00002590StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002591Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002592 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002593 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002594 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2595
John McCall781472f2010-08-25 08:40:02 +00002596 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002597 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002598 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002599 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002600 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002601 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002602}
2603
John McCalld1376ee2012-05-08 21:41:25 +00002604StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002605 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002606 ExprResult Result = DefaultLvalueConversion(Throw);
2607 if (Result.isInvalid())
2608 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002609
Richard Smith41956372013-01-14 22:39:08 +00002610 Result = ActOnFinishFullExpr(Result.take());
2611 if (Result.isInvalid())
2612 return StmtError();
2613 Throw = Result.take();
2614
Douglas Gregord1377b22010-04-22 21:44:01 +00002615 QualType ThrowType = Throw->getType();
2616 // Make sure the expression type is an ObjC pointer or "void *".
2617 if (!ThrowType->isDependentType() &&
2618 !ThrowType->isObjCObjectPointerType()) {
2619 const PointerType *PT = ThrowType->getAs<PointerType>();
2620 if (!PT || !PT->getPointeeType()->isVoidType())
2621 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2622 << Throw->getType() << Throw->getSourceRange());
2623 }
2624 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625
John McCall9ae2f072010-08-23 23:25:46 +00002626 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002627}
2628
John McCall60d7b3a2010-08-24 06:29:42 +00002629StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002630Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002631 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002632 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002633 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2634
John McCall9ae2f072010-08-23 23:25:46 +00002635 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002636 // @throw without an expression designates a rethrow (which much occur
2637 // in the context of an @catch clause).
2638 Scope *AtCatchParent = CurScope;
2639 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2640 AtCatchParent = AtCatchParent->getParent();
2641 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002642 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643 }
John McCall9ae2f072010-08-23 23:25:46 +00002644 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002645}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002646
John McCall07524032011-07-27 21:50:02 +00002647ExprResult
2648Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2649 ExprResult result = DefaultLvalueConversion(operand);
2650 if (result.isInvalid())
2651 return ExprError();
2652 operand = result.take();
2653
2654 // Make sure the expression type is an ObjC pointer or "void *".
2655 QualType type = operand->getType();
2656 if (!type->isDependentType() &&
2657 !type->isObjCObjectPointerType()) {
2658 const PointerType *pointerType = type->getAs<PointerType>();
2659 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2660 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2661 << type << operand->getSourceRange();
2662 }
2663
2664 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002665 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002666}
2667
John McCall60d7b3a2010-08-24 06:29:42 +00002668StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002669Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2670 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002671 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002672 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002673 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002674}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002675
2676/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2677/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002678StmtResult
John McCalld226f652010-08-21 09:40:31 +00002679Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002680 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002681 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002682 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002683 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002684 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002685}
Sebastian Redl8351da02008-12-22 21:35:02 +00002686
John McCallf85e1932011-06-15 23:02:42 +00002687StmtResult
2688Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2689 getCurFunction()->setHasBranchProtectedScope();
2690 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2691}
2692
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002693namespace {
2694
Sebastian Redlc447aba2009-07-29 17:15:45 +00002695class TypeWithHandler {
2696 QualType t;
2697 CXXCatchStmt *stmt;
2698public:
2699 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2700 : t(type), stmt(statement) {}
2701
John McCall0953e762009-09-24 19:53:00 +00002702 // An arbitrary order is fine as long as it places identical
2703 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002704 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002705 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002706 return true;
John McCall0953e762009-09-24 19:53:00 +00002707 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002708 return false;
2709 else
2710 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2711 }
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Sebastian Redlc447aba2009-07-29 17:15:45 +00002713 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002714 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002715 }
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Sebastian Redlc447aba2009-07-29 17:15:45 +00002717 CXXCatchStmt *getCatchStmt() const { return stmt; }
2718 SourceLocation getTypeSpecStartLoc() const {
2719 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2720 }
2721};
2722
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002723}
2724
Sebastian Redl8351da02008-12-22 21:35:02 +00002725/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2726/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002727StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002728Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002729 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002730 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002731 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002732 !getSourceManager().isInSystemHeader(TryLoc))
2733 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002734
Sebastian Redl8351da02008-12-22 21:35:02 +00002735 unsigned NumHandlers = RawHandlers.size();
2736 assert(NumHandlers > 0 &&
2737 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002738 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002739
Chris Lattner5f9e2722011-07-23 10:55:15 +00002740 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002741
2742 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002743 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002744 if (!Handler->getExceptionDecl()) {
2745 if (i < NumHandlers - 1)
2746 return StmtError(Diag(Handler->getLocStart(),
2747 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Sebastian Redlc447aba2009-07-29 17:15:45 +00002749 continue;
2750 }
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Sebastian Redlc447aba2009-07-29 17:15:45 +00002752 const QualType CaughtType = Handler->getCaughtType();
2753 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2754 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002755 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002756
2757 // Detect handlers for the same type as an earlier one.
2758 if (NumHandlers > 1) {
2759 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Sebastian Redlc447aba2009-07-29 17:15:45 +00002761 TypeWithHandler prev = TypesWithHandlers[0];
2762 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2763 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Sebastian Redlc447aba2009-07-29 17:15:45 +00002765 if (curr == prev) {
2766 Diag(curr.getTypeSpecStartLoc(),
2767 diag::warn_exception_caught_by_earlier_handler)
2768 << curr.getCatchStmt()->getCaughtType().getAsString();
2769 Diag(prev.getTypeSpecStartLoc(),
2770 diag::note_previous_exception_handler)
2771 << prev.getCatchStmt()->getCaughtType().getAsString();
2772 }
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Sebastian Redlc447aba2009-07-29 17:15:45 +00002774 prev = curr;
2775 }
2776 }
Mike Stump1eb44332009-09-09 15:08:12 +00002777
John McCall781472f2010-08-25 08:40:02 +00002778 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002779
Sebastian Redl8351da02008-12-22 21:35:02 +00002780 // FIXME: We should detect handlers that cannot catch anything because an
2781 // earlier handler catches a superclass. Need to find a method that is not
2782 // quadratic for this.
2783 // Neither of these are explicitly forbidden, but every compiler detects them
2784 // and warns.
2785
John McCall9ae2f072010-08-23 23:25:46 +00002786 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002787 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002788}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002789
2790StmtResult
2791Sema::ActOnSEHTryBlock(bool IsCXXTry,
2792 SourceLocation TryLoc,
2793 Stmt *TryBlock,
2794 Stmt *Handler) {
2795 assert(TryBlock && Handler);
2796
2797 getCurFunction()->setHasBranchProtectedScope();
2798
2799 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2800}
2801
2802StmtResult
2803Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2804 Expr *FilterExpr,
2805 Stmt *Block) {
2806 assert(FilterExpr && Block);
2807
2808 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002809 return StmtError(Diag(FilterExpr->getExprLoc(),
2810 diag::err_filter_expression_integral)
2811 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002812 }
2813
2814 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2815}
2816
2817StmtResult
2818Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2819 Stmt *Block) {
2820 assert(Block);
2821 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2822}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002823
2824StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2825 bool IsIfExists,
2826 NestedNameSpecifierLoc QualifierLoc,
2827 DeclarationNameInfo NameInfo,
2828 Stmt *Nested)
2829{
2830 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002831 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002832 cast<CompoundStmt>(Nested));
2833}
2834
2835
Chad Rosier1093f492012-08-10 17:56:09 +00002836StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002837 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002838 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002839 UnqualifiedId &Name,
2840 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002841 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002842 SS.getWithLocInContext(Context),
2843 GetNameFromUnqualifiedId(Name),
2844 Nested);
2845}