blob: 09c418072d60d37b4e10767e2b79d8e294b27096 [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;
160
Eli Friedmana6115062012-05-24 00:47:05 +0000161 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000162 SourceLocation Loc;
163 SourceRange R1, R2;
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +0000164 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmana6115062012-05-24 00:47:05 +0000165 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000166 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattner06b3a062012-08-31 22:39:21 +0000168 // If this is a GNU statement expression expanded from a macro, it is probably
169 // unused because it is a function-like macro that can be used as either an
170 // expression or statement. Don't warn, because it is almost certainly a
171 // false positive.
172 if (isa<StmtExpr>(E) && Loc.isMacroID())
173 return;
174
Chris Lattner419cfb32009-08-16 16:57:27 +0000175 // Okay, we have an unused result. Depending on what the base expression is,
176 // we might want to make a more specific diagnostic. Check for one of these
177 // cases now.
178 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000179 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000180 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000181 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
182 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000183
Chandler Carruthec8058f2011-08-17 09:34:37 +0000184 if (DiagnoseUnusedComparison(*this, E))
185 return;
186
Eli Friedmana6115062012-05-24 00:47:05 +0000187 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000188 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000189 if (E->getType()->isVoidType())
190 return;
191
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000192 // If the callee has attribute pure, const, or warn_unused_result, warn with
193 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000194 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000195 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000196 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000197 return;
198 }
199 if (FD->getAttr<PureAttr>()) {
200 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
201 return;
202 }
203 if (FD->getAttr<ConstAttr>()) {
204 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
205 return;
206 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000207 }
John McCall12f78a62010-12-02 01:19:52 +0000208 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000209 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000210 Diag(Loc, diag::err_arc_unused_init_message) << R1;
211 return;
212 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000213 const ObjCMethodDecl *MD = ME->getMethodDecl();
214 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000215 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000216 return;
217 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000218 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
219 const Expr *Source = POE->getSyntacticForm();
220 if (isa<ObjCSubscriptRefExpr>(Source))
221 DiagID = diag::warn_unused_container_subscript_expr;
222 else
223 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000224 } else if (const CXXFunctionalCastExpr *FC
225 = dyn_cast<CXXFunctionalCastExpr>(E)) {
226 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
227 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
228 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000229 }
John McCall209acbd2010-04-06 22:24:14 +0000230 // Diagnose "(void*) blah" as a typo for "(void) blah".
231 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
232 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
233 QualType T = TI->getType();
234
235 // We really do want to use the non-canonical type here.
236 if (T == Context.VoidPtrTy) {
237 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
238
239 Diag(Loc, diag::warn_unused_voidptr)
240 << FixItHint::CreateRemoval(TL.getStarLoc());
241 return;
242 }
243 }
244
Eli Friedmana6115062012-05-24 00:47:05 +0000245 if (E->isGLValue() && E->getType().isVolatileQualified()) {
246 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
247 return;
248 }
249
Ted Kremenek351ba912011-02-23 01:52:04 +0000250 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000251}
252
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000253void Sema::ActOnStartOfCompoundStmt() {
254 PushCompoundScope();
255}
256
257void Sema::ActOnFinishOfCompoundStmt() {
258 PopCompoundScope();
259}
260
261sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
262 return getCurFunction()->CompoundScopes.back();
263}
264
John McCall60d7b3a2010-08-24 06:29:42 +0000265StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000266Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000267 MultiStmtArg elts, bool isStmtExpr) {
268 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000270 // If we're in C89 mode, check that we don't have any decls after stmts. If
271 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000272 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000273 // Note that __extension__ can be around a decl.
274 unsigned i = 0;
275 // Skip over all declarations.
276 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
277 /*empty*/;
278
279 // We found the end of the list or a statement. Scan for another declstmt.
280 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
281 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000283 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000284 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000285 Diag(D->getLocation(), diag::ext_mixed_decls_code);
286 }
287 }
Chris Lattner98414c12007-08-31 21:49:55 +0000288 // Warn about unused expressions in statements.
289 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000290 // Ignore statements that are last in a statement expression.
291 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000292 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Anders Carlsson636463e2009-07-30 22:17:18 +0000294 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000295 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000296
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000297 // Check for suspicious empty body (null statement) in `for' and `while'
298 // statements. Don't do anything for template instantiations, this just adds
299 // noise.
300 if (NumElts != 0 && !CurrentInstantiationScope &&
301 getCurCompoundScope().HasEmptyLoopBodies) {
302 for (unsigned i = 0; i != NumElts - 1; ++i)
303 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
304 }
305
Nico Weberd36aa352012-12-29 20:03:39 +0000306 return Owned(new (Context) CompoundStmt(Context,
307 llvm::makeArrayRef(Elts, NumElts),
308 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000309}
310
John McCall60d7b3a2010-08-24 06:29:42 +0000311StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000312Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
313 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000314 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000315 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000316
John McCall781472f2010-08-25 08:40:02 +0000317 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000318 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000319 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000320 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000321
Richard Smith80ad52f2013-01-02 11:42:31 +0000322 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000323 // C99 6.8.4.2p3: The expression shall be an integer constant.
324 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000325 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
326 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
327 if (!LHSVal)
328 return StmtError();
329 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000330
331 // GCC extension: The expression shall be an integer constant.
332
Richard Smith282e7e62012-02-04 09:53:13 +0000333 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
334 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
335 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000336 }
337 }
338
Douglas Gregordbb26db2009-05-15 23:57:33 +0000339 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
340 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000341 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000342 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000343}
344
Chris Lattner24e1e702009-03-04 04:23:07 +0000345/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000346void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000347 DiagnoseUnusedExprResult(SubStmt);
348
Chris Lattner24e1e702009-03-04 04:23:07 +0000349 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000350 CS->setSubStmt(SubStmt);
351}
352
John McCall60d7b3a2010-08-24 06:29:42 +0000353StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000354Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000355 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000356 DiagnoseUnusedExprResult(SubStmt);
357
John McCall781472f2010-08-25 08:40:02 +0000358 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000359 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000360 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000361 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000362
Douglas Gregordbb26db2009-05-15 23:57:33 +0000363 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000364 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000365 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000366}
367
John McCall60d7b3a2010-08-24 06:29:42 +0000368StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000369Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
370 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000371 // If the label was multiply defined, reject it now.
372 if (TheDecl->getStmt()) {
373 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
374 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000375 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 }
Sebastian Redlde307472009-01-11 00:38:46 +0000377
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000378 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000379 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
380 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000381 if (!TheDecl->isGnuLocal()) {
382 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000383 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000384 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000385 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000386}
387
Richard Smith534986f2012-04-14 00:33:13 +0000388StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000389 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000390 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000391 // Fill in the declaration and return it.
392 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000393 return Owned(LS);
394}
395
John McCall60d7b3a2010-08-24 06:29:42 +0000396StmtResult
John McCalld226f652010-08-21 09:40:31 +0000397Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000398 Stmt *thenStmt, SourceLocation ElseLoc,
399 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000400 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000402 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000403 if (CondVar) {
404 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000405 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000406 if (CondResult.isInvalid())
407 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000408 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000409 Expr *ConditionExpr = CondResult.takeAs<Expr>();
410 if (!ConditionExpr)
411 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000412
Anders Carlsson75443112009-07-30 22:39:03 +0000413 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000414
John McCall9ae2f072010-08-23 23:25:46 +0000415 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000416 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
417 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000418 }
419
Anders Carlsson75443112009-07-30 22:39:03 +0000420 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000421
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000422 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000423 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000424}
425
Chris Lattnerf4021e72007-08-23 05:46:52 +0000426/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
427/// the specified width and sign. If an overflow occurs, detect it and emit
428/// the specified diagnostic.
429void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
430 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000431 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000432 unsigned DiagID) {
433 // Perform a conversion to the promoted condition type if needed.
434 if (NewWidth > Val.getBitWidth()) {
435 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000436 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000437 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000438
439 // If the input was signed and negative and the output is
440 // unsigned, don't bother to warn: this is implementation-defined
441 // behavior.
442 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000443 } else if (NewWidth < Val.getBitWidth()) {
444 // If this is a truncation, check for overflow.
445 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000446 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000447 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000448 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000449 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000450 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000451 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattnerf4021e72007-08-23 05:46:52 +0000453 // Regardless of whether a diagnostic was emitted, really do the
454 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000455 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000456 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000457 } else if (NewSign != Val.isSigned()) {
458 // Convert the sign to match the sign of the condition. This can cause
459 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000460 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000461 // behavior.
462 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000463 llvm::APSInt OldVal(Val);
464 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000465 }
466}
467
Chris Lattner0471f5b2007-08-23 18:29:20 +0000468namespace {
469 struct CaseCompareFunctor {
470 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
471 const llvm::APSInt &RHS) {
472 return LHS.first < RHS;
473 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000474 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
475 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
476 return LHS.first < RHS.first;
477 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000478 bool operator()(const llvm::APSInt &LHS,
479 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
480 return LHS < RHS.first;
481 }
482 };
483}
484
Chris Lattner764a7ce2007-09-21 18:15:22 +0000485/// CmpCaseVals - Comparison predicate for sorting case values.
486///
487static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
488 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
489 if (lhs.first < rhs.first)
490 return true;
491
492 if (lhs.first == rhs.first &&
493 lhs.second->getCaseLoc().getRawEncoding()
494 < rhs.second->getCaseLoc().getRawEncoding())
495 return true;
496 return false;
497}
498
Douglas Gregorba915af2010-02-08 22:24:16 +0000499/// CmpEnumVals - Comparison predicate for sorting enumeration values.
500///
501static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
502 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
503{
504 return lhs.first < rhs.first;
505}
506
507/// EqEnumVals - Comparison preficate for uniqing enumeration values.
508///
509static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
510 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
511{
512 return lhs.first == rhs.first;
513}
514
Chris Lattner5f048812009-10-16 16:45:22 +0000515/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
516/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000517static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
518 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
519 expr = cleanups->getSubExpr();
520 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
521 if (impcast->getCastKind() != CK_IntegralCast) break;
522 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000523 }
524 return expr->getType();
525}
526
John McCall60d7b3a2010-08-24 06:29:42 +0000527StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000528Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000529 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000530 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000531
Douglas Gregor586596f2010-05-06 17:25:47 +0000532 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000533 if (CondVar) {
534 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000535 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
536 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000537 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000538
John McCall9ae2f072010-08-23 23:25:46 +0000539 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000540 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000541
John McCall9ae2f072010-08-23 23:25:46 +0000542 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000543 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Douglas Gregorab41fe92012-05-04 22:38:52 +0000545 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
546 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000547
Douglas Gregorab41fe92012-05-04 22:38:52 +0000548 public:
549 SwitchConvertDiagnoser(Expr *Cond)
550 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000551
Douglas Gregorab41fe92012-05-04 22:38:52 +0000552 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
553 QualType T) {
554 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
555 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000556
Douglas Gregorab41fe92012-05-04 22:38:52 +0000557 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
558 QualType T) {
559 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
560 << T << Cond->getSourceRange();
561 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000562
Douglas Gregorab41fe92012-05-04 22:38:52 +0000563 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
564 QualType T,
565 QualType ConvTy) {
566 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
567 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000568
Douglas Gregorab41fe92012-05-04 22:38:52 +0000569 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
570 QualType ConvTy) {
571 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
572 << ConvTy->isEnumeralType() << ConvTy;
573 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000574
Douglas Gregorab41fe92012-05-04 22:38:52 +0000575 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
576 QualType T) {
577 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
578 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000579
Douglas Gregorab41fe92012-05-04 22:38:52 +0000580 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
581 QualType ConvTy) {
582 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
583 << ConvTy->isEnumeralType() << ConvTy;
584 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000585
Douglas Gregorab41fe92012-05-04 22:38:52 +0000586 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
587 QualType T,
588 QualType ConvTy) {
589 return DiagnosticBuilder::getEmpty();
590 }
591 } SwitchDiagnoser(Cond);
592
John McCall9ae2f072010-08-23 23:25:46 +0000593 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000594 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000595 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000596 if (CondResult.isInvalid()) return StmtError();
597 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
John McCalla8e0cd82011-08-06 07:30:58 +0000599 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
600 CondResult = UsualUnaryConversions(Cond);
601 if (CondResult.isInvalid()) return StmtError();
602 Cond = CondResult.take();
603
John McCalld226f652010-08-21 09:40:31 +0000604 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000605 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000606 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000607 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000608 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000609 }
John McCallb60a77e2010-08-01 00:26:45 +0000610
John McCall781472f2010-08-25 08:40:02 +0000611 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000612
John McCall9ae2f072010-08-23 23:25:46 +0000613 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000614 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000615 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000616}
617
Gabor Greif28164ab2010-10-01 22:05:14 +0000618static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
619 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000620 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000621 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000622 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000623 Val.setIsSigned(IsSigned);
624}
625
John McCall60d7b3a2010-08-24 06:29:42 +0000626StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000627Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
628 Stmt *BodyStmt) {
629 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000630 assert(SS == getCurFunction()->SwitchStack.back() &&
631 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000632
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000633 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000634 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000635
Chris Lattnerf4021e72007-08-23 05:46:52 +0000636 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000637 if (!CondExpr) return StmtError();
638
639 QualType CondType = CondExpr->getType();
640
John McCall0fb97082010-05-18 03:19:21 +0000641 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000642 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000643 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000644
Chris Lattner5f048812009-10-16 16:45:22 +0000645 // C++ 6.4.2.p2:
646 // Integral promotions are performed (on the switch condition).
647 //
648 // A case value unrepresentable by the original switch condition
649 // type (before the promotion) doesn't make sense, even when it can
650 // be represented by the promoted type. Therefore we need to find
651 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000652 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000653 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000655 // appropriate type now, just return an error.
656 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000657 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000658
Chris Lattner2b334bb2010-04-16 23:34:13 +0000659 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000660 // switch(bool_expr) {...} is often a programmer error, e.g.
661 // switch(n && mask) { ... } // Doh - should be "n & mask".
662 // One can always use an if statement instead of switch(bool_expr).
663 Diag(SwitchLoc, diag::warn_bool_switch_condition)
664 << CondExpr->getSourceRange();
665 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000666 }
Sebastian Redlde307472009-01-11 00:38:46 +0000667
Chris Lattnerf4021e72007-08-23 05:46:52 +0000668 // Get the bitwidth of the switched-on value before promotions. We must
669 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000670 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000671 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000672 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000673 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000674 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000675 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattnerf4021e72007-08-23 05:46:52 +0000677 // Accumulate all of the case values in a vector so that we can sort them
678 // and detect duplicates. This vector contains the APInt for the case after
679 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000680 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000681 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattnerf4021e72007-08-23 05:46:52 +0000683 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000684 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
685 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Chris Lattnerf4021e72007-08-23 05:46:52 +0000687 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000689 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Douglas Gregordbb26db2009-05-15 23:57:33 +0000691 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000692 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000694 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000695 if (TheDefaultStmt) {
696 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000697 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000698
Chris Lattnerf4021e72007-08-23 05:46:52 +0000699 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000700 // we'll return a valid AST. This requires recursing down the AST and
701 // finding it, not something we are set up to do right now. For now,
702 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000703 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000704 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000705 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnerf4021e72007-08-23 05:46:52 +0000707 } else {
708 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattner1e0a3902008-01-16 19:17:22 +0000710 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000711
712 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
713 HasDependentValue = true;
714 break;
715 }
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Richard Smith8ef7b202012-01-18 23:55:52 +0000717 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Richard Smith80ad52f2013-01-02 11:42:31 +0000719 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000720 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
721 // constant expression of the promoted type of the switch condition.
722 ExprResult ConvLo =
723 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
724 if (ConvLo.isInvalid()) {
725 CaseListIsErroneous = true;
726 continue;
727 }
728 Lo = ConvLo.take();
729 } else {
730 // We already verified that the expression has a i-c-e value (C99
731 // 6.8.4.2p3) - get that value now.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000732 SmallVector<PartialDiagnosticAt, 8> Diags;
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +0000733 LoVal = Lo->EvaluateKnownConstInt(Context, &Diags);
734 if (Diags.size() == 1 &&
735 Diags[0].second.getDiagID() == diag::note_constexpr_overflow) {
Fariborz Jahanianf6e65cc2013-01-10 20:26:42 +0000736 Diag(Lo->getLocStart(), diag::warn_case_constant_overflow) <<
737 LoVal.toString(10);
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +0000738 Diag(Diags[0].first, Diags[0].second);
739 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000740
741 // If the LHS is not the same type as the condition, insert an implicit
742 // cast.
743 Lo = DefaultLvalueConversion(Lo).take();
744 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
745 }
746
747 // Convert the value to the same width/sign as the condition had prior to
748 // integral promotions.
749 //
750 // FIXME: This causes us to reject valid code:
751 // switch ((char)c) { case 256: case 0: return 0; }
752 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000753 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000754 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000755 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000756
Chris Lattner1e0a3902008-01-16 19:17:22 +0000757 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000759 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000760 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000761 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000762 CS->getRHS()->isValueDependent()) {
763 HasDependentValue = true;
764 break;
765 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000766 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000767 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000768 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000769 }
770 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000771
772 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000773 // If we don't have a default statement, check whether the
774 // condition is constant.
775 llvm::APSInt ConstantCondValue;
776 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000777 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000778 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000779 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
780 Expr::SE_AllowSideEffects);
781 assert(!HasConstantCond ||
782 (ConstantCondValue.getBitWidth() == CondWidth &&
783 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000784 }
Richard Smith80d4b552011-12-28 19:48:30 +0000785 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000786
Douglas Gregordbb26db2009-05-15 23:57:33 +0000787 // Sort all the scalar case values so we can easily detect duplicates.
788 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
789
790 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000791 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
792 if (ShouldCheckConstantCond &&
793 CaseVals[i].first == ConstantCondValue)
794 ShouldCheckConstantCond = false;
795
796 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000797 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000798 // First, determine if either case value has a name
799 StringRef PrevString, CurrString;
800 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
801 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
802 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
803 PrevString = DeclRef->getDecl()->getName();
804 }
805 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
806 CurrString = DeclRef->getDecl()->getName();
807 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000808 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000809 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000810
811 if (PrevString == CurrString)
812 Diag(CaseVals[i].second->getLHS()->getLocStart(),
813 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000814 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000815 else
816 Diag(CaseVals[i].second->getLHS()->getLocStart(),
817 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000818 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
819 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000820 CaseValStr;
821
John McCall0fb97082010-05-18 03:19:21 +0000822 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000823 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000824 // FIXME: We really want to remove the bogus case stmt from the
825 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000826 CaseListIsErroneous = true;
827 }
828 }
829 }
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Douglas Gregordbb26db2009-05-15 23:57:33 +0000831 // Detect duplicate case ranges, which usually don't exist at all in
832 // the first place.
833 if (!CaseRanges.empty()) {
834 // Sort all the case ranges by their low value so we can easily detect
835 // overlaps between ranges.
836 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Douglas Gregordbb26db2009-05-15 23:57:33 +0000838 // Scan the ranges, computing the high values and removing empty ranges.
839 std::vector<llvm::APSInt> HiVals;
840 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000841 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000842 CaseStmt *CR = CaseRanges[i].second;
843 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000844 llvm::APSInt HiVal;
845
Richard Smith80ad52f2013-01-02 11:42:31 +0000846 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000847 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
848 // constant expression of the promoted type of the switch condition.
849 ExprResult ConvHi =
850 CheckConvertedConstantExpression(Hi, CondType, HiVal,
851 CCEK_CaseValue);
852 if (ConvHi.isInvalid()) {
853 CaseListIsErroneous = true;
854 continue;
855 }
856 Hi = ConvHi.take();
857 } else {
858 HiVal = Hi->EvaluateKnownConstInt(Context);
859
860 // If the RHS is not the same type as the condition, insert an
861 // implicit cast.
862 Hi = DefaultLvalueConversion(Hi).take();
863 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
864 }
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Douglas Gregordbb26db2009-05-15 23:57:33 +0000866 // Convert the value to the same width/sign as the condition.
867 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000868 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000869 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregordbb26db2009-05-15 23:57:33 +0000871 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Douglas Gregordbb26db2009-05-15 23:57:33 +0000873 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000874 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000875 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
876 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000877 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000878 CaseRanges.erase(CaseRanges.begin()+i);
879 --i, --e;
880 continue;
881 }
John McCall0fb97082010-05-18 03:19:21 +0000882
883 if (ShouldCheckConstantCond &&
884 LoVal <= ConstantCondValue &&
885 ConstantCondValue <= HiVal)
886 ShouldCheckConstantCond = false;
887
Douglas Gregordbb26db2009-05-15 23:57:33 +0000888 HiVals.push_back(HiVal);
889 }
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Douglas Gregordbb26db2009-05-15 23:57:33 +0000891 // Rescan the ranges, looking for overlap with singleton values and other
892 // ranges. Since the range list is sorted, we only need to compare case
893 // ranges with their neighbors.
894 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
895 llvm::APSInt &CRLo = CaseRanges[i].first;
896 llvm::APSInt &CRHi = HiVals[i];
897 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Douglas Gregordbb26db2009-05-15 23:57:33 +0000899 // Check to see whether the case range overlaps with any
900 // singleton cases.
901 CaseStmt *OverlapStmt = 0;
902 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Douglas Gregordbb26db2009-05-15 23:57:33 +0000904 // Find the smallest value >= the lower bound. If I is in the
905 // case range, then we have overlap.
906 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
907 CaseVals.end(), CRLo,
908 CaseCompareFunctor());
909 if (I != CaseVals.end() && I->first < CRHi) {
910 OverlapVal = I->first; // Found overlap with scalar.
911 OverlapStmt = I->second;
912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Douglas Gregordbb26db2009-05-15 23:57:33 +0000914 // Find the smallest value bigger than the upper bound.
915 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
916 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
917 OverlapVal = (I-1)->first; // Found overlap with scalar.
918 OverlapStmt = (I-1)->second;
919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Douglas Gregordbb26db2009-05-15 23:57:33 +0000921 // Check to see if this case stmt overlaps with the subsequent
922 // case range.
923 if (i && CRLo <= HiVals[i-1]) {
924 OverlapVal = HiVals[i-1]; // Found overlap with range.
925 OverlapStmt = CaseRanges[i-1].second;
926 }
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregordbb26db2009-05-15 23:57:33 +0000928 if (OverlapStmt) {
929 // If we have a duplicate, report it.
930 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
931 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000932 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000933 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000934 // FIXME: We really want to remove the bogus case stmt from the
935 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000936 CaseListIsErroneous = true;
937 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000938 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000939 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000940
John McCall0fb97082010-05-18 03:19:21 +0000941 // Complain if we have a constant condition and we didn't find a match.
942 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
943 // TODO: it would be nice if we printed enums as enums, chars as
944 // chars, etc.
945 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
946 << ConstantCondValue.toString(10)
947 << CondExpr->getSourceRange();
948 }
949
950 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000951 // values. We only issue a warning if there is not 'default:', but
952 // we still do the analysis to preserve this information in the AST
953 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000954 //
Chris Lattnerce784612010-09-16 17:09:42 +0000955 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000956
Douglas Gregorba915af2010-02-08 22:24:16 +0000957 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000958 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000959 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000960 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000961 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000962 EnumValsTy EnumVals;
963
John McCall0fb97082010-05-18 03:19:21 +0000964 // Gather all enum values, set their type and sort them,
965 // allowing easier comparison with CaseVals.
966 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000967 EDI != ED->enumerator_end(); ++EDI) {
968 llvm::APSInt Val = EDI->getInitVal();
969 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000970 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000971 }
972 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000973 EnumValsTy::iterator EIend =
974 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000975
976 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000977 EnumValsTy::const_iterator EI = EnumVals.begin();
978 for (CaseValsTy::const_iterator CI = CaseVals.begin();
979 CI != CaseVals.end(); CI++) {
980 while (EI != EIend && EI->first < CI->first)
981 EI++;
982 if (EI == EIend || EI->first > CI->first)
983 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000984 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000985 }
986 // See which of case ranges aren't in enum
987 EI = EnumVals.begin();
988 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
989 RI != CaseRanges.end() && EI != EIend; RI++) {
990 while (EI != EIend && EI->first < RI->first)
991 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000992
David Blaikie93667502012-01-22 02:31:55 +0000993 if (EI == EIend || EI->first != RI->first) {
994 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000995 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000996 }
David Blaikie93667502012-01-22 02:31:55 +0000997
Chad Rosier1093f492012-08-10 17:56:09 +0000998 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +0000999 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1000 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1001 while (EI != EIend && EI->first < Hi)
1002 EI++;
1003 if (EI == EIend || EI->first != Hi)
1004 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001005 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001006 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Ted Kremenek559fb552010-09-09 00:05:53 +00001008 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001009 CaseValsTy::const_iterator CI = CaseVals.begin();
1010 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001011 bool hasCasesNotInSwitch = false;
1012
Chris Lattner5f9e2722011-07-23 10:55:15 +00001013 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001014
David Blaikie93667502012-01-22 02:31:55 +00001015 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001016 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001017 llvm::APSInt CIVal;
1018 while (CI != CaseVals.end() && CI->first < EI->first)
1019 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001020
Douglas Gregorba915af2010-02-08 22:24:16 +00001021 if (CI != CaseVals.end() && CI->first == EI->first)
1022 continue;
1023
Ted Kremenek559fb552010-09-09 00:05:53 +00001024 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001025 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001026 llvm::APSInt Hi =
1027 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001028 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001029 if (EI->first <= Hi)
1030 break;
1031 }
1032
Ted Kremenek559fb552010-09-09 00:05:53 +00001033 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001034 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001035 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001036 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001037 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001038
David Blaikie585d7792012-01-23 04:46:12 +00001039 if (TheDefaultStmt && UnhandledNames.empty())
1040 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001041
Chris Lattnerce784612010-09-16 17:09:42 +00001042 // Produce a nice diagnostic if multiple values aren't handled.
1043 switch (UnhandledNames.size()) {
1044 case 0: break;
1045 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001046 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001047 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001048 << UnhandledNames[0];
1049 break;
1050 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001051 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001052 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001053 << UnhandledNames[0] << UnhandledNames[1];
1054 break;
1055 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001056 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1057 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001058 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1059 break;
1060 default:
David Blaikie585d7792012-01-23 04:46:12 +00001061 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1062 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001063 << (unsigned)UnhandledNames.size()
1064 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1065 break;
1066 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001067
1068 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001069 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001070 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001071 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001072
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001073 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1074 diag::warn_empty_switch_body);
1075
Mike Stump390b4cc2009-05-16 07:39:55 +00001076 // FIXME: If the case list was broken is some way, we don't have a good system
1077 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001078 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001079 return StmtError();
1080
Sebastian Redlde307472009-01-11 00:38:46 +00001081 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001082}
1083
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001084void
1085Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1086 Expr *SrcExpr) {
1087 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001088 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001089 == DiagnosticsEngine::Ignored)
1090 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001091
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001092 if (const EnumType *ET = DstType->getAs<EnumType>())
1093 if (!Context.hasSameType(SrcType, DstType) &&
1094 SrcType->isIntegerType()) {
1095 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1096 SrcExpr->isIntegerConstantExpr(Context)) {
1097 // Get the bitwidth of the enum value before promotions.
1098 unsigned DstWith = Context.getIntWidth(DstType);
1099 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1100
1101 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1102 const EnumDecl *ED = ET->getDecl();
1103 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1104 EnumValsTy;
1105 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001106
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001107 // Gather all enum values, set their type and sort them,
1108 // allowing easier comparison with rhs constant.
1109 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1110 EDI != ED->enumerator_end(); ++EDI) {
1111 llvm::APSInt Val = EDI->getInitVal();
1112 AdjustAPSInt(Val, DstWith, DstIsSigned);
1113 EnumVals.push_back(std::make_pair(Val, *EDI));
1114 }
1115 if (EnumVals.empty())
1116 return;
1117 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1118 EnumValsTy::iterator EIend =
1119 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001120
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001121 // See which case values aren't in enum.
1122 EnumValsTy::const_iterator EI = EnumVals.begin();
1123 while (EI != EIend && EI->first < RhsVal)
1124 EI++;
1125 if (EI == EIend || EI->first != RhsVal) {
1126 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1127 << DstType;
1128 }
1129 }
1130 }
1131}
1132
John McCall60d7b3a2010-08-24 06:29:42 +00001133StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001134Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001135 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001136 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001137
Douglas Gregor5656e142009-11-24 21:15:44 +00001138 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001139 if (CondVar) {
1140 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001141 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001142 if (CondResult.isInvalid())
1143 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001144 }
John McCall9ae2f072010-08-23 23:25:46 +00001145 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001146 if (!ConditionExpr)
1147 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001148
John McCall9ae2f072010-08-23 23:25:46 +00001149 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001151 if (isa<NullStmt>(Body))
1152 getCurCompoundScope().setHasEmptyLoopBodies();
1153
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001154 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001155 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001156}
1157
John McCall60d7b3a2010-08-24 06:29:42 +00001158StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001159Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001160 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001161 Expr *Cond, SourceLocation CondRParen) {
1162 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001163
John Wiegley429bb272011-04-08 18:41:53 +00001164 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001165 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001166 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001167 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001168
Richard Smith41956372013-01-14 22:39:08 +00001169 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001170 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001171 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001172 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001173
John McCall9ae2f072010-08-23 23:25:46 +00001174 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001175
John McCall9ae2f072010-08-23 23:25:46 +00001176 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001177}
1178
Richard Trieu694e7962012-04-30 18:01:30 +00001179namespace {
1180 // This visitor will traverse a conditional statement and store all
1181 // the evaluated decls into a vector. Simple is set to true if none
1182 // of the excluded constructs are used.
1183 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1184 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001185 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001186 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001187public:
1188 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1189
1190 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001191 SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001192 Inherited(S.Context),
1193 Decls(Decls),
1194 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001195 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001196
1197 bool isSimple() { return Simple; }
1198
1199 // Replaces the method in EvaluatedExprVisitor.
1200 void VisitMemberExpr(MemberExpr* E) {
1201 Simple = false;
1202 }
1203
1204 // Any Stmt not whitelisted will cause the condition to be marked complex.
1205 void VisitStmt(Stmt *S) {
1206 Simple = false;
1207 }
1208
1209 void VisitBinaryOperator(BinaryOperator *E) {
1210 Visit(E->getLHS());
1211 Visit(E->getRHS());
1212 }
1213
1214 void VisitCastExpr(CastExpr *E) {
1215 Visit(E->getSubExpr());
1216 }
1217
1218 void VisitUnaryOperator(UnaryOperator *E) {
1219 // Skip checking conditionals with derefernces.
1220 if (E->getOpcode() == UO_Deref)
1221 Simple = false;
1222 else
1223 Visit(E->getSubExpr());
1224 }
1225
1226 void VisitConditionalOperator(ConditionalOperator *E) {
1227 Visit(E->getCond());
1228 Visit(E->getTrueExpr());
1229 Visit(E->getFalseExpr());
1230 }
1231
1232 void VisitParenExpr(ParenExpr *E) {
1233 Visit(E->getSubExpr());
1234 }
1235
1236 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1237 Visit(E->getOpaqueValue()->getSourceExpr());
1238 Visit(E->getFalseExpr());
1239 }
1240
1241 void VisitIntegerLiteral(IntegerLiteral *E) { }
1242 void VisitFloatingLiteral(FloatingLiteral *E) { }
1243 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1244 void VisitCharacterLiteral(CharacterLiteral *E) { }
1245 void VisitGNUNullExpr(GNUNullExpr *E) { }
1246 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1247
1248 void VisitDeclRefExpr(DeclRefExpr *E) {
1249 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1250 if (!VD) return;
1251
1252 Ranges.push_back(E->getSourceRange());
1253
1254 Decls.insert(VD);
1255 }
1256
1257 }; // end class DeclExtractor
1258
1259 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001260 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001261 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1262 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1263 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001264
1265public:
1266 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1267
1268 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1269 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1270 if (!Statement) return;
1271
1272 Visit(Statement);
1273 }
1274
1275 void VisitReturnStmt(ReturnStmt *S) {
1276 FoundDecl = true;
1277 }
1278
1279 void VisitBreakStmt(BreakStmt *S) {
1280 FoundDecl = true;
1281 }
1282
1283 void VisitGotoStmt(GotoStmt *S) {
1284 FoundDecl = true;
1285 }
1286
1287 void VisitCastExpr(CastExpr *E) {
1288 if (E->getCastKind() == CK_LValueToRValue)
1289 CheckLValueToRValueCast(E->getSubExpr());
1290 else
1291 Visit(E->getSubExpr());
1292 }
1293
1294 void CheckLValueToRValueCast(Expr *E) {
1295 E = E->IgnoreParenImpCasts();
1296
1297 if (isa<DeclRefExpr>(E)) {
1298 return;
1299 }
1300
1301 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1302 Visit(CO->getCond());
1303 CheckLValueToRValueCast(CO->getTrueExpr());
1304 CheckLValueToRValueCast(CO->getFalseExpr());
1305 return;
1306 }
1307
1308 if (BinaryConditionalOperator *BCO =
1309 dyn_cast<BinaryConditionalOperator>(E)) {
1310 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1311 CheckLValueToRValueCast(BCO->getFalseExpr());
1312 return;
1313 }
1314
1315 Visit(E);
1316 }
1317
1318 void VisitDeclRefExpr(DeclRefExpr *E) {
1319 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1320 if (Decls.count(VD))
1321 FoundDecl = true;
1322 }
1323
1324 bool FoundDeclInUse() { return FoundDecl; }
1325
1326 }; // end class DeclMatcher
1327
1328 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1329 Expr *Third, Stmt *Body) {
1330 // Condition is empty
1331 if (!Second) return;
1332
1333 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1334 Second->getLocStart())
1335 == DiagnosticsEngine::Ignored)
1336 return;
1337
1338 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1339 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001340 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001341 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001342 DE.Visit(Second);
1343
1344 // Don't analyze complex conditionals.
1345 if (!DE.isSimple()) return;
1346
1347 // No decls found.
1348 if (Decls.size() == 0) return;
1349
Richard Trieu90875992012-05-04 03:01:54 +00001350 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001351 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1352 E = Decls.end();
1353 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001354 if ((*I)->getType().isVolatileQualified() ||
1355 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001356
1357 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1358 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1359 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1360 return;
1361
1362 // Load decl names into diagnostic.
1363 if (Decls.size() > 4)
1364 PDiag << 0;
1365 else {
1366 PDiag << Decls.size();
1367 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1368 E = Decls.end();
1369 I != E; ++I)
1370 PDiag << (*I)->getDeclName();
1371 }
1372
1373 // Load SourceRanges into diagnostic if there is room.
1374 // Otherwise, load the SourceRange of the conditional expression.
1375 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001376 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1377 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001378 I != E; ++I)
1379 PDiag << *I;
1380 else
1381 PDiag << Second->getSourceRange();
1382
1383 S.Diag(Ranges.begin()->getBegin(), PDiag);
1384 }
1385
1386} // end namespace
1387
John McCall60d7b3a2010-08-24 06:29:42 +00001388StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001389Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001390 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001391 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001392 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001393 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001394 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001395 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1396 // declare identifiers for objects having storage class 'auto' or
1397 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001398 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1399 DI!=DE; ++DI) {
1400 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001401 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001402 VD = 0;
1403 if (VD == 0)
1404 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1405 // FIXME: mark decl erroneous!
1406 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001407 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001409
Richard Trieu694e7962012-04-30 18:01:30 +00001410 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1411
John McCall60d7b3a2010-08-24 06:29:42 +00001412 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001413 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001414 if (secondVar) {
1415 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001416 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001417 if (SecondResult.isInvalid())
1418 return StmtError();
1419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001420
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001421 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001422
Anders Carlsson3af708f2009-08-01 01:39:59 +00001423 DiagnoseUnusedExprResult(First);
1424 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001425 DiagnoseUnusedExprResult(Body);
1426
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001427 if (isa<NullStmt>(Body))
1428 getCurCompoundScope().setHasEmptyLoopBodies();
1429
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001430 return Owned(new (Context) ForStmt(Context, First,
1431 SecondResult.take(), ConditionVar,
1432 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001433 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001434}
1435
John McCallf6a16482010-12-04 03:47:34 +00001436/// In an Objective C collection iteration statement:
1437/// for (x in y)
1438/// x can be an arbitrary l-value expression. Bind it up as a
1439/// full-expression.
1440StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001441 // Reduce placeholder expressions here. Note that this rejects the
1442 // use of pseudo-object l-values in this position.
1443 ExprResult result = CheckPlaceholderExpr(E);
1444 if (result.isInvalid()) return StmtError();
1445 E = result.take();
1446
Richard Smith41956372013-01-14 22:39:08 +00001447 ExprResult FullExpr = ActOnFinishFullExpr(E);
1448 if (FullExpr.isInvalid())
1449 return StmtError();
1450 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001451}
1452
John McCall990567c2011-07-27 01:07:15 +00001453ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001454Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1455 if (!collection)
1456 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001457
John McCall990567c2011-07-27 01:07:15 +00001458 // Bail out early if we've got a type-dependent expression.
1459 if (collection->isTypeDependent()) return Owned(collection);
1460
1461 // Perform normal l-value conversion.
1462 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1463 if (result.isInvalid())
1464 return ExprError();
1465 collection = result.take();
1466
1467 // The operand needs to have object-pointer type.
1468 // TODO: should we do a contextual conversion?
1469 const ObjCObjectPointerType *pointerType =
1470 collection->getType()->getAs<ObjCObjectPointerType>();
1471 if (!pointerType)
1472 return Diag(forLoc, diag::err_collection_expr_type)
1473 << collection->getType() << collection->getSourceRange();
1474
1475 // Check that the operand provides
1476 // - countByEnumeratingWithState:objects:count:
1477 const ObjCObjectType *objectType = pointerType->getObjectType();
1478 ObjCInterfaceDecl *iface = objectType->getInterface();
1479
1480 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001481 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001482 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001483 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001484 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001485 ? diag::err_arc_collection_forward
1486 : 0,
1487 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001488 // Otherwise, if we have any useful type information, check that
1489 // the type declares the appropriate method.
1490 } else if (iface || !objectType->qual_empty()) {
1491 IdentifierInfo *selectorIdents[] = {
1492 &Context.Idents.get("countByEnumeratingWithState"),
1493 &Context.Idents.get("objects"),
1494 &Context.Idents.get("count")
1495 };
1496 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1497
1498 ObjCMethodDecl *method = 0;
1499
1500 // If there's an interface, look in both the public and private APIs.
1501 if (iface) {
1502 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001503 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001504 }
1505
1506 // Also check protocol qualifiers.
1507 if (!method)
1508 method = LookupMethodInQualifiedType(selector, pointerType,
1509 /*instance*/ true);
1510
1511 // If we didn't find it anywhere, give up.
1512 if (!method) {
1513 Diag(forLoc, diag::warn_collection_expr_type)
1514 << collection->getType() << selector << collection->getSourceRange();
1515 }
1516
1517 // TODO: check for an incompatible signature?
1518 }
1519
1520 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001521 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001522}
1523
John McCall60d7b3a2010-08-24 06:29:42 +00001524StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001525Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001526 Stmt *First, Expr *collection,
1527 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001528
1529 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001530 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001531
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001532 if (First) {
1533 QualType FirstType;
1534 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001535 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001536 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1537 diag::err_toomany_element_decls));
1538
John McCallf85e1932011-06-15 23:02:42 +00001539 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1540 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001541 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1542 // declare identifiers for objects having storage class 'auto' or
1543 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001544 if (!D->hasLocalStorage())
1545 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001546 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001547 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001548 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001549 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001550 return StmtError(Diag(First->getLocStart(),
1551 diag::err_selector_element_not_lvalue)
1552 << First->getSourceRange());
1553
Mike Stump1eb44332009-09-09 15:08:12 +00001554 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001555 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001556 if (!FirstType->isDependentType() &&
1557 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001558 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001559 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1560 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001561 }
Chad Rosier1093f492012-08-10 17:56:09 +00001562
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001563 if (CollectionExprResult.isInvalid())
1564 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001565
Richard Smith41956372013-01-14 22:39:08 +00001566 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1567 if (CollectionExprResult.isInvalid())
1568 return StmtError();
1569
Chad Rosier1093f492012-08-10 17:56:09 +00001570 return Owned(new (Context) ObjCForCollectionStmt(First,
1571 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001572 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001573}
Reid Spencer5f016e22007-07-11 17:01:13 +00001574
Richard Smithad762fc2011-04-14 22:09:26 +00001575/// Finish building a variable declaration for a for-range statement.
1576/// \return true if an error occurs.
1577static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1578 SourceLocation Loc, int diag) {
1579 // Deduce the type for the iterator variable now rather than leaving it to
1580 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1581 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001582 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001583 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1584 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001585 SemaRef.Diag(Loc, diag) << Init->getType();
1586 if (!InitTSI) {
1587 Decl->setInvalidDecl();
1588 return true;
1589 }
1590 Decl->setTypeSourceInfo(InitTSI);
1591 Decl->setType(InitTSI->getType());
1592
John McCallf85e1932011-06-15 23:02:42 +00001593 // In ARC, infer lifetime.
1594 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1595 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001596 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001597 SemaRef.inferObjCARCLifetime(Decl))
1598 Decl->setInvalidDecl();
1599
Richard Smithad762fc2011-04-14 22:09:26 +00001600 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1601 /*TypeMayContainAuto=*/false);
1602 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001603 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001604 return false;
1605}
1606
Sam Panzere1715b62012-08-21 00:52:01 +00001607namespace {
1608
Richard Smithad762fc2011-04-14 22:09:26 +00001609/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001610/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001611/// nor from the diagnostics produced when analysing the implicit expressions
1612/// required in a for-range statement.
1613void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001614 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001615 CallExpr *CE = dyn_cast<CallExpr>(E);
1616 if (!CE)
1617 return;
1618 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1619 if (!D)
1620 return;
1621 SourceLocation Loc = D->getLocation();
1622
1623 std::string Description;
1624 bool IsTemplate = false;
1625 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1626 Description = SemaRef.getTemplateArgumentBindingsText(
1627 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1628 IsTemplate = true;
1629 }
1630
1631 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1632 << BEF << IsTemplate << Description << E->getType();
1633}
1634
Sam Panzere1715b62012-08-21 00:52:01 +00001635/// Build a variable declaration for a for-range statement.
1636VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1637 QualType Type, const char *Name) {
1638 DeclContext *DC = SemaRef.CurContext;
1639 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1640 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1641 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1642 TInfo, SC_Auto, SC_None);
1643 Decl->setImplicit();
1644 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001645}
1646
1647}
1648
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001649static bool ObjCEnumerationCollection(Expr *Collection) {
1650 return !Collection->isTypeDependent()
1651 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1652}
1653
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001654/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001655///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001656/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001657/// A range-based for statement is equivalent to
1658///
1659/// {
1660/// auto && __range = range-init;
1661/// for ( auto __begin = begin-expr,
1662/// __end = end-expr;
1663/// __begin != __end;
1664/// ++__begin ) {
1665/// for-range-declaration = *__begin;
1666/// statement
1667/// }
1668/// }
1669///
1670/// The body of the loop is not available yet, since it cannot be analysed until
1671/// we have determined the type of the for-range-declaration.
1672StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001673Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001674 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001675 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001676 if (!First || !Range)
1677 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001678
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001679 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001680 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001681
1682 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1683 assert(DS && "first part of for range not a decl stmt");
1684
1685 if (!DS->isSingleDecl()) {
1686 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1687 return StmtError();
1688 }
1689 if (DS->getSingleDecl()->isInvalidDecl())
1690 return StmtError();
1691
1692 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1693 return StmtError();
1694
1695 // Build auto && __range = range-init
1696 SourceLocation RangeLoc = Range->getLocStart();
1697 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1698 Context.getAutoRRefDeductType(),
1699 "__range");
1700 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1701 diag::err_for_range_deduction_failure))
1702 return StmtError();
1703
1704 // Claim the type doesn't contain auto: we've already done the checking.
1705 DeclGroupPtrTy RangeGroup =
1706 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1707 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1708 if (RangeDecl.isInvalid())
1709 return StmtError();
1710
1711 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1712 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001713 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001714}
1715
1716/// \brief Create the initialization, compare, and increment steps for
1717/// the range-based for loop expression.
1718/// This function does not handle array-based for loops,
1719/// which are created in Sema::BuildCXXForRangeStmt.
1720///
1721/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1722/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1723/// CandidateSet and BEF are set and some non-success value is returned on
1724/// failure.
1725static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1726 Expr *BeginRange, Expr *EndRange,
1727 QualType RangeType,
1728 VarDecl *BeginVar,
1729 VarDecl *EndVar,
1730 SourceLocation ColonLoc,
1731 OverloadCandidateSet *CandidateSet,
1732 ExprResult *BeginExpr,
1733 ExprResult *EndExpr,
1734 Sema::BeginEndFunction *BEF) {
1735 DeclarationNameInfo BeginNameInfo(
1736 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1737 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1738 ColonLoc);
1739
1740 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1741 Sema::LookupMemberName);
1742 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1743
1744 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1745 // - if _RangeT is a class type, the unqualified-ids begin and end are
1746 // looked up in the scope of class _RangeT as if by class member access
1747 // lookup (3.4.5), and if either (or both) finds at least one
1748 // declaration, begin-expr and end-expr are __range.begin() and
1749 // __range.end(), respectively;
1750 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1751 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1752
1753 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1754 SourceLocation RangeLoc = BeginVar->getLocation();
1755 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1756
1757 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1758 << RangeLoc << BeginRange->getType() << *BEF;
1759 return Sema::FRS_DiagnosticIssued;
1760 }
1761 } else {
1762 // - otherwise, begin-expr and end-expr are begin(__range) and
1763 // end(__range), respectively, where begin and end are looked up with
1764 // argument-dependent lookup (3.4.2). For the purposes of this name
1765 // lookup, namespace std is an associated namespace.
1766
1767 }
1768
1769 *BEF = Sema::BEF_begin;
1770 Sema::ForRangeStatus RangeStatus =
1771 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1772 Sema::BEF_begin, BeginNameInfo,
1773 BeginMemberLookup, CandidateSet,
1774 BeginRange, BeginExpr);
1775
1776 if (RangeStatus != Sema::FRS_Success)
1777 return RangeStatus;
1778 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1779 diag::err_for_range_iter_deduction_failure)) {
1780 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1781 return Sema::FRS_DiagnosticIssued;
1782 }
1783
1784 *BEF = Sema::BEF_end;
1785 RangeStatus =
1786 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1787 Sema::BEF_end, EndNameInfo,
1788 EndMemberLookup, CandidateSet,
1789 EndRange, EndExpr);
1790 if (RangeStatus != Sema::FRS_Success)
1791 return RangeStatus;
1792 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1793 diag::err_for_range_iter_deduction_failure)) {
1794 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1795 return Sema::FRS_DiagnosticIssued;
1796 }
1797 return Sema::FRS_Success;
1798}
1799
1800/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001801/// If the attempt fails, this function will return a valid, null StmtResult
1802/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001803static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1804 SourceLocation ForLoc,
1805 Stmt *LoopVarDecl,
1806 SourceLocation ColonLoc,
1807 Expr *Range,
1808 SourceLocation RangeLoc,
1809 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001810 // Determine whether we can rebuild the for-range statement with a
1811 // dereferenced range expression.
1812 ExprResult AdjustedRange;
1813 {
1814 Sema::SFINAETrap Trap(SemaRef);
1815
1816 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1817 if (AdjustedRange.isInvalid())
1818 return StmtResult();
1819
1820 StmtResult SR =
1821 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1822 AdjustedRange.get(), RParenLoc,
1823 Sema::BFRK_Check);
1824 if (SR.isInvalid())
1825 return StmtResult();
1826 }
1827
1828 // The attempt to dereference worked well enough that it could produce a valid
1829 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1830 // case there are any other (non-fatal) problems with it.
1831 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1832 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1833 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1834 AdjustedRange.get(), RParenLoc,
1835 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001836}
1837
Richard Smith8b533d92012-09-20 21:52:32 +00001838/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001839StmtResult
1840Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1841 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1842 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001843 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001844 Scope *S = getCurScope();
1845
1846 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1847 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1848 QualType RangeVarType = RangeVar->getType();
1849
1850 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1851 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1852
1853 StmtResult BeginEndDecl = BeginEnd;
1854 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1855
1856 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1857 SourceLocation RangeLoc = RangeVar->getLocation();
1858
Ted Kremeneke50b0152011-10-10 22:36:28 +00001859 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1860
1861 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1862 VK_LValue, ColonLoc);
1863 if (BeginRangeRef.isInvalid())
1864 return StmtError();
1865
1866 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1867 VK_LValue, ColonLoc);
1868 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001869 return StmtError();
1870
1871 QualType AutoType = Context.getAutoDeductType();
1872 Expr *Range = RangeVar->getInit();
1873 if (!Range)
1874 return StmtError();
1875 QualType RangeType = Range->getType();
1876
1877 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001878 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001879 return StmtError();
1880
1881 // Build auto __begin = begin-expr, __end = end-expr.
1882 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1883 "__begin");
1884 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1885 "__end");
1886
1887 // Build begin-expr and end-expr and attach to __begin and __end variables.
1888 ExprResult BeginExpr, EndExpr;
1889 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1890 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1891 // __range + __bound, respectively, where __bound is the array bound. If
1892 // _RangeT is an array of unknown size or an array of incomplete type,
1893 // the program is ill-formed;
1894
1895 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001896 BeginExpr = BeginRangeRef;
1897 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001898 diag::err_for_range_iter_deduction_failure)) {
1899 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1900 return StmtError();
1901 }
1902
1903 // Find the array bound.
1904 ExprResult BoundExpr;
1905 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1906 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001907 Context.getPointerDiffType(),
1908 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001909 else if (const VariableArrayType *VAT =
1910 dyn_cast<VariableArrayType>(UnqAT))
1911 BoundExpr = VAT->getSizeExpr();
1912 else {
1913 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1914 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001915 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001916 }
1917
1918 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001919 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001920 BoundExpr.get());
1921 if (EndExpr.isInvalid())
1922 return StmtError();
1923 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1924 diag::err_for_range_iter_deduction_failure)) {
1925 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1926 return StmtError();
1927 }
1928 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001929 OverloadCandidateSet CandidateSet(RangeLoc);
1930 Sema::BeginEndFunction BEFFailure;
1931 ForRangeStatus RangeStatus =
1932 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1933 EndRangeRef.get(), RangeType,
1934 BeginVar, EndVar, ColonLoc, &CandidateSet,
1935 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00001936
Sam Panzere1715b62012-08-21 00:52:01 +00001937 // If building the range failed, try dereferencing the range expression
1938 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00001939 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00001940 BEFFailure == BEF_begin) {
1941 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1942 LoopVarDecl, ColonLoc,
1943 Range, RangeLoc,
1944 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00001945 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00001946 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00001947 }
1948
Sam Panzere1715b62012-08-21 00:52:01 +00001949 // Otherwise, emit diagnostics if we haven't already.
1950 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00001951 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00001952 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1953 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00001954 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00001955 }
1956 // Return an error if no fix was discovered.
1957 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00001958 return StmtError();
1959 }
1960
Sam Panzere1715b62012-08-21 00:52:01 +00001961 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1962 "invalid range expression in for loop");
1963
1964 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00001965 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1966 if (!Context.hasSameType(BeginType, EndType)) {
1967 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1968 << BeginType << EndType;
1969 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1970 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1971 }
1972
1973 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1974 // Claim the type doesn't contain auto: we've already done the checking.
1975 DeclGroupPtrTy BeginEndGroup =
1976 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1977 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1978
Ted Kremeneke50b0152011-10-10 22:36:28 +00001979 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1980 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001981 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001982 if (BeginRef.isInvalid())
1983 return StmtError();
1984
Richard Smithad762fc2011-04-14 22:09:26 +00001985 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1986 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001987 if (EndRef.isInvalid())
1988 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001989
1990 // Build and check __begin != __end expression.
1991 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1992 BeginRef.get(), EndRef.get());
1993 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1994 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1995 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00001996 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
1997 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00001998 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1999 if (!Context.hasSameType(BeginType, EndType))
2000 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2001 return StmtError();
2002 }
2003
2004 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002005 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2006 VK_LValue, ColonLoc);
2007 if (BeginRef.isInvalid())
2008 return StmtError();
2009
Richard Smithad762fc2011-04-14 22:09:26 +00002010 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2011 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2012 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002013 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2014 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002015 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2016 return StmtError();
2017 }
2018
2019 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002020 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2021 VK_LValue, ColonLoc);
2022 if (BeginRef.isInvalid())
2023 return StmtError();
2024
Richard Smithad762fc2011-04-14 22:09:26 +00002025 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2026 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002027 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2028 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002029 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2030 return StmtError();
2031 }
2032
Richard Smith8b533d92012-09-20 21:52:32 +00002033 // Attach *__begin as initializer for VD. Don't touch it if we're just
2034 // trying to determine whether this would be a valid range.
2035 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002036 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2037 /*TypeMayContainAuto=*/true);
2038 if (LoopVar->isInvalidDecl())
2039 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2040 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002041 } else {
2042 // The range is implicitly used as a placeholder when it is dependent.
2043 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002044 }
2045
Richard Smith8b533d92012-09-20 21:52:32 +00002046 // Don't bother to actually allocate the result if we're just trying to
2047 // determine whether it would be valid.
2048 if (Kind == BFRK_Check)
2049 return StmtResult();
2050
Richard Smithad762fc2011-04-14 22:09:26 +00002051 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2052 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2053 NotEqExpr.take(), IncrExpr.take(),
2054 LoopVarDS, /*Body=*/0, ForLoc,
2055 ColonLoc, RParenLoc));
2056}
2057
Chad Rosier1093f492012-08-10 17:56:09 +00002058/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002059/// statement.
2060StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2061 if (!S || !B)
2062 return StmtError();
2063 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002064
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002065 ForStmt->setBody(B);
2066 return S;
2067}
2068
Richard Smithad762fc2011-04-14 22:09:26 +00002069/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2070/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2071/// body cannot be performed until after the type of the range variable is
2072/// determined.
2073StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2074 if (!S || !B)
2075 return StmtError();
2076
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002077 if (isa<ObjCForCollectionStmt>(S))
2078 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002079
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002080 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2081 ForStmt->setBody(B);
2082
2083 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2084 diag::warn_empty_range_based_for_body);
2085
Richard Smithad762fc2011-04-14 22:09:26 +00002086 return S;
2087}
2088
Chris Lattner57ad3782011-02-17 20:34:02 +00002089StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2090 SourceLocation LabelLoc,
2091 LabelDecl *TheDecl) {
2092 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002093 TheDecl->setUsed();
2094 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002095}
2096
John McCall60d7b3a2010-08-24 06:29:42 +00002097StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002098Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002099 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002100 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002101 if (!E->isTypeDependent()) {
2102 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002103 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002104 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002105 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002106 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2107 if (ExprRes.isInvalid())
2108 return StmtError();
2109 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002110 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002111 return StmtError();
2112 }
John McCallb60a77e2010-08-01 00:26:45 +00002113
Richard Smith41956372013-01-14 22:39:08 +00002114 ExprResult ExprRes = ActOnFinishFullExpr(E);
2115 if (ExprRes.isInvalid())
2116 return StmtError();
2117 E = ExprRes.take();
2118
John McCall781472f2010-08-25 08:40:02 +00002119 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002120
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002121 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002122}
2123
John McCall60d7b3a2010-08-24 06:29:42 +00002124StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002125Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002126 Scope *S = CurScope->getContinueParent();
2127 if (!S) {
2128 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002129 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002131
Ted Kremenek8189cde2009-02-07 01:47:29 +00002132 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002133}
2134
John McCall60d7b3a2010-08-24 06:29:42 +00002135StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002136Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 Scope *S = CurScope->getBreakParent();
2138 if (!S) {
2139 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002140 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002142
Ted Kremenek8189cde2009-02-07 01:47:29 +00002143 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002144}
2145
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002147/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002148///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002149/// \param ReturnType If we're determining the copy elision candidate for
2150/// a return statement, this is the return type of the function. If we're
2151/// determining the copy elision candidate for a throw expression, this will
2152/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002153///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002154/// \param E The expression being returned from the function or block, or
2155/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002156///
Douglas Gregor4926d832011-05-20 15:00:53 +00002157/// \param AllowFunctionParameter Whether we allow function parameters to
2158/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2159/// we re-use this logic to determine whether we should try to move as part of
2160/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002161///
2162/// \returns The NRVO candidate variable, if the return statement may use the
2163/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002164const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2165 Expr *E,
2166 bool AllowFunctionParameter) {
2167 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002168 // - in a return statement in a function with ...
2169 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002170 if (!ReturnType.isNull()) {
2171 if (!ReturnType->isRecordType())
2172 return 0;
2173 // ... the same cv-unqualified type as the function return type ...
2174 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2175 return 0;
2176 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002177
2178 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002179 // (other than a function or catch-clause parameter)) ...
2180 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002181 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002182 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002183 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2184 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002185 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002186
John McCall1cd76e82011-11-11 03:57:31 +00002187 // ...object (other than a function or catch-clause parameter)...
2188 if (VD->getKind() != Decl::Var &&
2189 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2190 return 0;
2191 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002192
John McCall1cd76e82011-11-11 03:57:31 +00002193 // ...automatic...
2194 if (!VD->hasLocalStorage()) return 0;
2195
2196 // ...non-volatile...
2197 if (VD->getType().isVolatileQualified()) return 0;
2198 if (VD->getType()->isReferenceType()) return 0;
2199
2200 // __block variables can't be allocated in a way that permits NRVO.
2201 if (VD->hasAttr<BlocksAttr>()) return 0;
2202
2203 // Variables with higher required alignment than their type's ABI
2204 // alignment cannot use NRVO.
2205 if (VD->hasAttr<AlignedAttr>() &&
2206 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2207 return 0;
2208
2209 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002210}
2211
Douglas Gregor07f402c2011-01-21 21:08:57 +00002212/// \brief Perform the initialization of a potentially-movable value, which
2213/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002214///
2215/// This routine implements C++0x [class.copy]p33, which attempts to treat
2216/// returned lvalues as rvalues in certain cases (to prefer move construction),
2217/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002219Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2220 const VarDecl *NRVOCandidate,
2221 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002222 Expr *Value,
2223 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002224 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002225 // When the criteria for elision of a copy operation are met or would
2226 // be met save for the fact that the source object is a function
2227 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002228 // overload resolution to select the constructor for the copy is first
2229 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002230 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002231 if (AllowNRVO &&
2232 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002233 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002234 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002235
Douglas Gregorcc15f012011-01-21 19:38:21 +00002236 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002237 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002238 = InitializationKind::CreateCopy(Value->getLocStart(),
2239 Value->getLocStart());
2240 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002241
2242 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002243 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002244 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002245 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002246 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002247 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2248 StepEnd = Seq.step_end();
2249 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002250 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002251 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002252
2253 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002254 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002255
Douglas Gregorcc15f012011-01-21 19:38:21 +00002256 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002257 = Constructor->getParamDecl(0)->getType()
2258 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002259
Douglas Gregorcc15f012011-01-21 19:38:21 +00002260 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002261 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002262 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2263 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002264 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002265
Douglas Gregorcc15f012011-01-21 19:38:21 +00002266 // Promote "AsRvalue" to the heap, since we now need this
2267 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002268 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002269 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002270
Douglas Gregorcc15f012011-01-21 19:38:21 +00002271 // Complete type-checking the initialization of the return type
2272 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002273 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002274 }
2275 }
2276 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277
Douglas Gregorcc15f012011-01-21 19:38:21 +00002278 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002279 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002280 // (again) now with the return value expression as written.
2281 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002282 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002283
Douglas Gregorcc15f012011-01-21 19:38:21 +00002284 return Res;
2285}
2286
Eli Friedman84b007f2012-01-26 03:00:14 +00002287/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2288/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002289///
John McCall60d7b3a2010-08-24 06:29:42 +00002290StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002291Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2292 // If this is the first return we've seen, infer the return type.
2293 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2294 // rules which allows multiple return statements.
2295 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002296 QualType FnRetType = CurCap->ReturnType;
2297
2298 // For blocks/lambdas with implicit return types, we check each return
2299 // statement individually, and deduce the common return type when the block
2300 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002301 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002302 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002303 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2304 if (Result.isInvalid())
2305 return StmtError();
2306 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002307
Jordan Rose7dd900e2012-07-02 21:19:23 +00002308 if (!RetValExp->isTypeDependent())
2309 FnRetType = RetValExp->getType();
2310 else
2311 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002312 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002313 if (RetValExp) {
2314 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2315 // initializer list, because it is not an expression (even
2316 // though we represent it as one). We still deduce 'void'.
2317 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2318 << RetValExp->getSourceRange();
2319 }
2320
Jordan Rose7dd900e2012-07-02 21:19:23 +00002321 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002322 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002323
2324 // Although we'll properly infer the type of the block once it's completed,
2325 // make sure we provide a return type now for better error recovery.
2326 if (CurCap->ReturnType.isNull())
2327 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002328 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002329 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002330
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002331 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002332 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2333 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2334 return StmtError();
2335 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002336 } else {
2337 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2338 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2339 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2340 return StmtError();
2341 }
2342 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002343
Steve Naroff4eb206b2008-09-03 18:15:37 +00002344 // Otherwise, verify that this result type matches the previous one. We are
2345 // pickier with blocks than for normal functions because we don't have GCC
2346 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002347 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002348 if (FnRetType->isDependentType()) {
2349 // Delay processing for now. TODO: there are lots of dependent
2350 // types we can conclusively prove aren't void.
2351 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002352 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002353 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002354 (RetValExp->isTypeDependent() ||
2355 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002356 if (!getLangOpts().CPlusPlus &&
2357 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002358 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002359 else {
2360 Diag(ReturnLoc, diag::err_return_block_has_expr);
2361 RetValExp = 0;
2362 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002363 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002364 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002365 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2366 } else if (!RetValExp->isTypeDependent()) {
2367 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002368
John McCall0a7efe12011-08-17 22:09:46 +00002369 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2370 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2371 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002372
John McCall0a7efe12011-08-17 22:09:46 +00002373 // In C++ the return statement is handled via a copy initialization.
2374 // the C version of which boils down to CheckSingleAssignmentConstraints.
2375 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2376 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2377 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002378 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002379 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2380 FnRetType, RetValExp);
2381 if (Res.isInvalid()) {
2382 // FIXME: Cleanup temporaries here, anyway?
2383 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002384 }
John McCall0a7efe12011-08-17 22:09:46 +00002385 RetValExp = Res.take();
2386 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002387 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002388
John McCalld963c372011-08-17 21:34:14 +00002389 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002390 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2391 if (ER.isInvalid())
2392 return StmtError();
2393 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002394 }
John McCall0a7efe12011-08-17 22:09:46 +00002395 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2396 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002397
Jordan Rose7dd900e2012-07-02 21:19:23 +00002398 // If we need to check for the named return value optimization,
2399 // or if we need to infer the return type,
2400 // save the return statement in our scope for later processing.
2401 if (CurCap->HasImplicitReturnType ||
2402 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2403 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002404 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002405
Douglas Gregor5077c382010-05-15 06:01:05 +00002406 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002407}
Reid Spencer5f016e22007-07-11 17:01:13 +00002408
John McCall60d7b3a2010-08-24 06:29:42 +00002409StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002410Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002411 // Check for unexpanded parameter packs.
2412 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2413 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002414
Eli Friedman84b007f2012-01-26 03:00:14 +00002415 if (isa<CapturingScopeInfo>(getCurFunction()))
2416 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002417
Chris Lattner371f2582008-12-04 23:50:19 +00002418 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002419 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002420 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002421 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00002422 if (FD->hasAttr<NoReturnAttr>() ||
2423 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00002424 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002425 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002426 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002427 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002428 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2429 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002430 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002431 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002432 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2433 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002434 }
2435 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002436 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Douglas Gregor5077c382010-05-15 06:01:05 +00002438 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002439 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002440 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002441 if (isa<InitListExpr>(RetValExp)) {
2442 // We simply never allow init lists as the return value of void
2443 // functions. This is compatible because this was never allowed before,
2444 // so there's no legacy code to deal with.
2445 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2446 int FunctionKind = 0;
2447 if (isa<ObjCMethodDecl>(CurDecl))
2448 FunctionKind = 1;
2449 else if (isa<CXXConstructorDecl>(CurDecl))
2450 FunctionKind = 2;
2451 else if (isa<CXXDestructorDecl>(CurDecl))
2452 FunctionKind = 3;
2453
2454 Diag(ReturnLoc, diag::err_return_init_list)
2455 << CurDecl->getDeclName() << FunctionKind
2456 << RetValExp->getSourceRange();
2457
2458 // Drop the expression.
2459 RetValExp = 0;
2460 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002461 // C99 6.8.6.4p1 (ext_ since GCC warns)
2462 unsigned D = diag::ext_return_has_expr;
2463 if (RetValExp->getType()->isVoidType())
2464 D = diag::ext_return_has_void_expr;
2465 else {
2466 ExprResult Result = Owned(RetValExp);
2467 Result = IgnoredValueConversions(Result.take());
2468 if (Result.isInvalid())
2469 return StmtError();
2470 RetValExp = Result.take();
2471 RetValExp = ImpCastExprToType(RetValExp,
2472 Context.VoidTy, CK_ToVoid).take();
2473 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002474
Nick Lewycky8d794612011-06-01 07:44:31 +00002475 // return (some void expression); is legal in C++.
2476 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002477 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002478 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002479
2480 int FunctionKind = 0;
2481 if (isa<ObjCMethodDecl>(CurDecl))
2482 FunctionKind = 1;
2483 else if (isa<CXXConstructorDecl>(CurDecl))
2484 FunctionKind = 2;
2485 else if (isa<CXXDestructorDecl>(CurDecl))
2486 FunctionKind = 3;
2487
Nick Lewycky8d794612011-06-01 07:44:31 +00002488 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002489 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002490 << RetValExp->getSourceRange();
2491 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002492 }
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Sebastian Redl33deb352012-02-22 10:50:08 +00002494 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002495 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2496 if (ER.isInvalid())
2497 return StmtError();
2498 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002499 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002500 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002501
Douglas Gregor5077c382010-05-15 06:01:05 +00002502 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2503 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002504 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2505 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002506 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002507
2508 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002509 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002510 else
Chris Lattner08631c52008-11-23 21:45:46 +00002511 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002512 Result = new (Context) ReturnStmt(ReturnLoc);
2513 } else {
2514 const VarDecl *NRVOCandidate = 0;
2515 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2516 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002517
Eli Friedman38ac2432012-03-30 01:13:43 +00002518 if (!RelatedRetType.isNull()) {
2519 // If we have a related result type, perform an extra conversion here.
2520 // FIXME: The diagnostics here don't really describe what is happening.
2521 InitializedEntity Entity =
2522 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002523
Eli Friedman38ac2432012-03-30 01:13:43 +00002524 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2525 RetValExp);
2526 if (Res.isInvalid()) {
2527 // FIXME: Cleanup temporaries here, anyway?
2528 return StmtError();
2529 }
2530 RetValExp = Res.takeAs<Expr>();
2531 }
2532
Douglas Gregor5077c382010-05-15 06:01:05 +00002533 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2534 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2535 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002536
John McCall856d3792011-06-16 23:24:51 +00002537 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002538 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002539 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002540 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002541 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002542 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002543 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002544 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002545 if (Res.isInvalid()) {
2546 // FIXME: Cleanup temporaries here, anyway?
2547 return StmtError();
2548 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002549
Douglas Gregor5077c382010-05-15 06:01:05 +00002550 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002552 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002553 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002554
John McCallb4eb64d2010-10-08 02:01:28 +00002555 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002556 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2557 if (ER.isInvalid())
2558 return StmtError();
2559 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002560 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002561 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002562 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002563
2564 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002565 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002566 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002567 !CurContext->isDependentContext())
2568 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002569
Douglas Gregor5077c382010-05-15 06:01:05 +00002570 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002571}
2572
John McCall60d7b3a2010-08-24 06:29:42 +00002573StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002574Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002575 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002576 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002577 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002578 if (Var && Var->isInvalidDecl())
2579 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002580
John McCall9ae2f072010-08-23 23:25:46 +00002581 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002582}
2583
John McCall60d7b3a2010-08-24 06:29:42 +00002584StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002585Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2586 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002587}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002588
John McCall60d7b3a2010-08-24 06:29:42 +00002589StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002590Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002591 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002592 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002593 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2594
John McCall781472f2010-08-25 08:40:02 +00002595 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002596 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002597 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002598 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002599 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002600 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002601}
2602
John McCalld1376ee2012-05-08 21:41:25 +00002603StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002604 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002605 ExprResult Result = DefaultLvalueConversion(Throw);
2606 if (Result.isInvalid())
2607 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002608
Richard Smith41956372013-01-14 22:39:08 +00002609 Result = ActOnFinishFullExpr(Result.take());
2610 if (Result.isInvalid())
2611 return StmtError();
2612 Throw = Result.take();
2613
Douglas Gregord1377b22010-04-22 21:44:01 +00002614 QualType ThrowType = Throw->getType();
2615 // Make sure the expression type is an ObjC pointer or "void *".
2616 if (!ThrowType->isDependentType() &&
2617 !ThrowType->isObjCObjectPointerType()) {
2618 const PointerType *PT = ThrowType->getAs<PointerType>();
2619 if (!PT || !PT->getPointeeType()->isVoidType())
2620 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2621 << Throw->getType() << Throw->getSourceRange());
2622 }
2623 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002624
John McCall9ae2f072010-08-23 23:25:46 +00002625 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002626}
2627
John McCall60d7b3a2010-08-24 06:29:42 +00002628StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002629Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002630 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002631 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002632 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2633
John McCall9ae2f072010-08-23 23:25:46 +00002634 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002635 // @throw without an expression designates a rethrow (which much occur
2636 // in the context of an @catch clause).
2637 Scope *AtCatchParent = CurScope;
2638 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2639 AtCatchParent = AtCatchParent->getParent();
2640 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002641 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002642 }
John McCall9ae2f072010-08-23 23:25:46 +00002643 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002644}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002645
John McCall07524032011-07-27 21:50:02 +00002646ExprResult
2647Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2648 ExprResult result = DefaultLvalueConversion(operand);
2649 if (result.isInvalid())
2650 return ExprError();
2651 operand = result.take();
2652
2653 // Make sure the expression type is an ObjC pointer or "void *".
2654 QualType type = operand->getType();
2655 if (!type->isDependentType() &&
2656 !type->isObjCObjectPointerType()) {
2657 const PointerType *pointerType = type->getAs<PointerType>();
2658 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2659 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2660 << type << operand->getSourceRange();
2661 }
2662
2663 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002664 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002665}
2666
John McCall60d7b3a2010-08-24 06:29:42 +00002667StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002668Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2669 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002670 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002671 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002672 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002673}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002674
2675/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2676/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002677StmtResult
John McCalld226f652010-08-21 09:40:31 +00002678Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002679 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002680 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002681 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002682 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002683 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002684}
Sebastian Redl8351da02008-12-22 21:35:02 +00002685
John McCallf85e1932011-06-15 23:02:42 +00002686StmtResult
2687Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2688 getCurFunction()->setHasBranchProtectedScope();
2689 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2690}
2691
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002692namespace {
2693
Sebastian Redlc447aba2009-07-29 17:15:45 +00002694class TypeWithHandler {
2695 QualType t;
2696 CXXCatchStmt *stmt;
2697public:
2698 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2699 : t(type), stmt(statement) {}
2700
John McCall0953e762009-09-24 19:53:00 +00002701 // An arbitrary order is fine as long as it places identical
2702 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002703 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002704 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002705 return true;
John McCall0953e762009-09-24 19:53:00 +00002706 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002707 return false;
2708 else
2709 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2710 }
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Sebastian Redlc447aba2009-07-29 17:15:45 +00002712 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002713 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Sebastian Redlc447aba2009-07-29 17:15:45 +00002716 CXXCatchStmt *getCatchStmt() const { return stmt; }
2717 SourceLocation getTypeSpecStartLoc() const {
2718 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2719 }
2720};
2721
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002722}
2723
Sebastian Redl8351da02008-12-22 21:35:02 +00002724/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2725/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002726StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002727Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002728 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002729 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002730 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002731 !getSourceManager().isInSystemHeader(TryLoc))
2732 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002733
Sebastian Redl8351da02008-12-22 21:35:02 +00002734 unsigned NumHandlers = RawHandlers.size();
2735 assert(NumHandlers > 0 &&
2736 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002737 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002738
Chris Lattner5f9e2722011-07-23 10:55:15 +00002739 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002740
2741 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002742 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002743 if (!Handler->getExceptionDecl()) {
2744 if (i < NumHandlers - 1)
2745 return StmtError(Diag(Handler->getLocStart(),
2746 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Sebastian Redlc447aba2009-07-29 17:15:45 +00002748 continue;
2749 }
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Sebastian Redlc447aba2009-07-29 17:15:45 +00002751 const QualType CaughtType = Handler->getCaughtType();
2752 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2753 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002754 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002755
2756 // Detect handlers for the same type as an earlier one.
2757 if (NumHandlers > 1) {
2758 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Sebastian Redlc447aba2009-07-29 17:15:45 +00002760 TypeWithHandler prev = TypesWithHandlers[0];
2761 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2762 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Sebastian Redlc447aba2009-07-29 17:15:45 +00002764 if (curr == prev) {
2765 Diag(curr.getTypeSpecStartLoc(),
2766 diag::warn_exception_caught_by_earlier_handler)
2767 << curr.getCatchStmt()->getCaughtType().getAsString();
2768 Diag(prev.getTypeSpecStartLoc(),
2769 diag::note_previous_exception_handler)
2770 << prev.getCatchStmt()->getCaughtType().getAsString();
2771 }
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Sebastian Redlc447aba2009-07-29 17:15:45 +00002773 prev = curr;
2774 }
2775 }
Mike Stump1eb44332009-09-09 15:08:12 +00002776
John McCall781472f2010-08-25 08:40:02 +00002777 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002778
Sebastian Redl8351da02008-12-22 21:35:02 +00002779 // FIXME: We should detect handlers that cannot catch anything because an
2780 // earlier handler catches a superclass. Need to find a method that is not
2781 // quadratic for this.
2782 // Neither of these are explicitly forbidden, but every compiler detects them
2783 // and warns.
2784
John McCall9ae2f072010-08-23 23:25:46 +00002785 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002786 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002787}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002788
2789StmtResult
2790Sema::ActOnSEHTryBlock(bool IsCXXTry,
2791 SourceLocation TryLoc,
2792 Stmt *TryBlock,
2793 Stmt *Handler) {
2794 assert(TryBlock && Handler);
2795
2796 getCurFunction()->setHasBranchProtectedScope();
2797
2798 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2799}
2800
2801StmtResult
2802Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2803 Expr *FilterExpr,
2804 Stmt *Block) {
2805 assert(FilterExpr && Block);
2806
2807 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002808 return StmtError(Diag(FilterExpr->getExprLoc(),
2809 diag::err_filter_expression_integral)
2810 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002811 }
2812
2813 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2814}
2815
2816StmtResult
2817Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2818 Stmt *Block) {
2819 assert(Block);
2820 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2821}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002822
2823StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2824 bool IsIfExists,
2825 NestedNameSpecifierLoc QualifierLoc,
2826 DeclarationNameInfo NameInfo,
2827 Stmt *Nested)
2828{
2829 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002830 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002831 cast<CompoundStmt>(Nested));
2832}
2833
2834
Chad Rosier1093f492012-08-10 17:56:09 +00002835StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002836 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002837 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002838 UnqualifiedId &Name,
2839 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002840 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002841 SS.getWithLocInContext(Context),
2842 GetNameFromUnqualifiedId(Name),
2843 Nested);
2844}